<?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 an audiologist
if ($role_code !== 'AUDIOLOGIST') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized role']);
    exit();
}

try {
    // Get audiology-related departments
    $dept_sql = "SELECT department_id FROM departments 
                 WHERE department_code IN ('AUDIOLOGY', 'VESTIBULAR') AND is_active = 1";
    $dept_result = $conn->query($dept_sql);
    $dept_ids = [];
    while ($row = $dept_result->fetch_assoc()) {
        $dept_ids[] = $row['department_id'];
    }
    
    if (empty($dept_ids)) {
        echo json_encode(['success' => true, 'patients' => []]);
        exit();
    }
    
    $dept_ids_str = implode(',', $dept_ids);
    
    // Get queue patients
    $queue_sql = "SELECT q.queue_id, q.queue_number, q.patient_name, q.patient_number, 
                  q.age, q.gender, 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.department_id IN ($dept_ids_str) 
                  AND q.queue_status = 'WAITING' 
                  AND DATE(q.queue_entry_time) = CURDATE()
                  ORDER BY 
                      CASE q.priority
                          WHEN 'EMERGENCY' THEN 1
                          WHEN 'URGENT' THEN 2
                          WHEN 'NORMAL' THEN 3
                      END,
                      q.queue_entry_time
                  LIMIT 10";
    
    $result = $conn->query($queue_sql);
    $patients = [];
    
    while ($row = $result->fetch_assoc()) {
        $patients[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'patients' => $patients
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
