<?php
session_start();
ini_set('display_errors', 0); // Hide raw errors from UI
error_reporting(E_ALL);

require_once dirname(__DIR__, 2) . '/dripend/includes/db.php';
if (!isset($conn) && isset($db)) { $conn = $db; }

if (!isset($conn) || !$conn) {
    die("<div style='padding:20px; background:#fee2e2; color:#991b1b; font-family:sans-serif; border-radius:8px;'><b>Fatal Error:</b> Database connection failed.</div>");
}

// ==============================================================================
// GLOBAL ADVANCED FILTERS
// ==============================================================================
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// ==============================================================================
// 1. QUEUE: WAITING FOR DOCTOR (Secure Prepared Statement & Extended Fetch)
// ==============================================================================
$q_pending = "
    SELECT 
        v.id AS visit_id, v.appointment_no, v.patient_no, v.visit_date, v.visit_time, v.status, v.clinical_outcome,
        p.first_name, p.last_name, p.dob, COALESCE(g.gender_name, 'Unknown') AS gender_name,
        COALESCE((
            SELECT d.department_name 
            FROM visit_details vd 
            JOIN service_catalog sc ON vd.service_id = sc.id 
            JOIN departments d ON sc.department_id = d.id 
            WHERE vd.visit_master_id = v.id 
            LIMIT 1
        ), 'General OPD') AS clinic_name,
        COALESCE((
            SELECT sc.service_name 
            FROM visit_details vd 
            JOIN service_catalog sc ON vd.service_id = sc.id 
            WHERE vd.visit_master_id = v.id 
            LIMIT 1
        ), 'Consultation') AS service_name,
        (SELECT COUNT(id) FROM patient_vitals pv WHERE pv.visit_id = v.id OR (pv.patient_no = v.patient_no AND DATE(pv.recorded_at) = CURDATE())) as vitals_taken
    FROM visit_master v 
    JOIN patient p ON v.patient_no = p.patient_no 
    LEFT JOIN gender g ON p.gender_id = g.id
    WHERE v.status IN ('Scheduled', 'Pending', 'In Progress', 'Triaged', 'Vitals Pending') 
    AND (v.clinical_outcome = 'Pending' OR v.clinical_outcome = 'Awaiting Doctor' OR v.clinical_outcome IS NULL OR v.clinical_outcome = '')
    AND DATE(v.visit_date) BETWEEN ? AND ?
    AND (v.nhis_service_type = 'Out-patient' OR v.nhis_service_type IS NULL)
    AND v.id NOT IN (SELECT visit_id FROM clinical_lab_requests WHERE visit_id IS NOT NULL AND status = 'Pending')
    ORDER BY v.visit_date ASC, v.visit_time ASC
";
$stmt_pending = $conn->prepare($q_pending);
$stmt_pending->bind_param("ss", $start_date, $end_date);
$stmt_pending->execute();
$res_pending = $stmt_pending->get_result();
$stmt_pending->close();

// ==============================================================================
// 2. QUEUE: AWAITING LAB RESULTS (Secure Prepared Statement)
// ==============================================================================
$q_labs = "
    SELECT 
        v.id AS visit_id, v.patient_no, v.visit_date, v.visit_time, v.status, v.clinical_outcome,
        p.first_name, p.last_name, p.dob, COALESCE(g.gender_name, 'Unknown') AS gender_name,
        COALESCE((
            SELECT d.department_name 
            FROM visit_details vd 
            JOIN service_catalog sc ON vd.service_id = sc.id 
            JOIN departments d ON sc.department_id = d.id 
            WHERE vd.visit_master_id = v.id 
            LIMIT 1
        ), 'General OPD') AS clinic_name,
        COALESCE((
            SELECT sc.service_name 
            FROM visit_details vd 
            JOIN service_catalog sc ON vd.service_id = sc.id 
            WHERE vd.visit_master_id = v.id 
            LIMIT 1
        ), 'Consultation') AS service_name
    FROM visit_master v 
    JOIN patient p ON v.patient_no = p.patient_no 
    LEFT JOIN gender g ON p.gender_id = g.id
    WHERE (v.status = 'Pending Labs' OR v.clinical_outcome = 'Awaiting Labs')
    AND DATE(v.visit_date) BETWEEN ? AND ?
    AND v.id IN (SELECT visit_id FROM clinical_notes WHERE visit_id IS NOT NULL)
    ORDER BY v.visit_date ASC, v.visit_time ASC
