<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_code'];

// Get patient ID and queue ID from URL
$patient_id = $_GET['id'] ?? 0;
$queue_id = $_GET['queue_id'] ?? 0;

if (empty($patient_id)) {
    header('Location: queue_dashboard.php');
    exit();
}

// Fetch comprehensive patient information
$patient_sql = "SELECT 
    p.patient_id, p.patient_number, p.registration_type, p.insurance_provider_id, p.insurance_number,
    p.blood_group, p.allergies, p.chronic_conditions, p.current_medications, p.ent_history,
    u.full_name, u.email, u.phone_primary, u.phone_secondary, u.date_of_birth, u.gender,
    u.national_id, u.address, u.emergency_contact_name, u.emergency_contact_phone,
    ip.provider_name as insurance_provider,
    TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age
FROM patients p
INNER JOIN users u ON p.user_id = u.user_id
LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
WHERE p.patient_id = ?";

$stmt = $conn->prepare($patient_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$patient_result = $stmt->get_result();

if ($patient_result->num_rows === 0) {
    header('Location: queue_dashboard.php');
    exit();
}

$patient = $patient_result->fetch_assoc();

// Get active queue information if queue_id provided
$queue_data = null;
if ($queue_id) {
    $queue_sql = "SELECT q.*, d.department_name, d.department_id
                  FROM patient_queue q
                  INNER JOIN departments d ON q.department_id = d.department_id
                  WHERE q.queue_id = ? AND q.patient_id = ?";
    $stmt = $conn->prepare($queue_sql);
    $stmt->bind_param("ii", $queue_id, $patient_id);
    $stmt->execute();
    $queue_result = $stmt->get_result();
    if ($queue_result->num_rows > 0) {
        $queue_data = $queue_result->fetch_assoc();
    }
}

// Get current visit or create one if doesn't exist
$visit_sql = "SELECT * FROM patient_visits 
              WHERE patient_id = ? 
              AND status = 'ACTIVE' 
              AND DATE(registration_date) = CURDATE()
              ORDER BY registration_date DESC LIMIT 1";
$stmt = $conn->prepare($visit_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$visit_result = $stmt->get_result();

if ($visit_result->num_rows > 0) {
    $current_visit = $visit_result->fetch_assoc();
} else {
    // Check if there's any active visit (from previous days)
    $any_active_sql = "SELECT * FROM patient_visits 
                       WHERE patient_id = ? AND status = 'ACTIVE' 
                       ORDER BY registration_date DESC LIMIT 1";
    $stmt = $conn->prepare($any_active_sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $any_active_result = $stmt->get_result();
    
    if ($any_active_result->num_rows > 0) {
        $current_visit = $any_active_result->fetch_assoc();
    } else {
        // Create a new visit if none exists
        try {
            $count_sql = "SELECT COUNT(*) as count FROM patient_visits WHERE DATE(registration_date) = CURDATE()";
            $count_result = $conn->query($count_sql);
            $count = $count_result->fetch_assoc()['count'];
            
            $visit_number = 'VST-' . date('Ymd') . '-' . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
            
            // Check for duplicate
            $check_sql = "SELECT visit_id FROM patient_visits WHERE visit_number = ?";
            $stmt = $conn->prepare($check_sql);
            $stmt->bind_param("s", $visit_number);
            $stmt->execute();
            
            if ($stmt->get_result()->num_rows > 0) {
                // Use timestamp if duplicate
                $visit_number = 'VST-' . date('Ymd') . '-' . time() . '-' . $patient_id;
            }
            
            $create_visit_sql = "INSERT INTO patient_visits (visit_number, patient_id, visit_type, registration_date, status, created_at)
                                VALUES (?, ?, 'OUT_PATIENT', NOW(), 'ACTIVE', NOW())";
            $stmt = $conn->prepare($create_visit_sql);
            $stmt->bind_param("si", $visit_number, $patient_id);
            
            if ($stmt->execute()) {
                $new_visit_id = $conn->insert_id;
                // Fetch the newly created visit
                $stmt = $conn->prepare($visit_sql);
                $stmt->bind_param("i", $patient_id);
                $stmt->execute();
                $current_visit = $stmt->get_result()->fetch_assoc();
            } else {
                $current_visit = ['visit_id' => null]; // Fallback
            }
        } catch (Exception $e) {
            $current_visit = ['visit_id' => null]; // Fallback on error
        }
    }
}

// Get vital signs history (last 5)
$vitals_sql = "SELECT v.*, u.full_name as recorded_by_name
               FROM vital_signs v
               LEFT JOIN users u ON v.recorded_by = u.user_id
               WHERE v.patient_id = ?
               ORDER BY v.recorded_date DESC
               LIMIT 5";
$stmt = $conn->prepare($vitals_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$vitals_result = $stmt->get_result();

// Get consultation history
$consultations_sql = "SELECT c.*, u.full_name as doctor_name, d.specialization
                      FROM consultations c
                      INNER JOIN doctors d ON c.doctor_id = d.doctor_id
                      INNER JOIN users u ON d.user_id = u.user_id
                      WHERE c.patient_id = ?
                      ORDER BY c.started_at DESC
                      LIMIT 5";
$stmt = $conn->prepare($consultations_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$consultations_result = $stmt->get_result();

// Get active prescriptions
$prescriptions_sql = "SELECT pr.*, u.full_name as doctor_name
                      FROM prescriptions pr
                      INNER JOIN users u ON pr.doctor_id = u.user_id
                      WHERE pr.patient_id = ? AND pr.status = 'ACTIVE'
                      ORDER BY pr.prescribed_date DESC";
$stmt = $conn->prepare($prescriptions_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$prescriptions_result = $stmt->get_result();

// Get available departments for routing
$departments_sql = "SELECT * FROM departments WHERE is_active = 1 ORDER BY display_order";
$departments_result = $conn->query($departments_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .patient-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .patient-avatar-lg {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: white;
            color: #667eea;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 3rem;
            font-weight: 700;
            margin-right: 2rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
        }
        
        .info-card-header {
            padding-bottom: 1rem;
            margin-bottom: 1rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .info-card-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
            margin-bottom: 0.25rem;
        }
        
        .info-value {
            font-size: 1rem;
            color: #1e293b;
            font-weight: 600;
        }
        
        .alert-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            background: #fee2e2;
            color: #991b1b;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .nav-pills .nav-link {
            border-radius: 8px;
            padding: 0.75rem 1.5rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .nav-pills .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .vital-card {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .vital-card .vital-label {
            font-size: 0.875rem;
            color: #64748b;
            margin-bottom: 0.25rem;
        }
        
        .vital-card .vital-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .vital-card .vital-unit {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: normal;
        }
        
        .history-timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .history-timeline::before {
            content: '';
            position: absolute;
            left: 0.5rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }
        
        .history-item {
            position: relative;
            padding-bottom: 1.5rem;
        }
        
        .history-item::before {
            content: '';
            position: absolute;
            left: -1.5rem;
            top: 0.5rem;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #667eea;
            border: 2px solid white;
            box-shadow: 0 0 0 2px #667eea;
        }
        
        .history-date {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .history-title {
            font-weight: 600;
            color: #1e293b;
            margin: 0.25rem 0;
        }
        
        .history-description {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .medication-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
        }
        
        .medication-name {
            font-weight: 600;
            color: #1e293b;
            font-size: 1rem;
        }
        
        .medication-details {
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.5rem;
        }
        
        .action-button {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .action-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
        
        .search-medicine-box {
            position: relative;
        }
        
        .medicine-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            display: none;
        }
        
        .medicine-results.show {
            display: block;
        }
        
        .medicine-result-item {
            padding: 1rem;
            border-bottom: 1px solid #e2e8f0;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .medicine-result-item:hover {
            background: #f8fafc;
        }
        
        .medicine-result-name {
            font-weight: 600;
            color: #1e293b;
        }
        
        .medicine-result-details {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .prescription-list {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .prescription-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            position: relative;
        }
        
        .remove-prescription {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            background: #fee2e2;
            color: #991b1b;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
        
        .empty-state i {
            font-size: 3rem;
            opacity: 0.3;
            margin-bottom: 1rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Patient Header -->
                    <div class="patient-header">
                        <div class="d-flex align-items-center">
                            <div class="patient-avatar-lg">
                                <?php echo strtoupper(substr($patient['full_name'], 0, 1)); ?>
                            </div>
                            <div class="flex-grow-1">
                                <h2 class="mb-2"><?php echo htmlspecialchars($patient['full_name']); ?></h2>
                                <div class="d-flex gap-4 flex-wrap">
                                    <div>
                                        <i class="ri-user-line me-1"></i>
                                        <strong><?php echo $patient['patient_number']; ?></strong>
                                    </div>
                                    <div>
                                        <i class="ri-calendar-line me-1"></i>
                                        <?php echo $patient['age']; ?> Years • <?php echo $patient['gender']; ?>
                                    </div>
                                    <div>
                                        <i class="ri-phone-line me-1"></i>
                                        <?php echo $patient['phone_primary']; ?>
                                    </div>
                                    <?php if ($patient['insurance_provider']): ?>
                                    <div>
                                        <i class="ri-shield-line me-1"></i>
                                        <?php echo $patient['insurance_provider']; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php if ($queue_data): ?>
                                <div class="mt-3">
                                    <span class="badge bg-light text-dark">
                                        Current Queue: <?php echo $queue_data['queue_number']; ?> - 
                                        <?php echo $queue_data['department_name']; ?>
                                    </span>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div>
                                <a href="queue_dashboard.php" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i> Back to Queue
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Medical Alerts -->
                    <?php if ($patient['allergies'] || $patient['chronic_conditions']): ?>
                    <div class="alert alert-danger border-0 mb-4" role="alert">
                        <h5 class="alert-heading">
                            <i class="ri-alert-line me-2"></i>Medical Alerts
                        </h5>
                        <?php if ($patient['allergies']): ?>
                        <div class="mb-2">
                            <strong>Allergies:</strong> <?php echo htmlspecialchars($patient['allergies']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if ($patient['chronic_conditions']): ?>
                        <div>
                            <strong>Chronic Conditions:</strong> <?php echo htmlspecialchars($patient['chronic_conditions']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <!-- Navigation Tabs -->
                    <ul class="nav nav-pills mb-4" id="patientTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="overview-tab" data-bs-toggle="pill" 
                                    data-bs-target="#overview" type="button" role="tab">
                                <i class="ri-dashboard-line me-1"></i> Overview
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="vitals-tab" data-bs-toggle="pill" 
                                    data-bs-target="#vitals" type="button" role="tab">
                                <i class="ri-heart-pulse-line me-1"></i> Vital Signs
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="history-tab" data-bs-toggle="pill" 
                                    data-bs-target="#history" type="button" role="tab">
                                <i class="ri-file-list-3-line me-1"></i> ENT History
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="prescriptions-tab" data-bs-toggle="pill" 
                                    data-bs-target="#prescriptions" type="button" role="tab">
                                <i class="ri-capsule-line me-1"></i> Prescriptions
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="actions-tab" data-bs-toggle="pill" 
                                    data-bs-target="#actions" type="button" role="tab">
                                <i class="ri-settings-line me-1"></i> Actions
                            </button>
                        </li>
                    </ul>

                    <!-- Tab Content -->
                    <div class="tab-content" id="patientTabsContent">
                        <!-- Overview Tab -->
                        <div class="tab-pane fade show active" id="overview" role="tabpanel">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="info-card">
                                        <div class="info-card-header">
                                            <h5 class="info-card-title">
                                                <i class="ri-user-line me-2"></i>Personal Information
                                            </h5>
                                        </div>
                                        <div class="info-grid">
                                            <div class="info-item">
                                                <span class="info-label">National ID</span>
                                                <span class="info-value"><?php echo $patient['national_id'] ?: 'N/A'; ?></span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Date of Birth</span>
                                                <span class="info-value"><?php echo date('d M Y', strtotime($patient['date_of_birth'])); ?></span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Blood Group</span>
                                                <span class="info-value"><?php echo $patient['blood_group'] ?: 'N/A'; ?></span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Email</span>
                                                <span class="info-value"><?php echo $patient['email'] ?: 'N/A'; ?></span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Address</span>
                                                <span class="info-value"><?php echo $patient['address'] ?: 'N/A'; ?></span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Registration Type</span>
                                                <span class="info-value"><?php echo str_replace('_', ' ', $patient['registration_type']); ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-lg-6">
                                    <div class="info-card">
                                        <div class="info-card-header">
                                            <h5 class="info-card-title">
                                                <i class="ri-contacts-line me-2"></i>Emergency Contact
                                            </h5>
                                        </div>
                                        <div class="info-grid">
                                            <div class="info-item">
                                                <span class="info-label">Contact Name</span>
                                                <span class="info-value"><?php echo $patient['emergency_contact_name'] ?: 'N/A'; ?></span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Contact Phone</span>
                                                <span class="info-value"><?php echo $patient['emergency_contact_phone'] ?: 'N/A'; ?></span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="info-card">
                                        <div class="info-card-header">
                                            <h5 class="info-card-title">
                                                <i class="ri-medicine-bottle-line me-2"></i>Current Medications
                                            </h5>
                                        </div>
                                        <p><?php echo $patient['current_medications'] ?: 'No current medications recorded'; ?></p>
                                    </div>
                                </div>
                            </div>

                            <!-- Recent Consultations -->
                            <div class="info-card">
                                <div class="info-card-header">
                                    <h5 class="info-card-title">
                                        <i class="ri-stethoscope-line me-2"></i>Recent Consultations
                                    </h5>
                                </div>
                                <?php if ($consultations_result->num_rows > 0): ?>
                                <div class="table-responsive">
                                    <table class="table">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Doctor</th>
                                                <th>Type</th>
                                                <th>Diagnosis</th>
                                                <th>Status</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($consult = $consultations_result->fetch_assoc()): ?>
                                            <tr>
                                                <td><?php echo date('d M Y', strtotime($consult['started_at'])); ?></td>
                                                <td><?php echo htmlspecialchars($consult['doctor_name']); ?></td>
                                                <td><?php echo $consult['consultation_type']; ?></td>
                                                <td><?php echo htmlspecialchars(substr($consult['diagnosis_primary'] ?? 'N/A', 0, 50)); ?>...</td>
                                                <td>
                                                    <span class="badge bg-<?php echo $consult['status'] === 'COMPLETED' ? 'success' : 'warning'; ?>">
                                                        <?php echo $consult['status']; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-info" onclick="viewConsultation(<?php echo $consult['consultation_id']; ?>)">
                                                        <i class="ri-eye-line"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php else: ?>
                                <div class="empty-state">
                                    <i class="ri-stethoscope-line"></i>
                                    <p>No consultation history available</p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Vital Signs Tab -->
                        <div class="tab-pane fade" id="vitals" role="tabpanel">
                            <div class="row">
                                <div class="col-12">
                                    <div class="info-card">
                                        <div class="info-card-header d-flex justify-content-between align-items-center">
                                            <h5 class="info-card-title">
                                                <i class="ri-heart-pulse-line me-2"></i>Vital Signs
                                            </h5>
                                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#recordVitalsModal">
                                                <i class="ri-add-line me-1"></i> Record New Vitals
                                            </button>
                                        </div>

                                        <?php if ($vitals_result->num_rows > 0): ?>
                                        <div class="history-timeline">
                                            <?php while ($vital = $vitals_result->fetch_assoc()): ?>
                                            <div class="history-item">
                                                <div class="history-date">
                                                    <?php echo date('d M Y H:i', strtotime($vital['recorded_date'])); ?> - 
                                                    by <?php echo htmlspecialchars($vital['recorded_by_name']); ?>
                                                </div>
                                                <div class="row mt-2">
                                                    <div class="col-md-3">
                                                        <div class="vital-card">
                                                            <div class="vital-label">Blood Pressure</div>
                                                            <div class="vital-value">
                                                                <?php echo $vital['blood_pressure'] ?: 'N/A'; ?>
                                                                <span class="vital-unit">mmHg</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="vital-card">
                                                            <div class="vital-label">Pulse Rate</div>
                                                            <div class="vital-value">
                                                                <?php echo $vital['pulse_rate'] ?: 'N/A'; ?>
                                                                <span class="vital-unit">bpm</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="vital-card">
                                                            <div class="vital-label">Temperature</div>
                                                            <div class="vital-value">
                                                                <?php echo $vital['temperature'] ?: 'N/A'; ?>
                                                                <span class="vital-unit">°C</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="vital-card">
                                                            <div class="vital-label">SpO2</div>
                                                            <div class="vital-value">
                                                                <?php echo $vital['oxygen_saturation'] ?: 'N/A'; ?>
                                                                <span class="vital-unit">%</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <?php if ($vital['notes']): ?>
                                                <div class="history-description mt-2">
                                                    <strong>Notes:</strong> <?php echo htmlspecialchars($vital['notes']); ?>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                            <?php endwhile; ?>
                                        </div>
                                        <?php else: ?>
                                        <div class="empty-state">
                                            <i class="ri-heart-pulse-line"></i>
                                            <p>No vital signs recorded yet</p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ENT History Tab -->
                        <div class="tab-pane fade" id="history" role="tabpanel">
                            <div class="info-card">
                                <div class="info-card-header">
                                    <h5 class="info-card-title">
                                        <i class="ri-file-list-3-line me-2"></i>ENT Medical History
                                    </h5>
                                </div>
                                <div class="row">
                                    <div class="col-12">
                                        <h6>ENT History</h6>
                                        <p><?php echo $patient['ent_history'] ? nl2br(htmlspecialchars($patient['ent_history'])) : 'No ENT history recorded'; ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Prescriptions Tab -->
                        <div class="tab-pane fade" id="prescriptions" role="tabpanel">
                            <div class="info-card">
                                <div class="info-card-header d-flex justify-content-between align-items-center">
                                    <h5 class="info-card-title">
                                        <i class="ri-capsule-line me-2"></i>Active Prescriptions
                                    </h5>
                                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#prescribeMedicineModal">
                                        <i class="ri-add-line me-1"></i> Prescribe Medicine
                                    </button>
                                </div>

                                <?php if ($prescriptions_result->num_rows > 0): ?>
                                <div class="prescription-list">
                                    <?php while ($rx = $prescriptions_result->fetch_assoc()): ?>
                                    <div class="medication-item">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <div class="medication-name">
                                                    <?php echo htmlspecialchars($rx['medication_name']); ?>
                                                </div>
                                                <div class="medication-details">
                                                    <strong>Dosage:</strong> <?php echo htmlspecialchars($rx['dosage']); ?> | 
                                                    <strong>Frequency:</strong> <?php echo htmlspecialchars($rx['frequency']); ?> | 
                                                    <strong>Duration:</strong> <?php echo htmlspecialchars($rx['duration']); ?>
                                                </div>
                                                <div class="medication-details">
                                                    <strong>Route:</strong> <?php echo $rx['route']; ?> | 
                                                    <strong>Prescribed by:</strong> <?php echo htmlspecialchars($rx['doctor_name']); ?> | 
                                                    <strong>Date:</strong> <?php echo date('d M Y', strtotime($rx['prescribed_date'])); ?>
                                                </div>
                                                <?php if ($rx['instructions']): ?>
                                                <div class="medication-details mt-2">
                                                    <strong>Instructions:</strong> <?php echo htmlspecialchars($rx['instructions']); ?>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                            <div>
                                                <span class="badge bg-<?php echo $rx['dispensed'] ? 'success' : 'warning'; ?>">
                                                    <?php echo $rx['dispensed'] ? 'Dispensed' : 'Pending'; ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                                <?php else: ?>
                                <div class="empty-state">
                                    <i class="ri-capsule-line"></i>
                                    <p>No active prescriptions</p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Actions Tab -->
                        <div class="tab-pane fade" id="actions" role="tabpanel">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="info-card">
                                        <div class="info-card-header">
                                            <h5 class="info-card-title">
                                                <i class="ri-arrow-left-right-line me-2"></i>Route Patient
                                            </h5>
                                        </div>
                                        <p class="text-muted mb-3">Transfer patient to another department</p>
                                        <form id="transferForm">
                                            <input type="hidden" name="patient_id" value="<?php echo $patient_id; ?>">
                                            <input type="hidden" name="queue_id" value="<?php echo $queue_id; ?>">
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Select Department</label>
                                                <select class="form-select" name="target_department" required>
                                                    <option value="">Choose department...</option>
                                                    <?php 
                                                    $departments_result->data_seek(0);
                                                    while ($dept = $departments_result->fetch_assoc()): 
                                                        if ($queue_data && $dept['department_id'] == $queue_data['department_id']) continue;
                                                    ?>
                                                    <option value="<?php echo $dept['department_id']; ?>">
                                                        <?php echo htmlspecialchars($dept['department_name']); ?>
                                                    </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Priority</label>
                                                <select class="form-select" name="priority">
                                                    <option value="NORMAL">Normal</option>
                                                    <option value="URGENT">Urgent</option>
                                                    <option value="EMERGENCY">Emergency</option>
                                                </select>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Transfer Reason</label>
                                                <select class="form-select" name="transfer_reason" required>
                                                    <option value="">Select reason...</option>
                                                    <option value="Further Investigation">Further Investigation</option>
                                                    <option value="Specialist Consultation">Specialist Consultation</option>
                                                    <option value="Diagnostic Test">Diagnostic Test</option>
                                                    <option value="Treatment">Treatment/Procedure</option>
                                                    <option value="Follow-up">Follow-up Care</option>
                                                    <option value="Medication">Medication Dispensing</option>
                                                    <option value="Billing">Billing/Payment</option>
                                                </select>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Notes</label>
                                                <textarea class="form-control" name="transfer_notes" rows="3"></textarea>
                                            </div>

                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-arrow-right-line me-1"></i> Transfer Patient
                                            </button>
                                        </form>
                                    </div>
                                </div>

                                <div class="col-lg-6">
                                    <div class="info-card">
                                        <div class="info-card-header">
                                            <h5 class="info-card-title">
                                                <i class="ri-check-line me-2"></i>Complete Service
                                            </h5>
                                        </div>
                                        <p class="text-muted mb-3">Mark service as complete and send to billing</p>
                                        
                                        <div class="alert alert-info">
                                            <i class="ri-information-line me-2"></i>
                                            Completing service will update the queue status and route the patient to billing department.
                                        </div>

                                        <button class="btn btn-success w-100 mb-3" onclick="completeService()">
                                            <i class="ri-check-line me-1"></i> Complete & Send to Billing
                                        </button>

                                        <button class="btn btn-outline-danger w-100" onclick="cancelService()">
                                            <i class="ri-close-line me-1"></i> Cancel Service
                                        </button>
                                    </div>

                                    <?php if ($queue_data && $queue_data['queue_status'] === 'WAITING'): ?>
                                    <div class="info-card">
                                        <div class="info-card-header">
                                            <h5 class="info-card-title">
                                                <i class="ri-play-line me-2"></i>Start Service
                                            </h5>
                                        </div>
                                        <p class="text-muted mb-3">Begin attending to this patient</p>
                                        
                                        <button class="btn btn-primary w-100" onclick="startService()">
                                            <i class="ri-play-line me-1"></i> Start Service Now
                                        </button>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Record Vitals Modal -->
    <div class="modal fade" id="recordVitalsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-heart-pulse-line me-2"></i>Record Vital Signs
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form id="vitalsForm">
                    <div class="modal-body">
                        <input type="hidden" name="patient_id" value="<?php echo $patient_id; ?>">
                        <input type="hidden" name="visit_id" value="<?php echo $current_visit['visit_id'] ?? ''; ?>">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Blood Pressure (mmHg)</label>
                                <input type="text" class="form-control" name="blood_pressure" 
                                       placeholder="e.g., 120/80" pattern="\d{2,3}/\d{2,3}">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Pulse Rate (bpm)</label>
                                <input type="number" class="form-control" name="pulse_rate" 
                                       placeholder="e.g., 72" min="30" max="200">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Temperature (°C)</label>
                                <input type="number" class="form-control" name="temperature" 
                                       placeholder="e.g., 37.0" step="0.1" min="30" max="45">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Temperature Route</label>
                                <select class="form-select" name="temperature_route">
                                    <option value="ORAL">Oral</option>
                                    <option value="AXILLARY">Axillary</option>
                                    <option value="TYMPANIC">Tympanic</option>
                                    <option value="TEMPORAL">Temporal</option>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Respiratory Rate (breaths/min)</label>
                                <input type="number" class="form-control" name="respiratory_rate" 
                                       placeholder="e.g., 16" min="8" max="60">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Oxygen Saturation (%)</label>
                                <input type="number" class="form-control" name="oxygen_saturation" 
                                       placeholder="e.g., 98" min="50" max="100" step="0.1">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Weight (kg)</label>
                                <input type="number" class="form-control" name="weight" 
                                       placeholder="e.g., 70" step="0.1" min="1" max="300">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Height (cm)</label>
                                <input type="number" class="form-control" name="height" 
                                       placeholder="e.g., 170" step="0.1" min="30" max="250">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">BMI (Auto-calculated)</label>
                                <input type="text" class="form-control" id="bmiDisplay" readonly placeholder="--">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Pain Scale (0-10)</label>
                                <input type="number" class="form-control" name="pain_scale" 
                                       placeholder="0 = No pain, 10 = Worst pain" min="0" max="10">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Consciousness Level</label>
                                <select class="form-select" name="consciousness_level">
                                    <option value="ALERT">Alert</option>
                                    <option value="VERBAL">Responds to Verbal</option>
                                    <option value="PAIN">Responds to Pain</option>
                                    <option value="UNRESPONSIVE">Unresponsive</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" 
                                      placeholder="Any additional observations or findings"></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Abnormal Findings</label>
                            <textarea class="form-control" name="abnormal_findings" rows="2" 
                                      placeholder="Note any abnormal vital signs"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="ri-save-line me-1"></i> Save Vital Signs
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Prescribe Medicine Modal -->
    <div class="modal fade" id="prescribeMedicineModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-capsule-line me-2"></i>Prescribe Medication
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form id="prescriptionForm">
                    <div class="modal-body">
                        <input type="hidden" name="patient_id" value="<?php echo $patient_id; ?>">
                        <input type="hidden" name="visit_id" value="<?php echo $current_visit['visit_id'] ?? ''; ?>">
                        <input type="hidden" name="doctor_id" value="<?php echo $user_id; ?>">
                        
                        <!-- Medicine Search -->
                        <div class="mb-3">
                            <label class="form-label">Search Medicine</label>
                            <div class="search-medicine-box">
                                <input type="text" class="form-control" id="medicineSearch" 
                                       placeholder="Type to search medicine from pharmacy inventory...">
                                <div class="medicine-results" id="medicineResults"></div>
                            </div>
                        </div>

                        <!-- Selected Medicine Details -->
                        <div id="selectedMedicineSection" style="display: none;">
                            <div class="alert alert-info">
                                <strong>Selected:</strong> <span id="selectedMedicineName"></span>
                            </div>

                            <input type="hidden" name="medication_name" id="medicationName">
                            <input type="hidden" name="inventory_id" id="inventoryId">

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Dosage <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="dosage" 
                                           placeholder="e.g., 500mg, 10ml" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Frequency <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="frequency" 
                                           placeholder="e.g., Twice daily, Every 8 hours" required>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Route</label>
                                    <select class="form-select" name="route">
                                        <option value="ORAL">Oral</option>
                                        <option value="TOPICAL">Topical</option>
                                        <option value="NASAL">Nasal</option>
                                        <option value="OTIC">Otic (Ear)</option>
                                        <option value="INJECTION">Injection</option>
                                        <option value="INHALATION">Inhalation</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Duration <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="duration" 
                                           placeholder="e.g., 7 days, 2 weeks" required>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Quantity</label>
                                <input type="text" class="form-control" name="quantity" 
                                       placeholder="Total quantity to dispense">
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Instructions for Patient</label>
                                <textarea class="form-control" name="instructions" rows="2" 
                                          placeholder="e.g., Take with food, Avoid alcohol"></textarea>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Indication (Reason)</label>
                                <textarea class="form-control" name="indication" rows="2" 
                                          placeholder="Why this medication is prescribed"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="prescribeBtn" disabled>
                            <i class="ri-save-line me-1"></i> Prescribe Medication
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Calculate BMI automatically
        $('input[name="weight"], input[name="height"]').on('input', function() {
            const weight = parseFloat($('input[name="weight"]').val());
            const height = parseFloat($('input[name="height"]').val()) / 100; // convert cm to m
            
            if (weight && height) {
                const bmi = (weight / (height * height)).toFixed(1);
                $('#bmiDisplay').val(bmi);
            } else {
                $('#bmiDisplay').val('--');
            }
        });

        // Medicine Search
        let searchTimeout;
        $('#medicineSearch').on('input', function() {
            const query = $(this).val().trim();
            
            clearTimeout(searchTimeout);
            
            if (query.length < 2) {
                $('#medicineResults').removeClass('show').html('');
                return;
            }
            
            searchTimeout = setTimeout(function() {
                $.ajax({
                    url: 'ajax/search_pharmacy_inventory.php',
                    method: 'POST',
                    data: { query: query },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success && response.data.length > 0) {
                            let html = '';
                            response.data.forEach(function(medicine) {
                                html += `
                                    <div class="medicine-result-item" onclick="selectMedicine(${medicine.inventory_id}, '${medicine.item_name}', '${medicine.strength}', '${medicine.dosage_form}')">
                                        <div class="medicine-result-name">${medicine.item_name}</div>
                                        <div class="medicine-result-details">
                                            ${medicine.generic_name ? medicine.generic_name + ' | ' : ''}
                                            ${medicine.strength} | ${medicine.dosage_form} | 
                                            Stock: ${medicine.current_stock} | 
                                            KES ${parseFloat(medicine.selling_price).toFixed(2)}
                                        </div>
                                    </div>
                                `;
                            });
                            $('#medicineResults').html(html).addClass('show');
                        } else {
                            $('#medicineResults').html('<div class="medicine-result-item">No medicines found</div>').addClass('show');
                        }
                    }
                });
            }, 300);
        });

        // Close results when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.search-medicine-box').length) {
                $('#medicineResults').removeClass('show');
            }
        });

        // Submit Vitals Form
        $('#vitalsForm').on('submit', function(e) {
            e.preventDefault();
            
            const formData = $(this).serialize();
            
            $.ajax({
                url: 'ajax/save_vital_signs.php',
                method: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Vital Signs Recorded',
                            text: response.message,
                            timer: 2000
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to save vital signs'
                    });
                }
            });
        });

        // Submit Prescription Form
        $('#prescriptionForm').on('submit', function(e) {
            e.preventDefault();
            
            const formData = $(this).serialize();
            
            $.ajax({
                url: 'ajax/save_prescription.php',
                method: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Prescription Created',
                            text: response.message,
                            timer: 2000
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to save prescription'
                    });
                }
            });
        });

        // Transfer Form
        $('#transferForm').on('submit', function(e) {
            e.preventDefault();
            
            const formData = $(this).serialize();
            
            Swal.fire({
                title: 'Transfer Patient?',
                text: 'This will move the patient to the selected department',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Transfer',
                confirmButtonColor: '#667eea'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/transfer_patient_queue.php',
                        method: 'POST',
                        data: formData,
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Patient Transferred',
                                    text: response.message,
                                    timer: 2000
                                }).then(() => {
                                    window.location.href = 'queue_dashboard.php';
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message
                                });
                            }
                        }
                    });
                }
            });
        });
    });

    // Select Medicine Function
    function selectMedicine(inventoryId, name, strength, form) {
        $('#medicineSearch').val(name);
        $('#medicineResults').removeClass('show');
        $('#selectedMedicineName').text(`${name} - ${strength} (${form})`);
        $('#medicationName').val(name);
        $('#inventoryId').val(inventoryId);
        $('#selectedMedicineSection').slideDown();
        $('#prescribeBtn').prop('disabled', false);
    }

    // Complete Service
    function completeService() {
        Swal.fire({
            title: 'Complete Service?',
            text: 'This will mark service as complete and route patient to billing',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Complete',
            confirmButtonColor: '#10b981'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `ajax/complete_service.php?queue_id=<?php echo $queue_id; ?>&patient_id=<?php echo $patient_id; ?>`;
            }
        });
    }

    // Start Service
    function startService() {
        window.location.href = `queue_actions.php?action=start_service&queue_id=<?php echo $queue_id; ?>`;
    }

    // Cancel Service
    function cancelService() {
        Swal.fire({
            title: 'Cancel Service?',
            input: 'textarea',
            inputLabel: 'Cancellation Reason',
            inputPlaceholder: 'Enter reason for cancellation',
            showCancelButton: true,
            confirmButtonText: 'Yes, Cancel',
            confirmButtonColor: '#ef4444',
            inputValidator: (value) => {
                if (!value) {
                    return 'Please provide a reason';
                }
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'queue_actions.php?action=cancel&queue_id=<?php echo $queue_id; ?>',
                    method: 'POST',
                    data: { cancel_reason: result.value },
                    success: function() {
                        window.location.href = 'queue_dashboard.php';
                    }
                });
            }
        });
    }

    // View Consultation
    function viewConsultation(consultationId) {
        window.location.href = `view_consultation.php?id=${consultationId}`;
    }
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>