<?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();
}

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'] ?? '';
$last_id = intval($_GET['last_id'] ?? 0);
$role = $_GET['role'] ?? '';

$today = date('Y-m-d');
$new_entries = [];
$queue_count = 0;

try {
    // Determine which departments to check based on role
    $department_codes = [];
    if ($role === 'nurse' || $role_code === 'HEAD_NURSE' || $role_code === 'ENT_NURSE') {
        $department_codes = ['TRIAGE', 'NURSING'];
    } elseif ($role === 'doctor' || $role_code === 'ENT_CONSULTANT' || $role_code === 'ENT_DOCTOR') {
        $department_codes = ['CONSULTATION'];
    } elseif ($role === 'audiologist' || $role_code === 'AUDIOLOGIST') {
        $department_codes = ['AUDIOLOGY', 'VESTIBULAR'];
    } elseif ($role === 'lab' || $role_code === 'LAB_TECHNICIAN') {
        $department_codes = ['LABORATORY'];
    } else {
        // Default: check all departments
        $department_codes = [];
    }
    
    // Build department filter
    $dept_filter = '';
    if (!empty($department_codes)) {
        $placeholders = implode(',', array_fill(0, count($department_codes), '?'));
        $dept_filter = "AND d.department_code IN ($placeholders)";
    }
    
    // Get new queue entries since last check
    if ($last_id > 0) {
        $new_entries_sql = "SELECT q.queue_id, q.queue_number, q.patient_name, q.patient_number, 
                           q.priority, q.queue_entry_time, q.chief_complaint, d.department_name
                           FROM patient_queue q
                           INNER JOIN departments d ON q.department_id = d.department_id
                           WHERE q.queue_id > ? 
                           AND q.queue_status = 'WAITING'
                           AND DATE(q.queue_entry_time) = ?
                           $dept_filter
                           ORDER BY q.queue_id DESC
                           LIMIT 10";
        
        $stmt = $conn->prepare($new_entries_sql);
        if (!empty($department_codes)) {
            $params = array_merge([$last_id, $today], $department_codes);
            $types = 'is' . str_repeat('s', count($department_codes));
            $stmt->bind_param($types, ...$params);
        } else {
            $stmt->bind_param("is", $last_id, $today);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $new_entries[] = $row;
        }
    }
    
    // Get current queue count
    if (!empty($department_codes)) {
        $count_sql = "SELECT COUNT(*) as count 
                     FROM patient_queue q
                     INNER JOIN departments d ON q.department_id = d.department_id
                     WHERE q.queue_status = 'WAITING'
                     AND DATE(q.queue_entry_time) = ?
                     $dept_filter";
        
        $stmt = $conn->prepare($count_sql);
        $params = array_merge([$today], $department_codes);
        $types = 's' . str_repeat('s', count($department_codes));
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $count_result = $stmt->get_result();
        $queue_count = $count_result->fetch_assoc()['count'];
    }
    
    echo json_encode([
        'success' => true,
        'new_entries' => $new_entries,
        'queue_count' => $queue_count,
        'last_id' => $last_id
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
