<?php
require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$consultation_id = isset($_GET['id']) ? $_GET['id'] : 0;

if (!$consultation_id) {
    die("Invalid Consultation ID");
}

// Determine if the ID is numeric (consultation_id) or string (consultation_number)
$is_numeric = is_numeric($consultation_id);

// Fetch consultation details with patient and doctor info
if ($is_numeric) {
    // Query by consultation_id
    $sql = "SELECT 
        c.*,
        p.patient_number,
        p.insurance_number,
        u_pat.full_name as patient_name,
        u_pat.date_of_birth,
        u_pat.gender,
        u_pat.phone_primary as patient_phone,
        u_doc.full_name as doctor_name,
        pv.visit_number,
        pv.registration_date as visit_date
    FROM consultations c
    JOIN patients p ON c.patient_id = p.patient_id
    JOIN users u_pat ON p.user_id = u_pat.user_id
    JOIN doctors d ON c.doctor_id = d.doctor_id
    JOIN users u_doc ON d.user_id = u_doc.user_id
    JOIN patient_visits pv ON c.visit_id = pv.visit_id
    WHERE c.consultation_id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $consultation_id);
} else {
    // Query by consultation_number
    $sql = "SELECT 
        c.*,
        p.patient_number,
        p.insurance_number,
        u_pat.full_name as patient_name,
        u_pat.date_of_birth,
        u_pat.gender,
        u_pat.phone_primary as patient_phone,
        u_doc.full_name as doctor_name,
        pv.visit_number,
        pv.registration_date as visit_date
    FROM consultations c
    JOIN patients p ON c.patient_id = p.patient_id
    JOIN users u_pat ON p.user_id = u_pat.user_id
    JOIN doctors d ON c.doctor_id = d.doctor_id
    JOIN users u_doc ON d.user_id = u_doc.user_id
    JOIN patient_visits pv ON c.visit_id = pv.visit_id
    WHERE c.consultation_number = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $consultation_id);
}

$stmt->execute();
$result = $stmt->get_result();
$consultation = $result->fetch_assoc();

if (!$consultation) {
    die("Consultation not found");
}

