<?php
/**
 * ajax/reassign_queue_doctor.php
 * Reassign a queued patient to a different doctor (intra-department).
 * Called via POST from the queue dashboard.
 *
 * Required POST params:
 *   queue_id       INT   – patient_queue.queue_id
 *   doctor_id      INT   – doctors.doctor_id  (0 = "Any available")
 *
 * Returns JSON { success, message, [data] }
 */
session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';

header('Content-Type: application/json; charset=utf-8');

/* ── Auth ─────────────────────────────────────────────── */
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit();
}

$allowed_roles = [
    'SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST',
    'FRONT_OFFICE', 'NURSE', 'CHIEF_PHARMACIST'
];
if (!in_array($_SESSION['role_code'] ?? '', $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to reassign queue patients.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit();
}

$queue_id  = (int)($_POST['queue_id']  ?? 0);
$doctor_id = (int)($_POST['doctor_id'] ?? 0);   // 0 = clear / any available
$user_id   = (int)$_SESSION['user_id'];

if ($queue_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid queue entry.']);
    exit();
}

/* ── Fetch queue entry ────────────────────────────────── */
$q = $conn->query("SELECT q.*, d.department_name
                   FROM patient_queue q
                   INNER JOIN departments d ON q.department_id = d.department_id
                   WHERE q.queue_id = $queue_id
                   AND DATE(q.queue_entry_time) = CURDATE()")->fetch_assoc();

if (!$q) {
    echo json_encode(['success' => false, 'message' => 'Queue entry not found.']);
    exit();
}

if (!in_array($q['queue_status'], ['WAITING', 'IN_SERVICE'])) {
    echo json_encode(['success' => false,
        'message' => 'Cannot reassign: patient status is ' . $q['queue_status'] . '.']);
    exit();
}

/* ── Validate new doctor (if specified) ──────────────── */
$doctor_name = null;
$doctor_spec = null;

if ($doctor_id > 0) {
    $dr = $conn->query("SELECT d.doctor_id, u.full_name, d.specialization
                        FROM doctors d
                        INNER JOIN users u ON d.user_id = u.user_id
                        WHERE d.doctor_id = $doctor_id
                        AND d.is_active = 1
                        AND u.status = 'ACTIVE'")->fetch_assoc();
    if (!$dr) {
        echo json_encode(['success' => false, 'message' => 'Selected doctor not found or inactive.']);
        exit();
    }
    $doctor_name = $dr['full_name'];
    $doctor_spec = $dr['specialization'];
}

/* ── Update ───────────────────────────────────────────── */
$old_doctor_id = (int)($q['assigned_doctor_id'] ?? 0);

if ($doctor_id === 0) {
    $set = "assigned_doctor_id = NULL, updated_at = NOW()";
} else {
    $set = "assigned_doctor_id = $doctor_id, updated_at = NOW()";
}

$conn->query("UPDATE patient_queue SET $set WHERE queue_id = $queue_id");

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

/* ── Audit log (if table exists) ─────────────────────── */
$audit_check = $conn->query("SHOW TABLES LIKE 'queue_audit_log'");
if ($audit_check && $audit_check->num_rows > 0) {
    $patient_name  = $conn->real_escape_string($q['patient_name'] ?? '');
    $dept          = $conn->real_escape_string($q['department_name'] ?? '');
    $old_doc_label = $old_doctor_id > 0 ? "Doctor ID $old_doctor_id" : "Any Available";
    $new_doc_label = $doctor_id    > 0 ? "Doctor ID $doctor_id ($doctor_name)" : "Any Available";
    $note          = $conn->real_escape_string("Reassigned: $patient_name ($dept) — $old_doc_label → $new_doc_label");
    $conn->query("INSERT INTO queue_audit_log (queue_id, action, note, performed_by, created_at)
                  VALUES ($queue_id, 'DOCTOR_REASSIGN', '$note', $user_id, NOW())");
}

/* ── Success response ─────────────────────────────────── */
echo json_encode([
    'success'     => true,
    'message'     => $doctor_id > 0
        ? "Patient reassigned to Dr. $doctor_name."
        : "Doctor assignment cleared (any available).",
    'data'        => [
        'queue_id'    => $queue_id,
        'doctor_id'   => $doctor_id,
        'doctor_name' => $doctor_name,
        'doctor_spec' => $doctor_spec,
    ]
]);