<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

if (!isset($_POST['consultation_id'])) {
    echo '<div class="alert alert-danger">Missing consultation ID</div>';
    exit();
}

$consultation_id = intval($_POST['consultation_id']);
$user_id = $_SESSION['user_id'];

// Get consultation details with patient and doctor information
$query = "SELECT 
    c.*,
    u.full_name as patient_name,
    p.date_of_birth,
    p.gender,
    p.phone_number,
    p.email,
    p.blood_group,
    p.allergies,
    p.chronic_conditions,
    doc_user.full_name as doctor_name,
    d.specialization,
    d.medical_license
FROM consultations c
INNER JOIN patients p ON c.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
INNER JOIN doctors d ON c.doctor_id = d.doctor_id
INNER JOIN users doc_user ON d.user_id = doc_user.user_id
WHERE c.consultation_id = ? 
AND (c.doctor_id = ? OR ? IN (SELECT user_id FROM users WHERE role_code IN ('SUPER_ADMIN', 'HOSPITAL_ADMIN')))";

$stmt = $conn->prepare($query);
$stmt->bind_param("iii", $consultation_id, $user_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo '<div class="alert alert-danger">Consultation not found or access denied</div>';
    exit();
}

$consultation = $result->fetch_assoc();

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

// Get vital signs
$vitals_query = "SELECT * FROM vital_signs WHERE consultation_id = ? ORDER BY recorded_at DESC LIMIT 1";
$vitals_stmt = $conn->prepare($vitals_query);
$vitals_stmt->bind_param("i", $consultation_id);
$vitals_stmt->execute();
$vitals_result = $vitals_stmt->get_result();
$vitals = $vitals_result->fetch_assoc();

// Get prescriptions
$prescriptions_query = "SELECT 
    pr.*,
    m.medication_name,
    m.strength,
    m.form
FROM prescriptions pr
LEFT JOIN medications m ON pr.medication_id = m.medication_id
WHERE pr.consultation_id = ?
ORDER BY pr.created_at DESC";
$prescriptions_stmt = $conn->prepare($prescriptions_query);
$prescriptions_stmt->bind_param("i", $consultation_id);
$prescriptions_stmt->execute();
$prescriptions_result = $prescriptions_stmt->get_result();

// Get lab orders
$lab_orders_query = "SELECT 
    lo.*,
    ett.test_name,
    ett.category,
    u.full_name as ordered_by_name
FROM lab_orders lo
INNER JOIN ent_test_types ett ON lo.test_type_id = ett.test_type_id
INNER JOIN users u ON lo.ordered_by = u.user_id
WHERE lo.consultation_id = ?
ORDER BY lo.order_date DESC";
$lab_orders_stmt = $conn->prepare($lab_orders_query);
$lab_orders_stmt->bind_param("i", $consultation_id);
$lab_orders_stmt->execute();
$lab_orders_result = $lab_orders_stmt->get_result();

// Get procedures
$procedures_query = "SELECT 
    mp.*,
    ept.procedure_name,
    ept.category,
    perf_user.full_name as performed_by_name
FROM medical_procedures mp
INNER JOIN ent_procedure_types ept ON mp.procedure_type_id = ept.procedure_type_id
LEFT JOIN users perf_user ON mp.performed_by = perf_user.user_id
WHERE mp.consultation_id = ?
ORDER BY mp.scheduled_date DESC";
$procedures_stmt = $conn->prepare($procedures_query);
$procedures_stmt->bind_param("i", $consultation_id);
$procedures_stmt->execute();
$procedures_result = $procedures_stmt->get_result();
?>

