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

if (!isset($_SESSION['user_id'])) { http_response_code(401); exit(); }

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

$dept_id = isset($_GET['department_id']) ? (int)$_GET['department_id'] : 0;
if (!$dept_id) { echo json_encode(['success' => false, 'message' => 'No department specified']); exit(); }

// Fetch doctors assigned to the department with their current queue size
// and a simple availability flag. Adjust the join to match your schema.
$sql = "
    SELECT
        d.doctor_id,
        u.full_name,
        d.specialization,
        COALESCE(d.is_available, 1)                                          AS is_available,
        (
            SELECT COUNT(*)
            FROM patient_queue pq
            WHERE pq.assigned_doctor_id = d.doctor_id
              AND pq.queue_status IN ('WAITING', 'IN_SERVICE')
              AND DATE(pq.queue_entry_time) = CURDATE()
        )                                                                     AS queue_count
    FROM doctors d
    JOIN users u ON d.user_id = u.user_id
    WHERE d.department_id = ?
      AND d.status = 'ACTIVE'
    ORDER BY is_available DESC, queue_count ASC, u.full_name ASC
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Query error: ' . $conn->error]);
    exit();
}

$stmt->bind_param('i', $dept_id);
$stmt->execute();
$doctors = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

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