";
$stmt_labs = $conn->prepare($q_labs);
$stmt_labs->bind_param("ss", $start_date, $end_date);
$stmt_labs->execute();
$res_labs = $stmt_labs->get_result();
$stmt_labs->close();

// ==============================================================================
// 3. QUEUE: COMPLETED / FINALIZED ARCHIVE (Secure Prepared Statement)
// ==============================================================================
$q_completed = "
    SELECT 
        v.id AS visit_id, v.patient_no, v.visit_date, v.visit_time, v.status, v.clinical_outcome,
        p.first_name, p.last_name, p.dob, COALESCE(g.gender_name, 'Unknown') AS gender_name,
        COALESCE((
            SELECT d.department_name 
            FROM visit_details vd 
            JOIN service_catalog sc ON vd.service_id = sc.id 
            JOIN departments d ON sc.department_id = d.id 
            WHERE vd.visit_master_id = v.id 
            LIMIT 1
        ), 'General OPD') AS clinic_name,
        COALESCE((
            SELECT sc.service_name 
            FROM visit_details vd 
            JOIN service_catalog sc ON vd.service_id = sc.id 
            WHERE vd.visit_master_id = v.id 
            LIMIT 1
        ), 'Consultation') AS service_name
    FROM visit_master v 
    JOIN patient p ON v.patient_no = p.patient_no 
    LEFT JOIN gender g ON p.gender_id = g.id
    WHERE v.status = 'Completed'
    AND DATE(v.visit_date) BETWEEN ? AND ?
    AND (v.nhis_service_type = 'Out-patient' OR v.nhis_service_type IS NULL)
    ORDER BY v.visit_date DESC, v.visit_time DESC
";
$stmt_comp = $conn->prepare($q_completed);
$stmt_comp->bind_param("ss", $start_date, $end_date);
$stmt_comp->execute();
$res_completed = $stmt_comp->get_result();
$stmt_comp->close();