<div class="row">
    <!-- Patient Information -->
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h6 class="mb-0"><i class="ri-user-line me-2"></i>Patient Information</h6>
            </div>
            <div class="card-body">
                <table class="table table-sm table-borderless">
                    <tr>
                        <td class="fw-bold">Name:</td>
                        <td><?php echo htmlspecialchars($consultation['patient_name']); ?></td>
                    </tr>
                    <tr>
                        <td class="fw-bold">Age:</td>
                        <td><?php echo $age; ?> years</td>
                    </tr>
                    <tr>
                        <td class="fw-bold">Gender:</td>
                        <td><?php echo htmlspecialchars($consultation['gender']); ?></td>
                    </tr>
                    <tr>
                        <td class="fw-bold">Phone:</td>
                        <td><?php echo htmlspecialchars($consultation['phone_number']); ?></td>
                    </tr>
                    <tr>
                        <td class="fw-bold">Email:</td>
                        <td><?php echo htmlspecialchars($consultation['email']); ?></td>
                    </tr>
                    <tr>
                        <td class="fw-bold">Blood Group:</td>
                        <td><?php echo htmlspecialchars($consultation['blood_group'] ?: 'N/A'); ?></td>
                    </tr>
                </table>
                
                <?php if ($consultation['allergies']): ?>
                <div class="alert alert-warning py-2 mb-2">
                    <strong>Allergies:</strong><br>
                    <?php echo nl2br(htmlspecialchars($consultation['allergies'])); ?>
                </div>
                <?php endif; ?>
                
                <?php if ($consultation['chronic_conditions']): ?>
                <div class="alert alert-info py-2 mb-0">
                    <strong>Chronic Conditions:</strong><br>
                    <?php echo nl2br(htmlspecialchars($consultation['chronic_conditions'])); ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Consultation Details -->
    <div class="col-md-8 mb-3">
        <div class="card">
            <div class="card-header bg-success text-white">
                <h6 class="mb-0"><i class="ri-file-text-line me-2"></i>Consultation Details</h6>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <p class="mb-1"><strong>Date:</strong> <?php echo date('M d, Y h:i A', strtotime($consultation['consultation_date'])); ?></p>
                        <p class="mb-1"><strong>Type:</strong> 
                            <span class="badge bg-<?php echo ($consultation['consultation_type'] == 'NEW') ? 'primary' : 'info'; ?>">
                                <?php echo htmlspecialchars($consultation['consultation_type']); ?>
                            </span>
                        </p>
                        <p class="mb-1"><strong>Status:</strong> 
                            <span class="badge bg-<?php 
                                echo ($consultation['status'] == 'COMPLETED') ? 'success' : 
                                     (($consultation['status'] == 'IN_PROGRESS') ? 'warning' : 'secondary');
                            ?>">
                                <?php echo htmlspecialchars($consultation['status']); ?>
                            </span>
                        </p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1"><strong>Doctor:</strong> <?php echo htmlspecialchars($consultation['doctor_name']); ?></p>
                        <p class="mb-1"><strong>Specialization:</strong> <?php echo htmlspecialchars($consultation['specialization']); ?></p>
                        <p class="mb-1"><strong>License:</strong> <?php echo htmlspecialchars($consultation['medical_license']); ?></p>
                    </div>
                </div>
                
                <hr>
                
                <div class="row">
                    <div class="col-12 mb-3">
                        <h6 class="text-primary">Chief Complaint</h6>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($consultation['chief_complaint'] ?: 'N/A')); ?></p>
                    </div>
                    
                    <div class="col-12 mb-3">
                        <h6 class="text-primary">History of Present Illness</h6>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($consultation['history_of_present_illness'] ?: 'N/A')); ?></p>
                    </div>
                    
                    <div class="col-12 mb-3">
                        <h6 class="text-primary">Physical Examination</h6>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($consultation['physical_examination'] ?: 'N/A')); ?></p>
                    </div>
                    
                    <div class="col-12 mb-3">
                        <h6 class="text-primary">Diagnosis</h6>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($consultation['diagnosis'] ?: 'N/A')); ?></p>
                    </div>
                    
                    <div class="col-12 mb-3">
                        <h6 class="text-primary">Treatment Plan</h6>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($consultation['treatment_plan'] ?: 'N/A')); ?></p>
                    </div>
                    
                    <?php if ($consultation['follow_up_date']): ?>
                    <div class="col-12">
                        <div class="alert alert-info py-2">
                            <strong>Follow-up Date:</strong> <?php echo date('M d, Y', strtotime($consultation['follow_up_date'])); ?>
                            <?php if ($consultation['follow_up_instructions']): ?>
                            <br><strong>Instructions:</strong> <?php echo nl2br(htmlspecialchars($consultation['follow_up_instructions'])); ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Vital Signs -->
