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

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

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

$role_code = $_SESSION['role_code'] ?? '';
if (!in_array($role_code, ['ENT_CONSULTANT', 'ENT_DOCTOR', 'PLASTIC_SURGEON'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized role']);
    exit();
}

try {
    $user_id = (int) $_SESSION['user_id'];

    $doc_stmt = $conn->prepare("SELECT doctor_id FROM doctors WHERE user_id = ? LIMIT 1");
    $doc_stmt->bind_param("i", $user_id);
    $doc_stmt->execute();
    $doc_row = $doc_stmt->get_result()->fetch_assoc();
    $doc_stmt->close();

    $doctor_id = $doc_row ? (int) $doc_row['doctor_id'] : 0;

    /*
     * WHY THE PREVIOUS VERSION FAILED
     * ─────────────────────────────────────────────────────────────────────
     * patient_queue.visit_id is nullable (DEFAULT NULL).
     * All three previous NOT EXISTS blocks joined on  q.visit_id, so when
     * visit_id IS NULL every subquery returned zero rows, NOT EXISTS was
     * always TRUE, and the patient was never excluded — regardless of
     * whether they had already been seen and billed.
     *
     * THE FIX
     * ─────────────────────────────────────────────────────────────────────
     * Use  q.patient_id  (which is NOT NULL on patient_queue) as the join
     * key across all three signals, scoped to CURDATE().
     *
     *  • consultations.patient_id   — NOT NULL
     *  • patient_visits.patient_id  — NOT NULL
     *  • invoices.patient_id        — NOT NULL
     *
     * This means the subqueries always work regardless of whether
     * visit_id was populated on the queue row.
     *
     * SIGNAL LOGIC
     * ─────────────────────────────────────────────────────────────────────
     * Signal 1 — Any non-cancelled consultation exists for this patient
     *            today (any doctor). Once a consultation session opens the
     *            patient is considered "in service" and should leave the
     *            waiting queue.
     *
     * Signal 2 — The linked visit record has moved past WAITING/REGISTERED
     *            into IN_CONSULTATION or COMPLETED today.  This fires even
     *            before the consultation form is saved.
     *
     * Signal 3 — An invoice has been raised beyond DRAFT for this patient
     *            today (cash: INVOICED/PAID; insurance: INSURANCE_PENDING/
     *            SENT/PARTIAL_PAYMENT).  A patient who has been billed has
     *            definitively been seen.
     *
     * Any ONE signal being true is enough to hide the patient.
     */
    $stmt = $conn->prepare("
        SELECT
            q.queue_id,
            q.patient_id,
            q.visit_id,
            q.queue_number,
            q.patient_name,
            q.patient_number,
            q.age,
            q.gender,
            q.priority,
            q.chief_complaint,
            q.queue_status,
            q.position_in_queue,
            TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) AS wait_minutes,
            q.queue_entry_time,
            d.department_name
        FROM patient_queue q
        INNER JOIN departments d ON q.department_id = d.department_id
        WHERE q.queue_status IN ('WAITING', 'IN_SERVICE')
          AND DATE(q.queue_entry_time) = CURDATE()
          AND (
              q.assigned_doctor_id = ?
              OR (
                  d.department_name LIKE '%ENT%'
                  AND (q.assigned_doctor_id IS NULL OR q.assigned_doctor_id = 0)
              )
          )

          /* ── Signal 1: consultation opened today for this patient ─── */
          AND NOT EXISTS (
              SELECT 1
              FROM   consultations c
              WHERE  c.patient_id = q.patient_id
                AND  c.status    NOT IN ('CANCELLED')
                AND  DATE(c.started_at) = CURDATE()
          )

          /* ── Signal 2: visit advanced past waiting today ──────────── */
          AND NOT EXISTS (
              SELECT 1
              FROM   patient_visits pv
              WHERE  pv.patient_id = q.patient_id
                AND  pv.status    IN ('IN_CONSULTATION', 'COMPLETED')
                AND  DATE(pv.registration_date) = CURDATE()
          )

          /* ── Signal 3: invoice raised (cash or insurance) today ───── */
          AND NOT EXISTS (
              SELECT 1
              FROM   invoices inv
              WHERE  inv.patient_id = q.patient_id
                AND  inv.status    NOT IN ('DRAFT', 'CANCELLED')
                AND  DATE(inv.created_at) = CURDATE()
          )

        ORDER BY
            CASE q.priority
                WHEN 'EMERGENCY' THEN 1
                WHEN 'URGENT'    THEN 2
                WHEN 'NORMAL'    THEN 3
            END,
            q.queue_entry_time ASC,
            q.queue_id         ASC
        LIMIT 50
    ");

    /* Only one binding now — doctor_id for the assignment filter.
       All three NOT EXISTS use q.patient_id from the outer query. */
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $queue = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    echo json_encode(['success' => true, 'queue' => $queue]);

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