<?php
header('Content-Type: application/json');
session_start();
ob_start();

include '../layouts/dbconn.php';

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

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

if (!in_array($role_code, ['HEAD_NURSE', 'ENT_NURSE', 'SUPER_ADMIN', 'HOSPITAL_ADMIN'])) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// ── Inputs ────────────────────────────────────────────────────────────────────
$queue_id             = isset($_POST['queue_id'])             ? (int)$_POST['queue_id']             : 0;
$target_department_id = isset($_POST['target_department_id']) ? (int)$_POST['target_department_id'] : 0;
$routing_notes        = trim($_POST['routing_notes']          ?? '');
$route_to_doctor_raw  = trim($_POST['route_to_doctor_id']     ?? '');

if (!$queue_id || !$target_department_id) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Queue ID and target department are required']);
    exit();
}

try {
    $conn->begin_transaction();

    // ── 1. Fetch source queue row ─────────────────────────────────────────────
    $stmt = $conn->prepare("SELECT * FROM patient_queue WHERE queue_id = ? LIMIT 1");
    $stmt->bind_param("i", $queue_id);
    $stmt->execute();
    $q = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$q) throw new Exception("Queue record not found");

    // ── 2. Fetch target department ────────────────────────────────────────────
    $stmt = $conn->prepare(
        "SELECT department_id, department_code, department_name
         FROM departments WHERE department_id = ? AND is_active = 1 LIMIT 1"
    );
    $stmt->bind_param("i", $target_department_id);
    $stmt->execute();
    $dept = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$dept) throw new Exception("Target department not found or inactive");

    // ── 3. Effective priority ─────────────────────────────────────────────────
    $priority = $q['triage_priority'] ?? $q['priority'] ?? 'NORMAL';

    // ── 4. Safe registration_type ─────────────────────────────────────────────
    $valid_reg = ['WALK_IN', 'INSURANCE', 'PRO_BONO'];
    $reg_type  = strtoupper(trim((string)($q['registration_type'] ?? '')));
    $reg_type  = in_array($reg_type, $valid_reg, true) ? $reg_type : 'WALK_IN';

    // ── 5. Resolve doctor assignment from "d_N" or "a_N" prefixed value ───────
    $assigned_doctor_id = null;
    if (preg_match('/^d_(\d+)$/', $route_to_doctor_raw, $m)) {
        $assigned_doctor_id = (int)$m[1];
    } elseif (!empty($q['assigned_doctor_id'])) {
        $assigned_doctor_id = (int)$q['assigned_doctor_id'];
    }

    // ── 6. Mark source queue entry as ROUTED ──────────────────────────────────
    $next_dept_str = (string)$target_department_id;
    $stmt = $conn->prepare(
        "UPDATE patient_queue
         SET queue_status            = 'ROUTED',
             routed_to_department_id = ?,
             next_department_id      = ?,
             routed_at               = NOW(),
             routed_by               = ?,
             service_end_time        = NOW(),
             position_in_queue       = NULL
         WHERE queue_id = ?"
    );
    // 4 params: i s i i
    $stmt->bind_param("isii", $target_department_id, $next_dept_str, $user_id, $queue_id);
    $stmt->execute();
    $stmt->close();

    // ── 7. Generate new queue number for target department ────────────────────
    $stmt = $conn->prepare(
        "SELECT COUNT(*) AS cnt FROM patient_queue
         WHERE department_id = ? AND DATE(queue_entry_time) = CURDATE()"
    );
    $stmt->bind_param("i", $target_department_id);
    $stmt->execute();
    $cnt = (int)$stmt->get_result()->fetch_assoc()['cnt'];
    $stmt->close();

    $new_queue_number = $dept['department_code'] . '-' . date('Ymd') . '-' . str_pad($cnt + 1, 3, '0', STR_PAD_LEFT);

    // ── 8. Calculate position and estimated wait ──────────────────────────────
    $stmt = $conn->prepare(
        "SELECT COUNT(*) + 1 AS pos FROM patient_queue
         WHERE department_id = ? AND queue_status = 'WAITING' AND DATE(queue_entry_time) = CURDATE()"
    );
    $stmt->bind_param("i", $target_department_id);
    $stmt->execute();
    $position       = (int)$stmt->get_result()->fetch_assoc()['pos'];
    $estimated_wait = ($position - 1) * 15;
    $stmt->close();

    // ── 9. Insert new queue row in target department ──────────────────────────
    //
    // Columns (25 bound + 4 literals: 'WAITING', NULL, '', NOW()):
    //
    //  #   Column                    Type  Variable
    //  1   queue_number              s     $new_queue_number
    //  2   patient_id                i     $q['patient_id']
    //  3   visit_id                  i     $q['visit_id']
    //  4   department_id             i     $target_department_id
    //  --- 'WAITING' literal ---
    //  5   priority                  s     $priority
    //  6   registration_priority     s     $priority
    //  7   triage_priority           s     $priority
    //  8   registration_type         s     $reg_type
    //  9   patient_name              s     $q['patient_name']
    //  10  patient_number            s     $q['patient_number']
    //  11  phone_number              s     $q['phone_number']
    //  12  age                       s     $q['age']
    //  13  gender                    s     $q['gender']
    //  14  service_type              s     $q['service_type']
    //  15  assigned_doctor_id        i     $assigned_doctor_id
    //  16  chief_complaint           s     $q['chief_complaint']
    //  17  special_needs             s     $q['special_needs']
    //  18  is_vip                    i     $q['is_vip']
    //  19  vitals_taken              i     $q['vitals_taken']
    //  20  vital_signs_id            i     $q['vital_signs_id']
    //  21  previous_department_id    i     $q['department_id']
    //  22  transfer_reason           s     $transfer_reason
    //  --- NULL, '' literals ---
    //  23  position_in_queue         i     $position
    //  24  estimated_wait_minutes    i     $estimated_wait
    //  25  created_by                i     $user_id
    //  --- NOW() literal ---
    //
    // Format string = "siii" + "ssss" + "ssssssi" + "ssi" + "iii" + "i" + "s" + "iii"
    //               = s s s s s s s s s s s s s i s s i i i i s i i i  = 25 chars

    $transfer_reason = 'Routed from Triage after vitals';

    $stmt = $conn->prepare(
        "INSERT INTO patient_queue (
            queue_number,
            patient_id, visit_id, department_id,
            queue_status,
            priority, registration_priority, triage_priority,
            registration_type,
            patient_name, patient_number, phone_number, age, gender,
            service_type, assigned_doctor_id,
            chief_complaint, special_needs, is_vip,
            vitals_taken, vital_signs_id, previous_department_id,
            transfer_reason,
            referred_by, transfer_notes,
            position_in_queue, estimated_wait_minutes,
            created_by, created_at
         ) VALUES (
            ?,
            ?, ?, ?,
            'WAITING',
            ?, ?, ?,
            ?,
            ?, ?, ?, ?, ?,
            ?, ?,
            ?, ?, ?,
            ?, ?, ?,
            ?,
            NULL, '',
            ?, ?,
            ?, NOW()
         )"
    );

    // 25 params — format string exactly 25 chars:
    // s  i  i  i  s  s  s  s  s  s  s  s  s  s  i  s  s  i  i  i  i  s  i  i  i
    // 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
    $stmt->bind_param(
        "siiissssssssssissiiiisiii",
        $new_queue_number,           // 1  s
        $q['patient_id'],            // 2  i
        $q['visit_id'],              // 3  i
        $target_department_id,       // 4  i
        $priority,                   // 5  s
        $priority,                   // 6  s
        $priority,                   // 7  s
        $reg_type,                   // 8  s
        $q['patient_name'],          // 9  s
        $q['patient_number'],        // 10 s
        $q['phone_number'],          // 11 s
        $q['age'],                   // 12 s
        $q['gender'],                // 13 s
        $q['service_type'],          // 14 s
        $assigned_doctor_id,         // 15 i
        $q['chief_complaint'],       // 16 s
        $q['special_needs'],         // 17 s
        $q['is_vip'],                // 18 i
        $q['vitals_taken'],          // 19 i
        $q['vital_signs_id'],        // 20 i
        $q['department_id'],         // 21 i  → previous_department_id
        $transfer_reason,            // 22 s
        $position,                   // 23 i
        $estimated_wait,             // 24 i
        $user_id                     // 25 i
    );

    if (!$stmt->execute()) {
        throw new Exception("Failed to create new queue entry: " . $stmt->error);
    }
    $new_queue_id = $conn->insert_id;
    $stmt->close();

    // ── 10. Update patient_visits.current_department_id ──────────────────────
    if (!empty($q['visit_id'])) {
        $stmt = $conn->prepare(
            "UPDATE patient_visits SET current_department_id = ?, updated_at = NOW() WHERE visit_id = ?"
        );
        $stmt->bind_param("ii", $target_department_id, $q['visit_id']);
        $stmt->execute();
        $stmt->close();
    }

    // ── 11. Recalculate queue positions (optional stored proc) ────────────────
    @$conn->query("CALL UpdateQueuePositions($target_department_id)");

    // ── 12. Activity log (non-fatal) ──────────────────────────────────────────
    try {
        $stmt_log = $conn->prepare(
            "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent, session_id)
             VALUES (?, 'TRANSFER', 'NURSING', ?, 'QUEUE', ?, ?, ?, ?, ?)"
        );
        if ($stmt_log) {
            $old_j = json_encode(['department_id' => $q['department_id'],   'queue_status' => 'IN_SERVICE']);
            $new_j = json_encode(['department_id' => $target_department_id, 'queue_status' => 'WAITING', 'queue_number' => $new_queue_number]);
            $ip    = $_SERVER['REMOTE_ADDR']     ?? 'UNKNOWN';
            $ua    = $_SERVER['HTTP_USER_AGENT'] ?? '';
            $sid   = session_id();
            $stmt_log->bind_param("iisssss", $user_id, $new_queue_id, $old_j, $new_j, $ip, $ua, $sid);
            $stmt_log->execute();
            $stmt_log->close();
        }
    } catch (Exception $e) {
        error_log("Route activity_log error: " . $e->getMessage());
    }

    $conn->commit();
    ob_end_clean();
    echo json_encode([
        'success'           => true,
        'message'           => 'Patient routed successfully.',
        'new_queue_id'      => $new_queue_id,
        'new_queue_number'  => $new_queue_number,
        'target_department' => $dept['department_name'],
        'position'          => $position,
    ]);

} catch (Exception $e) {
    $conn->rollback();
    error_log("route_patient_after_vitals error: " . $e->getMessage());
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}