<?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 filters
$department_filter = $_GET['department'] ?? 'all';
$status_filter = $_GET['status'] ?? 'active';
$view_mode = $_GET['view'] ?? 'current'; // current or history
// Fetch department statistics
$dept_stats_sql = "SELECT
    d.department_id,
    d.department_name,
    d.department_code,
    COUNT(CASE WHEN q.queue_status = 'WAITING' THEN 1 END) as waiting_count,
    COUNT(CASE WHEN q.queue_status = 'IN_SERVICE' THEN 1 END) as in_service_count,
    COUNT(CASE WHEN q.queue_status IN ('WAITING', 'IN_SERVICE') THEN 1 END) as active_count,
    COUNT(CASE WHEN q.queue_status = 'COMPLETED' THEN 1 END) as completed_today,
    AVG(CASE
        WHEN q.queue_status IN ('IN_SERVICE', 'COMPLETED')
        THEN TIMESTAMPDIFF(MINUTE, q.queue_entry_time, COALESCE(q.service_start_time, NOW()))
    END) as avg_wait_minutes,
    MAX(CASE
        WHEN q.queue_status = 'WAITING'
        THEN TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW())
    END) as longest_wait_minutes,
    d.max_queue_capacity,
    ROUND((COUNT(CASE WHEN q.queue_status IN ('WAITING', 'IN_SERVICE') THEN 1 END) / d.max_queue_capacity) * 100, 2) as capacity_percentage
FROM departments d
LEFT JOIN patient_queue q ON d.department_id = q.department_id
    AND DATE(q.queue_entry_time) = CURDATE()
WHERE d.is_active = 1
GROUP BY d.department_id, d.department_name, d.department_code, d.max_queue_capacity
ORDER BY d.display_order";
$dept_stats_result = $conn->query($dept_stats_sql);
// Build queue query based on view mode
if ($view_mode === 'history') {
    // Queue history - completed/cancelled patients
    $queue_sql = "SELECT
        q.queue_id,
        q.queue_number,
        q.patient_id,
        q.patient_name,
        q.patient_number,
        q.phone_number,
        q.age,
        q.gender,
        d.department_id,
        d.department_name,
        d.department_code,
        q.queue_status,
        q.priority,
        q.registration_type,
        q.position_in_queue,
        q.estimated_wait_minutes,
        q.service_type,
        q.chief_complaint,
        q.triage_category,
        q.vitals_taken,
        q.queue_entry_time,
        q.service_start_time,
        q.service_end_time,
        q.total_wait_minutes,
        q.total_service_minutes,
        TIMESTAMPDIFF(MINUTE, q.queue_entry_time, COALESCE(q.service_start_time, q.service_end_time)) as actual_wait_minutes,
        q.serving_staff_name,
        q.has_appointment,
        q.is_vip,
        q.special_needs,
        q.alert_flags,
        u.full_name as created_by_name,
        q.created_at,
        q.updated_at
    FROM patient_queue q
    INNER JOIN departments d ON q.department_id = d.department_id
    LEFT JOIN users u ON q.created_by = u.user_id
    WHERE DATE(q.queue_entry_time) = CURDATE()
    AND q.queue_status IN ('COMPLETED', 'CANCELLED', 'NO_SHOW', 'TRANSFERRED')";
} else {
    // Current queue - active patients
    $queue_sql = "SELECT
        q.queue_id,
        q.queue_number,
        q.patient_id,
        q.patient_name,
        q.patient_number,
        q.phone_number,
        q.age,
        q.gender,
        d.department_id,
        d.department_name,
        d.department_code,
        q.queue_status,
        q.priority,
        q.registration_type,
        q.position_in_queue,
        q.estimated_wait_minutes,
        q.service_type,
        q.chief_complaint,
        q.triage_category,
        q.vitals_taken,
        q.queue_entry_time,
        q.service_start_time,
        TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) as actual_wait_minutes,
        q.serving_staff_name,
        q.has_appointment,
        q.is_vip,
        q.special_needs,
        q.alert_flags,
        u.full_name as created_by_name,
        q.created_at
    FROM patient_queue q
    INNER JOIN departments d ON q.department_id = d.department_id
    LEFT JOIN users u ON q.created_by = u.user_id
    WHERE DATE(q.queue_entry_time) = CURDATE()
    AND q.queue_status IN ('WAITING', 'IN_SERVICE')";
}
if ($department_filter !== 'all') {
    $queue_sql .= " AND q.department_id = " . intval($department_filter);
}
if ($view_mode === 'current') {
    if ($status_filter === 'active') {
        $queue_sql .= " AND queue_status IN ('WAITING', 'IN_SERVICE')";
    } elseif ($status_filter === 'waiting') {
        $queue_sql .= " AND queue_status = 'WAITING'";
    } elseif ($status_filter === 'in_service') {
        $queue_sql .= " AND queue_status = 'IN_SERVICE'";
    }
}
$queue_sql .= " ORDER BY ";
if ($view_mode === 'history') {
    $queue_sql .= "q.updated_at DESC, q.queue_entry_time DESC";
} else {
    $queue_sql .= "CASE q.priority
        WHEN 'EMERGENCY' THEN 1
        WHEN 'URGENT' THEN 2
        WHEN 'NORMAL' THEN 3
    END, q.queue_entry_time";
}
$queue_result = $conn->query($queue_sql);
// Get total counts for today
$counts_sql = "SELECT
    COUNT(CASE WHEN queue_status IN ('WAITING', 'IN_SERVICE') THEN 1 END) as active_count,
    COUNT(CASE WHEN queue_status = 'WAITING' THEN 1 END) as waiting_count,
    COUNT(CASE WHEN queue_status = 'IN_SERVICE' THEN 1 END) as in_service_count,
    COUNT(CASE WHEN queue_status = 'COMPLETED' THEN 1 END) as completed_count,
    COUNT(CASE WHEN priority = 'EMERGENCY' THEN 1 END) as emergency_count