function calculateAge($dob) {
    if (empty($dob) || $dob === '0000-00-00') return '--';
    $birthDate = new DateTime($dob);
    return $birthDate->diff(new DateTime('today'))->y;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Consultation Queue | eRHAMS</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{ --sidebar-width:290px; --bg:#f1f5f9; --accent-dark:#0f172a; --accent-mid:#0284c7; --border:#e2e8f0; --muted:#64748b; --success:#10b981; --danger:#ef4444; }
*{box-sizing:border-box;margin:0;padding:0;font-family:'Inter',system-ui,sans-serif;}
body{background:var(--bg);color:#1e293b;}

/* Strict Layout Sync */
.page-wrapper { margin-left: var(--sidebar-width) !important; padding: 2.5rem; width: calc(100% - var(--sidebar-width)); min-height: 100vh; box-sizing: border-box; }
@media (max-width: 992px) { .page-wrapper { margin-left: 0 !important; width: 100% !important; padding: 1.5rem; } }

.dashboard-header { margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid var(--border); padding-bottom: 15px;}
.page-title { font-size: 22px; font-weight: 800; color: var(--accent-dark); display: flex; align-items: center; gap: 10px; }

/* Filter Bars */
.filter-bar { background: #fff; padding: 18px 24px; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); display: flex; gap: 20px; align-items: center; margin-bottom: 25px; border: 1px solid #e2e8f0; flex-wrap: wrap;}
.filter-group { display: flex; align-items: center; gap: 12px; }
.filter-group label { font-size: 11px; font-weight: 800; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;}
.input-control { padding: 10px 14px; border-radius: 8px; border: 1px solid #cbd5e1; outline: none; font-size:13px; font-weight: 600; background: #f8fafc; transition: 0.2s;}
.input-control:focus { border-color: var(--accent-mid); background:#fff; box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.15); }

/* Buttons */
.btn-cute { padding: 8px 18px; border-radius: 20px; font-weight: 700; font-size: 12px; transition: 0.2s; cursor:pointer; border:none; display: inline-flex; align-items: center; justify-content:center; gap: 6px; text-decoration: none;}
.btn-primary { background: var(--accent-mid); color: #fff; box-shadow: 0 4px 6px rgba(2, 132, 199, 0.2); }
.btn-primary:hover { transform: translateY(-1px); background: #0369a1; color:#fff; }
.btn-warning { background: #f59e0b; color: #fff; }
.btn-warning:hover { background: #d97706; transform: translateY(-1px); color:#fff; }
.btn-success { background: var(--success); color: #fff; }
.btn-success:hover { background: #059669; color:#fff; }

/* Grid Layouts */
.queue-container { display: grid; grid-template-columns: 1.6fr 1fr; gap: 25px; margin-bottom: 25px; }
@media (max-width: 1200px) { .queue-container { grid-template-columns: 1fr; } }
.queue-card { background: #fff; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; border: 1px solid var(--border); }
.queue-card.full-width { grid-column: 1 / -1; }
.queue-header { padding: 16px 20px; font-weight: 800; font-size: 15px; display: flex; justify-content: space-between; align-items: center; }
.queue-header.blue { background: #f0f9ff; color: #0369a1; border-bottom: 2px solid #bae6fd; }
.queue-header.orange { background: #fffbeb; color: #b45309; border-bottom: 2px solid #fde68a; }
.queue-header.green { background: #f0fdf4; color: #166534; border-bottom: 2px solid #bbf7d0; }
.badge { background: #fff; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 800; border: 1px solid currentColor; }

/* Tables */
.table-wrapper { overflow-y: auto; max-height: 550px; }
table { width: 100%; border-collapse: collapse; text-align: left; font-size: 13px; }
th { padding: 14px 20px; color: var(--muted); border-bottom: 2px solid var(--border); font-weight: 800; text-transform: uppercase; font-size: 11px; position: sticky; top: 0; background: #fff; z-index: 10; letter-spacing: 0.5px; }
td { padding: 16px 20px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
tr:hover td { background: #f8fafc; }
.patient-name { font-weight: 800; color: var(--accent-dark); display: block; font-size: 14px; margin-bottom: 4px;}
.patient-meta { color: var(--muted); font-size: 12px; font-weight: 600;}
.empty-queue { text-align: center; padding: 60px 20px; color: var(--muted); }
.clinic-tag { background: #f8fafc; padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; color: #0284c7; border: 1px solid #e0f2fe; display: inline-block; margin-top: 6px; }
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">
    
    <div class="dashboard-header">
        <div class="page-title"><i class="fa-solid fa-layer-group" style="color:var(--accent-mid);"></i> Dynamic Consulting Room Queue</div>
    </div>

    <div class="filter-bar">
        <form action="" method="GET" style="display:flex; flex-wrap:wrap; gap:20px; align-items:center; width:100%; justify-content: space-between;">
            
            <div class="filter-group">
                <label><i class="fa-solid fa-calendar-days text-muted me-1"></i> Operational Window:</label>
                <div style="display:flex; gap:10px; align-items:center;">
                    <input type="date" name="start_date" class="input-control" value="<?php echo htmlspecialchars($start_date); ?>">
                    <span style="color:var(--muted); font-weight:800; font-size:11px;">TO</span>
                    <input type="date" name="end_date" class="input-control" value="<?php echo htmlspecialchars($end_date); ?>">
                    <button type="submit" class="btn-primary btn-cute"><i class="fa-solid fa-filter"></i> Apply Filter</button>
                </div>
            </div>

            <div style="border-left: 2px solid var(--border); padding-left: 20px; display:flex; gap:12px; align-items:center;">
                <label style="font-weight:800; color:var(--accent-dark); font-size:11px;">DIRECT ACCESS:</label>
                <input type="text" id="direct_visit_id" class="input-control" placeholder="Enter Encounter ID..." style="width:160px; font-weight:700;">
                <button type="button" class="btn-warning btn-cute" onclick="const val = document.getElementById('direct_visit_id').value; if(val) window.location.href='addConsultation.php?visit_id='+val;">Open Room <i class="fa-solid fa-arrow-right-to-bracket"></i></button>
            </div>
            
        </form>
    </div>

    <div class="queue-container">
        
        <!-- WAITING FOR DOCTOR SECTION -->
        <div class="queue-card">
            <div class="queue-header blue">
                <span><i class="fa-solid fa-user-doctor me-2"></i> Attending / Waiting Queue</span>
                <span class="badge"><?php echo $res_pending ? $res_pending->num_rows : 0; ?> Patients</span>
            </div>
            <div class="table-wrapper">
                <?php if($res_pending && $res_pending->num_rows > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Encounter / Time</th>
                            <th>Patient Demographic Matrix</th>
                            <th>Triage Resolution</th>
                            <th style="text-align:right;">Clinical Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = $res_pending->fetch_assoc()): ?>
                        <tr>
                            <td style="font-weight:700; color:var(--accent-mid); font-size:12px; line-height:1.5;">
                                <span style="color:#0f172a; font-weight:800; font-size:13px;">#<?php echo $row['visit_id']; ?></span><br>
                                <?php echo date('d-M-Y', strtotime($row['visit_date'])); ?><br>
                                <span style="color:var(--muted);"><i class="fa-regular fa-clock"></i> <?php echo date('h:i A', strtotime($row['visit_time'])); ?></span>
                            </td>
                            <td>
                                <span class="patient-name"><?php echo htmlspecialchars($row['first_name'].' '.$row['last_name']); ?></span>
                                <span class="patient-meta"><?php echo htmlspecialchars($row['patient_no']); ?> &bull; <?php echo htmlspecialchars($row['gender_name']); ?> &bull; <?php echo calculateAge($row['dob']); ?> yrs</span><br>
                                <span class="clinic-tag"><i class="fa-solid fa-stethoscope me-1"></i> <?php echo htmlspecialchars($row['service_name']); ?> (<?php echo htmlspecialchars($row['clinic_name']); ?>)</span>
                            </td>
                            <td>
                                <?php if($row['vitals_taken'] > 0): ?>
                                    <span style="color:var(--success); font-size:12px; font-weight:800; display:block; margin-bottom:6px;"><i class="fa-solid fa-circle-check"></i> Triage Settled</span>
                                <?php else: ?>
                                    <span style="color:var(--danger); font-size:12px; font-weight:800; display:block; margin-bottom:6px;"><i class="fa-solid fa-triangle-exclamation"></i> Vitals Outstanding</span>
                                <?php endif; ?>
                                <span style="background:#f1f5f9; padding:4px 10px; border-radius:6px; font-size:10px; font-weight:800; color:#475569; text-transform:uppercase; border:1px solid #e2e8f0;"><?php echo htmlspecialchars($row['status']); ?></span>
                            </td>
                            <td style="text-align:right;">
                                <a href="addConsultation.php?visit_id=<?php echo $row['visit_id']; ?>" class="btn-primary btn-cute"><i class="fa-solid fa-stethoscope"></i> Attend</a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <div class="empty-queue">
                    <i class="fa-solid fa-mug-hot" style="font-size:42px; color:#cbd5e1; margin-bottom:15px;"></i>
                    <p style="font-weight:700; font-size:15px; color:#334155;">Queue Clear</p>
                    <p style="color:var(--muted); font-size:13px;">No patients currently routed to this station.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- AWAITING LABS SECTION -->
        <div class="queue-card">
            <div class="queue-header orange">
                <span><i class="fa-solid fa-flask-vial me-2"></i> Diagnostics Pending</span>
                <span class="badge"><?php echo $res_labs ? $res_labs->num_rows : 0; ?> Patients</span>
            </div>
            <div class="table-wrapper">
                <?php if($res_labs && $res_labs->num_rows > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Encounter</th>
                            <th>Patient Matrix</th>
                            <th style="text-align:right;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = $res_labs->fetch_assoc()): ?>
                        <tr>
                            <td style="font-weight:700; color:#b45309; font-size:12px; line-height:1.5;">
                                <span style="font-size:13px;">#<?php echo $row['visit_id']; ?></span><br>
                                <span style="color:var(--muted);"><i class="fa-regular fa-clock"></i> <?php echo date('h:i A', strtotime($row['visit_time'])); ?></span>
                            </td>
                            <td>
                                <span class="patient-name"><?php echo htmlspecialchars($row['first_name'].' '.$row['last_name']); ?></span>
                                <span class="patient-meta"><?php echo htmlspecialchars($row['patient_no']); ?> &bull; <?php echo calculateAge($row['dob']); ?> yrs</span><br>
                                <span class="clinic-tag"><i class="fa-solid fa-syringe me-1"></i> <?php echo htmlspecialchars($row['service_name']); ?></span>
                            </td>
                            <td style="text-align:right;">
                                <a href="addConsultation.php?visit_id=<?php echo $row['visit_id']; ?>" class="btn-warning btn-cute"><i class="fa-solid fa-arrow-rotate-right"></i> Resume</a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <div class="empty-queue">
                    <i class="fa-solid fa-vials" style="font-size:42px; color:#cbd5e1; margin-bottom:15px;"></i>
                    <p style="font-weight:700; font-size:15px; color:#334155;">No Pending Trackers</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- COMPLETED ENCOUNTERS ARCHIVE -->
        <div class="queue-card full-width">
            <div class="queue-header green">
                <span><i class="fa-solid fa-box-archive me-2"></i> Finalized / Signed Encounters</span>
                <span class="badge"><?php echo $res_completed ? $res_completed->num_rows : 0; ?> Records</span>
            </div>
            <div class="table-wrapper" style="max-height: 400px;">
                <?php if($res_completed && $res_completed->num_rows > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Master ID</th>
                            <th>Date & Time Status</th>
                            <th>Patient Demographics</th>
                            <th>Clinical Outcome Resolution</th>
                            <th style="text-align:right;">Registry Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = $res_completed->fetch_assoc()): ?>
                        <tr>
                            <td><strong style="color:var(--muted); font-family:monospace; font-size:14px;">#<?php echo str_pad($row['visit_id'], 6, '0', STR_PAD_LEFT); ?></strong></td>
                            <td style="font-weight:700; color:var(--accent-dark); font-size:13px;">
                                <?php echo date('d-M-Y', strtotime($row['visit_date'])); ?> <span style="color:var(--muted); font-size:12px;">@ <?php echo date('h:i A', strtotime($row['visit_time'])); ?></span>
                            </td>
                            <td>
                                <span class="patient-name"><?php echo htmlspecialchars($row['first_name'].' '.$row['last_name']); ?></span>
                                <span class="patient-meta"><?php echo htmlspecialchars($row['patient_no']); ?> &bull; <?php echo htmlspecialchars($row['gender_name']); ?> &bull; <?php echo calculateAge($row['dob']); ?> yrs</span><br>
                                <span class="clinic-tag"><i class="fa-solid fa-circle-check" style="color:var(--success);"></i> <?php echo htmlspecialchars($row['service_name']); ?></span>
                            </td>
                            <td>
                                <span style="background:#f8fafc; color:#475569; padding:6px 14px; border-radius:20px; font-size:11px; font-weight:800; border:1px solid #cbd5e1; display:inline-block;">
                                    <i class="fa-solid fa-arrow-right-from-bracket" style="color:var(--success); margin-right:4px;"></i> <?php echo htmlspecialchars($row['clinical_outcome']); ?>
                                </span>
                            </td>
                            <td style="text-align:right;">
                                <a href="updateConsultation.php?visit_id=<?php echo $row['visit_id']; ?>" class="btn-success btn-cute" style="background:#f8fafc; color:#16a34a; border:1px solid #16a34a; box-shadow:none;">
                                    <i class="fa-solid fa-pen-to-square"></i> Update Consultation
                                </a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <div class="empty-queue" style="padding: 40px 20px;">
                    <i class="fa-solid fa-folder-closed" style="font-size:42px; color:#cbd5e1; margin-bottom:15px;"></i>
                    <p style="font-weight:700; font-size:15px; color:#334155;">No closed files found within this scope.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>
</body>
</html>