<?php if ($vitals): ?>
<div class="row mb-3">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-info text-white">
                <h6 class="mb-0"><i class="ri-heart-pulse-line me-2"></i>Vital Signs</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <p class="mb-1"><strong>Blood Pressure:</strong> <?php echo htmlspecialchars($vitals['blood_pressure'] ?: 'N/A'); ?> mmHg</p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>Heart Rate:</strong> <?php echo htmlspecialchars($vitals['heart_rate'] ?: 'N/A'); ?> bpm</p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>Temperature:</strong> <?php echo htmlspecialchars($vitals['temperature'] ?: 'N/A'); ?> °C</p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>Respiratory Rate:</strong> <?php echo htmlspecialchars($vitals['respiratory_rate'] ?: 'N/A'); ?> /min</p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>Weight:</strong> <?php echo htmlspecialchars($vitals['weight'] ?: 'N/A'); ?> kg</p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>Height:</strong> <?php echo htmlspecialchars($vitals['height'] ?: 'N/A'); ?> cm</p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>BMI:</strong> <?php echo htmlspecialchars($vitals['bmi'] ?: 'N/A'); ?></p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>SpO2:</strong> <?php echo htmlspecialchars($vitals['oxygen_saturation'] ?: 'N/A'); ?> %</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Prescriptions -->
<?php if ($prescriptions_result->num_rows > 0): ?>
<div class="row mb-3">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-warning text-dark">
                <h6 class="mb-0"><i class="ri-medicine-bottle-line me-2"></i>Prescriptions</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Medication</th>
                                <th>Dosage</th>
                                <th>Frequency</th>
                                <th>Duration</th>
                                <th>Instructions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($prescription = $prescriptions_result->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($prescription['medication_name'] . ' ' . $prescription['strength'] . ' ' . $prescription['form']); ?></td>
                                <td><?php echo htmlspecialchars($prescription['dosage']); ?></td>
                                <td><?php echo htmlspecialchars($prescription['frequency']); ?></td>
                                <td><?php echo htmlspecialchars($prescription['duration']); ?></td>
                                <td><?php echo htmlspecialchars($prescription['instructions'] ?: '-'); ?></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Lab Orders -->
<?php if ($lab_orders_result->num_rows > 0): ?>
<div class="row mb-3">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-secondary text-white">
                <h6 class="mb-0"><i class="ri-flask-line me-2"></i>Lab Orders</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Test Name</th>
                                <th>Category</th>
                                <th>Order Date</th>
                                <th>Ordered By</th>
                                <th>Status</th>
                                <th>Priority</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($lab_order = $lab_orders_result->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($lab_order['test_name']); ?></td>
                                <td><?php echo htmlspecialchars($lab_order['category']); ?></td>
                                <td><?php echo date('M d, Y', strtotime($lab_order['order_date'])); ?></td>
                                <td><?php echo htmlspecialchars($lab_order['ordered_by_name']); ?></td>
                                <td>
                                    <span class="badge bg-<?php 
                                        echo ($lab_order['status'] == 'COMPLETED') ? 'success' : 
                                             (($lab_order['status'] == 'IN_PROGRESS') ? 'warning' : 'secondary');
                                    ?>">
                                        <?php echo htmlspecialchars($lab_order['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-<?php echo ($lab_order['priority'] == 'URGENT') ? 'danger' : 'info'; ?>">
                                        <?php echo htmlspecialchars($lab_order['priority']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Procedures -->
<?php if ($procedures_result->num_rows > 0): ?>
<div class="row mb-3">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-danger text-white">
                <h6 class="mb-0"><i class="ri-surgical-mask-line me-2"></i>Procedures</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Procedure</th>
                                <th>Category</th>
                                <th>Scheduled Date</th>
                                <th>Performed By</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($procedure = $procedures_result->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($procedure['procedure_name']); ?></td>
                                <td><?php echo htmlspecialchars($procedure['category']); ?></td>
                                <td><?php echo date('M d, Y', strtotime($procedure['scheduled_date'])); ?></td>
                                <td><?php echo htmlspecialchars($procedure['performed_by_name'] ?: 'Not assigned'); ?></td>
                                <td>
                                    <span class="badge bg-<?php 
                                        echo ($procedure['status'] == 'COMPLETED') ? 'success' : 
                                             (($procedure['status'] == 'IN_PROGRESS') ? 'warning' : 'secondary');
                                    ?>">
                                        <?php echo htmlspecialchars($procedure['status']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php
$conn->close();
?>