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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$view_mode = isset($_GET['view']) && $_GET['view'] === 'history' ? 'history' : 'current';
$department_filter = isset($_GET['department']) ? $_GET['department'] : 'all';
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'active';

if ($department_filter !== 'all') {
    $department_filter = (string) intval($department_filter);
}
$status_filter = in_array($status_filter, ['active', 'waiting', 'in_service'], true) ? $status_filter : 'active';

try {
    if ($view_mode === 'history') {
        $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_name, q.queue_status, q.priority,
            q.queue_entry_time, q.service_start_time, q.service_end_time, q.total_wait_minutes,
            q.total_service_minutes, q.serving_staff_name, q.has_appointment, q.is_vip,
            q.chief_complaint, q.updated_at
            FROM patient_queue q
            INNER JOIN departments d ON q.department_id = d.department_id
            WHERE DATE(q.queue_entry_time) = CURDATE()
            AND q.queue_status IN ('COMPLETED', 'CANCELLED', 'NO_SHOW', 'TRANSFERRED')
            ORDER BY q.updated_at DESC, q.queue_entry_time DESC";
    } else {
        // Unseen queue only: vitals not yet taken
        $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_name, q.queue_status, q.priority,
            q.position_in_queue, q.estimated_wait_minutes, q.chief_complaint, q.is_vip,
            q.assigned_doctor_id, u_doc.full_name as assigned_doctor_name, doc.specialization as assigned_doctor_specialization,
            q.queue_entry_time, q.service_start_time,
            TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) as actual_wait_minutes
            FROM patient_queue q
            INNER JOIN departments d ON q.department_id = d.department_id
            LEFT JOIN doctors doc ON q.assigned_doctor_id = doc.doctor_id
            LEFT JOIN users u_doc ON doc.user_id = u_doc.user_id
            WHERE DATE(q.queue_entry_time) = CURDATE()
            AND q.queue_status IN ('WAITING', 'IN_SERVICE')
            AND (q.vitals_taken = 0 OR q.vitals_taken IS NULL)";
        if ($department_filter !== 'all') {
            $queue_sql .= " AND q.department_id = " . intval($department_filter);
        }
        if ($status_filter === 'waiting') {
            $queue_sql .= " AND q.queue_status = 'WAITING'";
        } elseif ($status_filter === 'in_service') {
            $queue_sql .= " AND q.queue_status = 'IN_SERVICE'";
        }
        // PRODIGY NOTES Item #17: Order by earliest registered first
        $queue_sql .= " ORDER BY q.queue_entry_time ASC, CASE q.priority WHEN 'EMERGENCY' THEN 1 WHEN 'URGENT' THEN 2 WHEN 'NORMAL' THEN 3 END";
    }

    $queue_result = $conn->query($queue_sql);
    $queue = [];
    while ($row = $queue_result->fetch_assoc()) {
        $queue[] = $row;
    }

    // Counts for unseen queue (vitals not taken)
    $counts_sql = "SELECT
        COUNT(CASE WHEN queue_status IN ('WAITING', 'IN_SERVICE') AND (vitals_taken = 0 OR vitals_taken IS NULL) THEN 1 END) as active_count,
        COUNT(CASE WHEN queue_status = 'WAITING' AND (vitals_taken = 0 OR vitals_taken IS NULL) THEN 1 END) as waiting_count,
        COUNT(CASE WHEN queue_status = 'IN_SERVICE' AND (vitals_taken = 0 OR vitals_taken IS NULL) THEN 1 END) as in_service_count,
        COUNT(CASE WHEN queue_status = 'COMPLETED' THEN 1 END) as completed_count,
        COUNT(CASE WHEN priority = 'EMERGENCY' AND (vitals_taken = 0 OR vitals_taken IS NULL) 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();

    echo json_encode([
        'success' => true,
        'view_mode' => $view_mode,
        'counts' => $counts,
        'queue' => $queue
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage(), 'counts' => [], 'queue' => []]);
}
