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

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

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

$role_code = $_SESSION['role_code'] ?? '';

// Verify it's a nurse
if ($role_code !== 'HEAD_NURSE' && $role_code !== 'ENT_NURSE') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized role']);
    exit();
}

try {
    $today = date('Y-m-d');
    
    // Get triage department (department_id = 2 as per user's code)
    $triage_dept_id = 2;
    
    // Get metrics
    $metrics = [];
    
    // Patients needing vital signs today
    $vitals_needed_sql = "SELECT COUNT(*) as count FROM patient_queue
                         WHERE DATE(queue_entry_time) = ? 
                         AND queue_status IN ('WAITING', 'IN_SERVICE')
                         AND department_id = ?
                         AND vitals_taken = 0";
    $stmt = $conn->prepare($vitals_needed_sql);
    $stmt->bind_param("si", $today, $triage_dept_id);
    $stmt->execute();
    $metrics['vitals_needed'] = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // Patients in triage queue today
    $triage_queue_sql = "SELECT COUNT(*) as count FROM patient_queue
                        WHERE DATE(queue_entry_time) = ?
                        AND department_id = ?
                        AND queue_status IN ('WAITING', 'IN_SERVICE')";
    $stmt = $conn->prepare($triage_queue_sql);
    $stmt->bind_param("si", $today, $triage_dept_id);
    $stmt->execute();
    $metrics['triage_queue'] = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // Triage vitals completed today (count of patients who had vitals taken in triage today)
    $completed_today_sql = "SELECT COUNT(*) as count FROM patient_queue
                            WHERE DATE(queue_entry_time) = ?
                            AND department_id = ?
                            AND (vitals_taken = 1)";
    $stmt = $conn->prepare($completed_today_sql);
    $stmt->bind_param("si", $today, $triage_dept_id);
    $stmt->execute();
    $metrics['completed_today'] = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // Get full triage queue (no limit - for nurse dashboard full queue)
    $triage_details_sql = "SELECT 
        q.queue_id,
        q.queue_number,
        q.patient_id,
        q.visit_id,
        q.patient_name,
        q.patient_number,
        q.age,
        q.gender,
        q.phone_number,
        q.chief_complaint,
        q.triage_category,
        COALESCE(q.triage_priority, q.priority) AS priority,
        q.queue_status,
        q.vitals_taken,
        q.vital_signs_id,
        q.queue_entry_time,
        TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) as wait_minutes,
        q.position_in_queue
    FROM patient_queue q
    WHERE DATE(q.queue_entry_time) = ?
    AND q.department_id = ?
    AND q.queue_status IN ('WAITING', 'IN_SERVICE')
    ORDER BY 
        CASE COALESCE(q.triage_priority, q.priority)
            WHEN 'EMERGENCY' THEN 1
            WHEN 'URGENT' THEN 2
            WHEN 'NORMAL' THEN 3
        END,
        q.queue_entry_time";
    
    $stmt = $conn->prepare($triage_details_sql);
    $stmt->bind_param("si", $today, $triage_dept_id);
    $stmt->execute();
    $triage_result = $stmt->get_result();
    
    $triage_patients = [];
    while ($row = $triage_result->fetch_assoc()) {
        $triage_patients[] = $row;
    }
    $stmt->close();
    
    // Procedures assisting today
    $user_id = $_SESSION['user_id'];
    $assisting_procedures_sql = "SELECT COUNT(*) as count FROM patient_procedures 
                                WHERE DATE(procedure_date) = ? 
                                AND status IN ('SCHEDULED', 'PREPARING', 'IN_PROGRESS')";
    $stmt = $conn->prepare($assisting_procedures_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $metrics['assisting_procedures'] = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    echo json_encode([
        'success' => true,
        'metrics' => $metrics,
        'triage_patients' => $triage_patients,
        'has_waiting_patients' => $metrics['triage_queue'] > 0
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