// Helper function to decode JSON safely
function safe_json_decode($json)
{
    if (empty($json)) {
        return [];
    }
    $decoded = json_decode($json, true);
    return (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
}

// Decode JSON fields
$ear_exam = safe_json_decode($consultation['ear_examination']);
$nose_exam = safe_json_decode($consultation['nose_examination']);
$throat_exam = safe_json_decode($consultation['throat_examination']);
$neck_exam = safe_json_decode($consultation['neck_examination']);
$cranial_nerves = safe_json_decode($consultation['cranial_nerves']);
$vital_signs = safe_json_decode($consultation['vital_signs']);
$medications = safe_json_decode($consultation['medications_prescribed']);
$procedures = safe_json_decode($consultation['procedures_recommended']);
$investigations = safe_json_decode($consultation['investigations_ordered']);
$referrals = safe_json_decode($consultation['referrals']);

// Calculate Age
$dob = new DateTime($consultation['date_of_birth']);
$now = new DateTime();
$age = $now->diff($dob)->y;
?>

<!DOCTYPE html>
<html>
    
<?php include 'layouts/main.php'; ?>    

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Consultation Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .section-title {
            border-bottom: 2px solid #f3f4f6;
            padding-bottom: 0.5rem;
            margin-bottom: 1rem;
            color: #4b5563;
            font-weight: 600;
        }

        .info-label {
            color: #6b7280;
            font-size: 0.875rem;
            font-weight: 500;
        }

        .info-value {
            color: #111827;
            font-weight: 500;
        }

        .exam-box {
            background: #f9fafb;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }

        .exam-box h6 {
            color: #667eea;
            font-weight: 600;
            margin-bottom: 0.75rem;
            border-bottom: 1px solid #e5e7eb;
            padding-bottom: 0.5rem;
        }

        .exam-item {
            margin-bottom: 0.5rem;
            padding: 0.5rem;
            background: white;
            border-radius: 4px;
        }

        .exam-item small {
            color: #6b7280;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75rem;
        }

        @media print {
            .no-print {
                display: none !important;
            }

            .card {
                border: none !important;
                shadow: none !important;
            }

            .main-content {
                margin-left: 0 !important;
            }

            .page-content {
                padding: 0 !important;
            }
            
            .exam-box {
                page-break-inside: avoid;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <!-- Page Header -->
                    <div class="row no-print">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Consultation Details</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_consultations.php">Consultations</a></li>
                                        <li class="breadcrumb-item active"><?php echo $consultation['consultation_number']; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header border-bottom-dashed p-4" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <img src="assets/images/prodigy.png" class="card-logo card-logo-dark" alt="logo" height="40" style="filter: brightness(0) invert(1);">
                                            <div class="mt-2 text-white">
                                                <h5 class="mb-0 text-white">ENT Consultation Report</h5>
                                                <small class="text-white-50">ID: <?php echo $consultation['consultation_number']; ?></small>
                                            </div>
                                        </div>
                                        <div class="text-end text-white">
                                            <h6 class="mb-1 text-white">Date: <?php echo date('d M, Y', strtotime($consultation['created_at'])); ?></h6>
                                            <span class="badge <?php echo $consultation['status'] == 'COMPLETED' ? 'bg-success' : 'bg-warning'; ?>">
                                                <?php echo $consultation['status']; ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body p-4">
                                    <div class="row g-3">
                                        <!-- Patient Info -->
                                        <div class="col-md-6 border-end">
                                            <h6 class="text-muted text-uppercase fw-semibold mb-3">Patient Details</h6>
                                            <p class="mb-1"><strong>Name:</strong> <?php echo htmlspecialchars($consultation['patient_name']); ?></p>
                                            <p class="mb-1"><strong>Patient ID:</strong> <?php echo $consultation['patient_number']; ?></p>
                                            <p class="mb-1"><strong>Age/Gender:</strong> <?php echo $age; ?> Years / <?php echo $consultation['gender']; ?></p>
                                            <p class="mb-0"><strong>Phone:</strong> <?php echo htmlspecialchars($consultation['patient_phone']); ?></p>
                                        </div>
                                        <!-- Doctor Info -->
                                        <div class="col-md-6 ps-md-4">
                                            <h6 class="text-muted text-uppercase fw-semibold mb-3">Attending Physician</h6>
                                            <p class="mb-1"><strong>Doctor:</strong> <?php echo htmlspecialchars($consultation['doctor_name']); ?></p>
                                            <p class="mb-1"><strong>Visit #:</strong> <?php echo $consultation['visit_number']; ?></p>
                                            <p class="mb-0"><strong>Type:</strong> <?php echo $consultation['consultation_type']; ?></p>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body p-4 border-top border-top-dashed">
                                    <div class="row">
                                        <!-- Left Column: Complaints, History, Exam -->
                                        <div class="col-md-6">
                                            <div class="mb-4">
                                                <h5 class="section-title">Chief Complaint</h5>
                                                <p><?php echo nl2br(htmlspecialchars($consultation['chief_complaint'])); ?></p>
                                            </div>

                                            <div class="mb-4">
                                                <h5 class="section-title">Medical History</h5>
                                                <?php if ($consultation['history_present_illness']): ?>
                                                    <div class="mb-2"><strong>HPI:</strong> <?php echo nl2br(htmlspecialchars($consultation['history_present_illness'])); ?></div>
                                                <?php endif; ?>
                                                <?php if ($consultation['past_medical_history']): ?>
                                                    <div class="mb-2"><strong>PMH:</strong> <?php echo nl2br(htmlspecialchars($consultation['past_medical_history'])); ?></div>
                                                <?php endif; ?>
                                                <?php if ($consultation['family_history']): ?>
                                                    <div class="mb-2"><strong>Family Hx:</strong> <?php echo nl2br(htmlspecialchars($consultation['family_history'])); ?></div>
                                                <?php endif; ?>
                                                <?php if ($consultation['social_history']): ?>
                                                    <div class="mb-2"><strong>Social Hx:</strong> <?php echo nl2br(htmlspecialchars($consultation['social_history'])); ?></div>
                                                <?php endif; ?>
                                            </div>

                                            <div class="mb-4">
                                                <h5 class="section-title">Examination Findings</h5>

                                                <?php if (!empty($ear_exam)): ?>
                                                    <div class="exam-box">
                                                        <h6>👂 Ear Examination</h6>
                                                        <?php foreach ($ear_exam as $k => $v): if ($v): ?>
                                                            <div class="exam-item">
                                                                <small><?php echo ucwords(str_replace('_', ' ', $k)); ?>:</small><br>
                                                                <span><?php echo htmlspecialchars($v); ?></span>
                                                            </div>
                                                        <?php endif; endforeach; ?>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if (!empty($nose_exam)): ?>
                                                    <div class="exam-box">
                                                        <h6>👃 Nose Examination</h6>
                                                        <?php foreach ($nose_exam as $k => $v): if ($v): ?>
                                                            <div class="exam-item">
                                                                <small><?php echo ucwords(str_replace('_', ' ', $k)); ?>:</small><br>
                                                                <span><?php echo htmlspecialchars($v); ?></span>
                                                            </div>
                                                        <?php endif; endforeach; ?>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if (!empty($throat_exam)): ?>
                                                    <div class="exam-box">
                                                        <h6>🗣️ Throat Examination</h6>
                                                        <?php foreach ($throat_exam as $k => $v): if ($v): ?>
                                                            <div class="exam-item">
                                                                <small><?php echo ucwords(str_replace('_', ' ', $k)); ?>:</small><br>
                                                                <span><?php echo htmlspecialchars($v); ?></span>
                                                            </div>
                                                        <?php endif; endforeach; ?>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if (!empty($neck_exam)): ?>
                                                    <div class="exam-box">
                                                        <h6>🔍 Neck Examination</h6>
                                                        <?php foreach ($neck_exam as $k => $v): if ($v): ?>
                                                            <div class="exam-item">
                                                                <small><?php echo ucwords(str_replace('_', ' ', $k)); ?>:</small><br>
                                                                <span><?php echo htmlspecialchars($v); ?></span>
                                                            </div>
                                                        <?php endif; endforeach; ?>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if (!empty($cranial_nerves)): ?>
                                                    <div class="exam-box">
                                                        <h6>🧠 Cranial Nerves</h6>
                                                        <?php foreach ($cranial_nerves as $k => $v): if ($v): ?>
                                                            <div class="exam-item">
                                                                <small><?php echo ucwords(str_replace('_', ' ', $k)); ?>:</small><br>
                                                                <span><?php echo htmlspecialchars($v); ?></span>
                                                            </div>
                                                        <?php endif; endforeach; ?>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if ($consultation['general_examination']): ?>
                                                    <div class="exam-box">
                                                        <h6>📋 General Examination</h6>
                                                        <div class="exam-item">
                                                            <?php echo nl2br(htmlspecialchars($consultation['general_examination'])); ?>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <!-- Right Column: Diagnosis, Plan, Rx -->
                                        <div class="col-md-6 border-start ps-md-4">
                                            <div class="mb-4">
                                                <h5 class="section-title">Diagnosis</h5>
                                                <div class="mb-2">
                                                    <span class="badge bg-primary fs-6 me-2">Primary</span>
                                                    <span class="fs-5"><?php echo htmlspecialchars($consultation['diagnosis_primary']); ?></span>
                                                </div>
                                                <?php if ($consultation['diagnosis_secondary']): ?>
                                                    <div class="mb-2">
                                                        <span class="badge bg-secondary me-2">Secondary</span>
                                                        <span><?php echo htmlspecialchars($consultation['diagnosis_secondary']); ?></span>
                                                    </div>
                                                <?php endif; ?>
                                                <?php if ($consultation['differential_diagnosis']): ?>
                                                    <div class="mt-2">
                                                        <small class="text-muted">Differential:</small>
                                                        <p><?php echo nl2br(htmlspecialchars($consultation['differential_diagnosis'])); ?></p>
                                                    </div>
                                                <?php endif; ?>
                                            </div>

                                            <div class="mb-4">
                                                <h5 class="section-title">Treatment Plan</h5>
                                                <p><?php echo nl2br(htmlspecialchars($consultation['treatment_plan'])); ?></p>
                                            </div>

                                            <?php if (!empty($medications)): ?>
                                                <div class="mb-4">
                                                    <h5 class="section-title">💊 Prescriptions</h5>
                                                    <div class="table-responsive">
                                                        <table class="table table-sm table-bordered">
                                                            <thead class="table-light">
                                                                <tr>
                                                                    <th>Medication</th>
                                                                    <th>Dosage</th>
                                                                    <th>Freq</th>
                                                                    <th>Dur</th>
                                                                    <th>Qty</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php foreach ($medications as $med): ?>
                                                                    <tr>
                                                                        <td><?php echo htmlspecialchars($med['name'] ?? ''); ?></td>
                                                                        <td><?php echo htmlspecialchars($med['dosage'] ?? ''); ?></td>
                                                                        <td><?php echo htmlspecialchars($med['frequency'] ?? ''); ?></td>
                                                                        <td><?php echo htmlspecialchars($med['duration'] ?? ''); ?></td>
                                                                        <td><?php echo htmlspecialchars($med['quantity'] ?? ''); ?></td>
                                                                    </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            <?php endif; ?>

                                            <?php if (!empty($procedures) || !empty($investigations) || !empty($referrals)): ?>
                                                <div class="mb-4">
                                                    <h5 class="section-title">Orders & Referrals</h5>

                                                    <?php if (!empty($investigations)): ?>
                                                        <div class="mb-3">
                                                            <strong>🔬 Investigations:</strong>
                                                            <ul class="mt-2">
                                                                <?php foreach ($investigations as $inv): ?>
                                                                    <li><?php echo htmlspecialchars(is_string($inv) ? $inv : ($inv['test'] ?? '')); ?></li>
                                                                <?php endforeach; ?>
                                                            </ul>
                                                        </div>
                                                    <?php endif; ?>

                                                    <?php if (!empty($procedures)): ?>
                                                        <div class="mb-3">
                                                            <strong>⚕️ Procedures:</strong>
                                                            <ul class="mt-2">
                                                                <?php foreach ($procedures as $proc): ?>
                                                                    <li><?php echo htmlspecialchars(is_string($proc) ? $proc : ($proc['procedure'] ?? '')); ?></li>
                                                                <?php endforeach; ?>
                                                            </ul>
                                                        </div>
                                                    <?php endif; ?>

                                                    <?php if (!empty($referrals)): ?>
                                                        <div class="mb-3">
                                                            <strong>👨‍⚕️ Referrals:</strong>
                                                            <ul class="mt-2">
                                                                <?php foreach ($referrals as $ref): ?>
                                                                    <li><?php echo htmlspecialchars(is_string($ref) ? $ref : ($ref['specialist'] ?? '')); ?></li>
                                                                <?php endforeach; ?>
                                                            </ul>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>

                                            <?php if ($consultation['follow_up_instructions'] || $consultation['next_appointment']): ?>
                                                <div class="alert alert-info">
                                                    <h6 class="alert-heading fw-bold"><i class="ri-calendar-event-line me-1"></i> Follow-up</h6>
                                                    <?php if ($consultation['follow_up_instructions']): ?>
                                                        <p class="mb-1"><?php echo nl2br(htmlspecialchars($consultation['follow_up_instructions'])); ?></p>
                                                    <?php endif; ?>
                                                    <?php if ($consultation['next_appointment']): ?>
                                                        <hr>
                                                        <p class="mb-0"><strong>Next Appointment:</strong> <?php echo date('d M, Y', strtotime($consultation['next_appointment'])); ?></p>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>

                                            <?php if ($consultation['doctor_notes']): ?>
                                                <div class="alert alert-secondary">
                                                    <h6 class="alert-heading fw-bold">📝 Doctor's Notes</h6>
                                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($consultation['doctor_notes'])); ?></p>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-footer p-4 border-top no-print text-end" style="background: #f8f9fa;">
                                    <a href="list_consultations.php" class="btn btn-outline-secondary me-2">
                                        <i class="ri-arrow-left-line me-1"></i> Back to List
                                    </a>
                                    <a href="javascript:window.print()" class="btn btn-primary">
                                        <i class="ri-printer-line me-1"></i> Print Report
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>

</html>