FROM patient_queue
WHERE DATE(queue_entry_time) = CURDATE()";
$counts_result = $conn->query($counts_sql);
$counts = $counts_result->fetch_assoc();
?>
<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Queue Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <!-- Select2 CSS from CDN -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
   
    <style>
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-left: 4px solid #667eea;
            transition: all 0.3s;
        }
       
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
       
        .stat-card.waiting {
            border-left-color: #3b82f6;
        }
       
        .stat-card.in-service {
            border-left-color: #f59e0b;
        }
       
        .stat-card.completed {
            border-left-color: #10b981;
        }
       
        .stat-card.emergency {
            border-left-color: #ef4444;
        }
       
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
       
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
       
        .stat-icon {
            font-size: 2.5rem;
            opacity: 0.2;
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
        }
       
        .dept-card {
            background: white;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            border: 1px solid #e2e8f0;
            cursor: pointer;
            transition: all 0.3s;
        }
       
        .dept-card:hover {
            border-color: #667eea;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
       
        .dept-card.selected {
            border-color: #667eea;
            background: #eff6ff;
        }
       
        .dept-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
       
        .dept-stats {
            display: flex;
            justify-content: space-between;
            font-size: 0.875rem;
        }
       
        .dept-stat {
            text-align: center;
        }
       
        .dept-stat-value {
            font-weight: 600;
            color: #667eea;
        }
       
        .dept-stat-label {
            color: #64748b;
            font-size: 0.75rem;
        }
       
        .queue-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
       
        .queue-table thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
       
        .queue-table th {
            padding: 1rem;
            font-weight: 600;
            border: none;
        }
       
        .queue-table td {
            padding: 1rem;
            vertical-align: middle;
        }
       
        .queue-table tbody tr {
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s;
        }
       
        .queue-table tbody tr:hover {
            background: #f8fafc;
        }
       
        .priority-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
       
        .priority-normal {
            background: #dcfce7;
            color: #166534;
        }
       
        .priority-urgent {
            background: #fef3c7;
            color: #92400e;
        }
       
        .priority-emergency {
            background: #fee2e2;
            color: #991b1b;
        }
       
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
       
        .status-waiting {
            background: #dbeafe;
            color: #1e40af;
        }
       
        .status-in-service {
            background: #fef3c7;
            color: #92400e;
        }
       
        .status-completed {
            background: #dcfce7;
            color: #166534;
        }
       
        .status-cancelled {
            background: #fee2e2;
            color: #991b1b;
        }
       
        .status-no-show {
            background: #f3f4f6;
            color: #6b7280;
        }
       
        .status-transferred {
            background: #e0e7ff;
            color: #4338ca;
        }
       
        .patient-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
       
        .patient-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 1rem;
        }
       
        .patient-details {
            flex: 1;
        }
       
        .patient-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.125rem;
        }
       
        .patient-meta {
            font-size: 0.75rem;
            color: #64748b;
        }
       
        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
        }
       
        .action-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
       
        .wait-time {
            font-size: 0.875rem;
            color: #64748b;
        }
       
        .wait-time.long {
            color: #dc2626;
            font-weight: 600;
        }
       
        .vip-flag {
            display: inline-block;
            padding: 0.125rem 0.5rem;
            background: #fef3c7;
            color: #92400e;
            border-radius: 4px;
            font-size: 0.625rem;
            font-weight: 600;
            margin-left: 0.5rem;
        }
       
        .refresh-indicator {
            display: inline-block;
            color: #10b981;
            font-size: 0.875rem;
            animation: pulse 2s infinite;
        }
       
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
       
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
       
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }
       
        .view-toggle {
            display: inline-flex;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
       
        .view-toggle-btn {
            padding: 0.5rem 1rem;
            border: none;
            background: white;
            color: #64748b;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }
       
        .view-toggle-btn.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
       
        .view-toggle-btn:hover:not(.active) {
            background: #f8fafc;
        }
       
        /* Select2 Custom Styling */
        .select2-container--bootstrap-5 .select2-selection {
            border-color: #e2e8f0;
            min-height: 38px;
        }
       
        .select2-container--bootstrap-5.select2-container--focus .select2-selection,
        .select2-container--bootstrap-5.select2-container--open .select2-selection {
            border-color: #667eea;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.25);
        }
       
        .select2-container--bootstrap-5 .select2-dropdown {
            border-color: #e2e8f0;
        }
       
        .select2-container--bootstrap-5 .select2-results__option--highlighted {
            background-color: #667eea;
            color: white;
        }
       
        .select2-container--bootstrap-5 .select2-search__field {
            border-color: #e2e8f0;
        }
       
        .select2-container--bootstrap-5 .select2-search__field:focus {
            border-color: #667eea;
            outline: 0;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.25);
        }
    </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 Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">
                                    <i class="ri-dashboard-line me-2"></i>Queue Dashboard
                                    <span class="refresh-indicator ms-3">
                                        <i class="ri-refresh-line"></i> Live
                                    </span>
                                </h4>
                                <div class="page-title-right">
                                    <div class="view-toggle me-2">
                                        <button class="view-toggle-btn <?php echo $view_mode === 'current' ? 'active' : ''; ?>"
                                                onclick="switchView('current')">
                                            <i class="ri-time-line me-1"></i> Current Queue
                                        </button>
                                        <button class="view-toggle-btn <?php echo $view_mode === 'history' ? 'active' : ''; ?>"
                                                onclick="switchView('history')">
                                            <i class="ri-history-line me-1"></i> History
                                        </button>
                                    </div>
                                    <button class="btn btn-success me-2" onclick="showAddPatientModal()">
                                        <i class="ri-user-add-line me-1"></i> Add to Queue
                                    </button>
                                    <button class="btn btn-primary me-2" onclick="location.href='register_patient.php'">
                                        <i class="ri-user-add-line me-1"></i> New Patient
                                    </button>
                                    <button class="btn btn-secondary" onclick="refreshQueue()">
                                        <i class="ri-refresh-line me-1"></i> Refresh
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="position-relative">
                                    <p class="stat-label">Total Active</p>
                                    <h2 class="stat-value"><?php echo $counts['active_count']; ?></h2>
                                    <i class="ri-team-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card waiting">
                                <div class="position-relative">
                                    <p class="stat-label">Waiting</p>
                                    <h2 class="stat-value"><?php echo $counts['waiting_count']; ?></h2>
                                    <i class="ri-time-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card in-service">
                                <div class="position-relative">
                                    <p class="stat-label">In Service</p>
                                    <h2 class="stat-value"><?php echo $counts['in_service_count']; ?></h2>
                                    <i class="ri-user-settings-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card completed">
                                <div class="position-relative">
                                    <p class="stat-label">Completed Today</p>
                                    <h2 class="stat-value"><?php echo $counts['completed_count']; ?></h2>
                                    <i class="ri-checkbox-circle-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <!-- Department Sidebar -->
                        <div class="col-xl-3">
                            <div class="card">
                                <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                    <h5 class="mb-0">
                                        <i class="ri-hospital-line me-2"></i>Departments
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="dept-card <?php echo $department_filter === 'all' ? 'selected' : ''; ?>"
                                         onclick="filterByDepartment('all')">
                                        <div class="dept-name">
                                            <i class="ri-building-2-line me-2"></i>All Departments
                                        </div>
                                        <div class="dept-stats">
                                            <div class="dept-stat">
                                                <div class="dept-stat-value"><?php echo $counts['active_count']; ?></div>
                                                <div class="dept-stat-label">Active</div>
                                            </div>
                                        </div>
                                    </div>
                                   
                                    <?php
                                    $dept_stats_result->data_seek(0);
                                    while ($dept = $dept_stats_result->fetch_assoc()):
                                    ?>
                                    <div class="dept-card <?php echo $department_filter == $dept['department_id'] ? 'selected' : ''; ?>"
                                         onclick="filterByDepartment(<?php echo $dept['department_id']; ?>)">
                                        <div class="dept-name"><?php echo htmlspecialchars($dept['department_name']); ?></div>
                                        <div class="dept-stats">
                                            <div class="dept-stat">
                                                <div class="dept-stat-value"><?php echo $dept['waiting_count']; ?></div>
                                                <div class="dept-stat-label">Waiting</div>
                                            </div>
                                            <div class="dept-stat">
                                                <div class="dept-stat-value"><?php echo $dept['in_service_count']; ?></div>
                                                <div class="dept-stat-label">In Service</div>
                                            </div>
                                            <div class="dept-stat">
                                                <div class="dept-stat-value"><?php echo $dept['completed_today']; ?></div>
                                                <div class="dept-stat-label">Done</div>
                                            </div>
                                        </div>
                                        <?php if ($dept['capacity_percentage'] > 80): ?>
                                        <div class="mt-2">
                                            <small class="text-danger">
                                                <i class="ri-alert-line"></i> <?php echo round($dept['capacity_percentage']); ?>% Capacity
                                            </small>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                        </div>
                        <!-- Queue List -->
                        <div class="col-xl-9">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center"
                                     style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                    <h5 class="mb-0">
                                        <i class="<?php echo $view_mode === 'history' ? 'ri-history-line' : 'ri-list-check'; ?> me-2"></i>
                                        <?php echo $view_mode === 'history' ? 'Queue History' : 'Patient Queue'; ?>
                                    </h5>
                                    <?php if ($view_mode === 'current'): ?>
                                    <div>
                                        <select class="form-select form-select-sm" style="width: auto; display: inline-block;"
                                                onchange="filterByStatus(this.value)">
                                            <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                            <option value="waiting" <?php echo $status_filter === 'waiting' ? 'selected' : ''; ?>>Waiting Only</option>
                                            <option value="in_service" <?php echo $status_filter === 'in_service' ? 'selected' : ''; ?>>In Service</option>
                                        </select>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div class="card-body p-0">
                                    <?php if ($queue_result->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table queue-table mb-0">
                                            <thead>
                                                <tr>
                                                    <th style="width: 5%;">#</th>
                                                    <th style="width: 25%;">Patient</th>
                                                    <th style="width: 15%;">Department</th>
                                                    <th style="width: 10%;">Priority</th>
                                                    <th style="width: 10%;">Status</th>
                                                    <th style="width: 15%;">
                                                        <?php echo $view_mode === 'history' ? 'Duration' : 'Wait Time'; ?>
                                                    </th>
                                                    <?php if ($view_mode === 'current'): ?>
                                                    <th style="width: 10%;">Position</th>
                                                    <th style="width: 10%;">Actions</th>
                                                    <?php else: ?>
                                                    <th style="width: 20%;">Completed</th>
                                                    <?php endif; ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $row_num = 1;
                                                while ($queue = $queue_result->fetch_assoc()):
                                                    $wait_minutes = $queue['actual_wait_minutes'];
                                                    $is_long_wait = $wait_minutes > 60;
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo $row_num++; ?></strong>
                                                    </td>
                                                    <td>
                                                        <div class="patient-info">
                                                            <div class="patient-avatar">
                                                                <?php echo strtoupper(substr($queue['patient_name'], 0, 1)); ?>
                                                            </div>
                                                            <div class="patient-details">
                                                                <div class="patient-name">
                                                                    <?php echo htmlspecialchars($queue['patient_name']); ?>
                                                                    <?php if ($queue['is_vip']): ?>
                                                                    <span class="vip-flag">VIP</span>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <div class="patient-meta">
                                                                    <?php echo $queue['patient_number']; ?> •
                                                                    <?php echo $queue['age']; ?>Y <?php echo $queue['gender']; ?> •
                                                                    <?php echo substr($queue['phone_number'], 0, 10); ?>
                                                                </div>
                                                                <?php if ($queue['chief_complaint']): ?>
                                                                <div class="patient-meta">
                                                                    <i class="ri-stethoscope-line"></i> <?php echo htmlspecialchars(substr($queue['chief_complaint'], 0, 40)); ?>...
                                                                </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <strong><?php echo htmlspecialchars($queue['department_name']); ?></strong>
                                                    </td>
                                                    <td>
                                                        <span class="priority-badge priority-<?php echo strtolower($queue['priority']); ?>">
                                                            <?php echo $queue['priority']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="status-badge status-<?php echo str_replace('_', '-', strtolower($queue['queue_status'])); ?>">
                                                            <?php echo str_replace('_', ' ', $queue['queue_status']); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if ($view_mode === 'history' && $queue['total_service_minutes']): ?>
                                                        <div class="wait-time">
                                                            <i class="ri-time-line me-1"></i>
                                                            Service: <?php echo $queue['total_service_minutes']; ?> min
                                                        </div>
                                                        <?php if ($queue['total_wait_minutes']): ?>
                                                        <small class="text-muted">Wait: <?php echo $queue['total_wait_minutes']; ?> min</small>
                                                        <?php endif; ?>
                                                        <?php else: ?>
                                                        <div class="wait-time <?php echo $is_long_wait ? 'long' : ''; ?>">
                                                            <i class="ri-time-line me-1"></i>
                                                            <?php
                                                            if ($wait_minutes < 60) {
                                                                echo $wait_minutes . ' min';
                                                            } else {
                                                                $hours = floor($wait_minutes / 60);
                                                                $mins = $wait_minutes % 60;
                                                                echo $hours . 'h ' . $mins . 'm';
                                                            }
                                                            ?>
                                                        </div>
                                                        <?php if ($queue['estimated_wait_minutes']): ?>
                                                        <small class="text-muted">Est: <?php echo $queue['estimated_wait_minutes']; ?> min</small>
                                                        <?php endif; ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <?php if ($view_mode === 'current'): ?>
                                                    <td>
                                                        <?php if ($queue['queue_status'] === 'WAITING'): ?>
                                                        <span class="badge bg-info">#<?php echo $queue['position_in_queue']; ?></span>
                                                        <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <button class="btn btn-success" onclick="callPatient(<?php echo $queue['queue_id']; ?>)"
                                                                    title="Call Patient"
                                                                    <?php echo $queue['queue_status'] !== 'WAITING' ? 'disabled' : ''; ?>>
                                                                <i class="ri-phone-line"></i>
                                                            </button>
                                                            <button class="btn btn-primary" onclick="startService(<?php echo $queue['queue_id']; ?>)"
                                                                    title="Start Service"
                                                                    <?php echo $queue['queue_status'] !== 'WAITING' ? 'disabled' : ''; ?>>
                                                                <i class="ri-play-line"></i>
                                                            </button>
                                                            <button class="btn btn-warning" onclick="transferPatient(<?php echo $queue['queue_id']; ?>)"
                                                                    title="Transfer">
                                                                <i class="ri-arrow-right-line"></i>
                                                            </button>
                                                            <button class="btn btn-info" onclick="viewDetails(<?php echo $queue['patient_id']; ?>)"
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                    <?php else: ?>
                                                    <td>
                                                        <small class="text-muted">
                                                            <?php
                                                            if ($queue['updated_at']) {
                                                                echo date('H:i', strtotime($queue['updated_at']));
                                                            }
                                                            ?>
                                                        </small>
                                                        <br>
                                                        <button class="btn btn-sm btn-info" onclick="viewDetails(<?php echo $queue['patient_id']; ?>)">
                                                            <i class="ri-eye-line"></i> View
                                                        </button>
                                                    </td>
                                                    <?php endif; ?>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <div class="empty-state">
                                        <i class="ri-inbox-line"></i>
                                        <h5><?php echo $view_mode === 'history' ? 'No Queue History' : 'No Patients in Queue'; ?></h5>
                                        <p class="text-muted">
                                            <?php echo $view_mode === 'history' ? 'No patients have been processed today.' : 'The queue is currently empty for the selected filters.'; ?>
                                        </p>
                                        <?php if ($view_mode === 'current'): ?>
                                        <button class="btn btn-primary mt-3" onclick="showAddPatientModal()">
                                            <i class="ri-user-add-line me-1"></i> Add Patient to Queue
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <!-- Add Patient to Queue Modal -->
    <div class="modal fade" id="addPatientModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                    <h5 class="modal-title">
                        <i class="ri-user-add-line me-2"></i>Add Patient to Queue
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addToQueueForm">
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Search Patient <span class="text-danger">*</span></label>
                                <select class="form-select" id="patientSelect" name="patient_id" required>
                                    <option value="">Type patient name or number...</option>
                                </select>
                                <div id="patientInfo" class="mt-2" style="display: none;">
                                    <div class="alert alert-info">
                                        <strong>Selected Patient:</strong>
                                        <div id="patientDetails"></div>
                                    </div>
                                </div>
                            </div>
                           
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Department <span class="text-danger">*</span></label>
                                <select class="form-select" name="department_id" required>
                                    <option value="">Select Department</option>
                                    <?php
                                    $dept_sql = "SELECT department_id, department_name FROM departments WHERE is_active = 1 ORDER BY display_order";
                                    $dept_result = $conn->query($dept_sql);
                                    while ($dept = $dept_result->fetch_assoc()):
                                    ?>
                                    <option value="<?php echo $dept['department_id']; ?>">
                                        <?php echo htmlspecialchars($dept['department_name']); ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                           
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Priority <span class="text-danger">*</span></label>
                                <select class="form-select" name="priority" required>
                                    <option value="NORMAL">Normal</option>
                                    <option value="URGENT">Urgent</option>
                                    <option value="EMERGENCY">Emergency</option>
                                </select>
                            </div>
                           
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Service Type</label>
                                <input type="text" class="form-control" name="service_type" placeholder="e.g., Consultation, Follow-up">
                            </div>
                           
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Has Appointment?</label>
                                <select class="form-select" name="has_appointment">
                                    <option value="0">No</option>
                                    <option value="1">Yes</option>
                                </select>
                            </div>
                           
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Chief Complaint</label>
                                <textarea class="form-control" name="chief_complaint" rows="3" placeholder="Reason for visit..."></textarea>
                            </div>
                           
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Special Needs / Notes</label>
                                <textarea class="form-control" name="special_needs" rows="2" placeholder="Any special requirements..."></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="submitAddToQueue()">
                        <i class="ri-add-line me-1"></i> Add to Queue
                    </button>
                </div>
            </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>
    <!-- Select2 JS from CDN - Load after jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
   
    <script>
    // Initialize Select2 for patient search
    $(document).ready(function() {
        // Check if Select2 is available
        if (typeof $.fn.select2 === 'undefined') {
            console.error('Select2 library not loaded');
            return;
        }
       
        $('#patientSelect').select2({
            dropdownParent: $('#addPatientModal'),
            placeholder: 'Type patient name or number...',
            allowClear: true,
            theme: 'bootstrap-5',
            minimumInputLength: 2,
            ajax: {
                url: 'ajax/search_patients.php',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        search: params.term
                    };
                },
                processResults: function(data) {
                    // Handle object response with 'results' array
                    if (!data || !data.success || !Array.isArray(data.results)) {
                        console.warn('Invalid or empty response from server:', data);
                        return { results: [] };
                    }
                    return {
                        results: data.results.map(function(patient) {
                            return {
                                id: patient.id,
                                text: patient.patient_number + ' - ' + patient.full_name + ' (' + patient.age + 'Y ' + patient.gender + ')',
                                patient: patient
                            };
                        })
                    };
                },
                cache: true
            }
        }).on('select2:select', function(e) {
            const patient = e.params.data.patient;
            $('#patientDetails').html(`
                <strong>${patient.full_name}</strong><br>
                Patient #: ${patient.patient_number}<br>
                Age: ${patient.age}, Gender: ${patient.gender}<br>
                Phone: ${patient.phone || 'N/A'}<br>
                Blood Group: ${patient.blood_group || 'N/A'}<br>
                Type: ${patient.registration_type || 'N/A'}
            `);
            $('#patientInfo').show();
        }).on('select2:clear', function() {
            $('#patientInfo').hide();
        });
    });
   
    // Auto-refresh every 30 seconds (only for current view)
    <?php if ($view_mode === 'current'): ?>
    setInterval(function() {
        location.reload();
    }, 30000);
    <?php endif; ?>
   
    function switchView(view) {
        const url = new URL(window.location.href);
        url.searchParams.set('view', view);
        window.location.href = url.toString();
    }
   
    function filterByDepartment(deptId) {
        const url = new URL(window.location.href);
        url.searchParams.set('department', deptId);
        window.location.href = url.toString();
    }
   
    function filterByStatus(status) {
        const url = new URL(window.location.href);
        url.searchParams.set('status', status);
        window.location.href = url.toString();
    }
   
    function refreshQueue() {
        location.reload();
    }
   
    function showAddPatientModal() {
        const modal = new bootstrap.Modal(document.getElementById('addPatientModal'));
        modal.show();
    }
   
    function submitAddToQueue() {
        const form = document.getElementById('addToQueueForm');
        const formData = new FormData(form);
       
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
       
        Swal.fire({
            title: 'Adding to Queue...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
       
        fetch('ajax/add_to_queue.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: 'Patient added to queue successfully',
                    timer: 2000
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: data.message || 'Failed to add patient to queue'
                });
            }
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred. Please try again.'
            });
        });
    }
   
    function callPatient(queueId) {
        Swal.fire({
            title: 'Call Patient?',
            text: 'This will notify the patient via SMS/WhatsApp',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Call Patient',
            confirmButtonColor: '#10b981'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `queue_actions.php?action=call&queue_id=${queueId}`;
            }
        });
    }
   
    function startService(queueId) {
        Swal.fire({
            title: 'Start Service?',
            text: 'Mark this patient as in service?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Start Service',
            confirmButtonColor: '#667eea'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `queue_actions.php?action=start_service&queue_id=${queueId}`;
            }
        });
    }
   
    function transferPatient(queueId) {
        window.location.href = `transfer_patient.php?queue_id=${queueId}`;
    }
   
    function viewDetails(patientId) {
        window.location.href = `view_patient.php?id=${patientId}`;
    }
    </script>
    <script src="assets/js/app.js"></script>
</body>
</html>