<?php
/**
 * File 4: ajax/transfer_patient_queue.php
 * Transfer patient to another department
 */
session_start();
include '../layouts/dbconn.php';

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

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

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['full_name'] ?? 'Staff';
$patient_id = $_POST['patient_id'] ?? 0;
$queue_id = $_POST['queue_id'] ?? 0;
$target_department = $_POST['target_department'] ?? 0;
$priority = $_POST['priority'] ?? 'NORMAL';
$transfer_reason = trim($_POST['transfer_reason'] ?? '');
$transfer_notes = trim($_POST['transfer_notes'] ?? '');

if (empty($target_department) || empty($transfer_reason)) {
    echo json_encode([
        'success' => false,
        'message' => 'Please select department and provide transfer reason'
    ]);
    exit();
}

try {
    $conn->begin_transaction();

    // Get current queue data
    $queue_sql = "SELECT * FROM patient_queue WHERE queue_id = ?";
    $stmt = $conn->prepare($queue_sql);
    $stmt->bind_param("i", $queue_id);
    $stmt->execute();
    $queue_data = $stmt->get_result()->fetch_assoc();

    if (!$queue_data) {
        throw new Exception("Queue record not found");
    }

    // Mark current queue as transferred
    $update_sql = "UPDATE patient_queue 
                  SET queue_status = 'TRANSFERRED',
                      service_end_time = NOW(),
                      total_service_minutes = TIMESTAMPDIFF(MINUTE, COALESCE(service_start_time, queue_entry_time), NOW()),
                      updated_by = ?
                  WHERE queue_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ii", $user_id, $queue_id);
    $stmt->execute();

    // Generate new queue number
    $dept_code_sql = "SELECT department_code FROM departments WHERE department_id = ?";
    $stmt = $conn->prepare($dept_code_sql);
    $stmt->bind_param("i", $target_department);
    $stmt->execute();
    $dept_code = $stmt->get_result()->fetch_assoc()['department_code'];

    $queue_number_sql = "SELECT GenerateQueueNumber(?) as queue_number";
    $stmt = $conn->prepare($queue_number_sql);
    $stmt->bind_param("s", $dept_code);
    $stmt->execute();
    $new_queue_number = $stmt->get_result()->fetch_assoc()['queue_number'];

    // patient_queue.registration_type ENUM allows only WALK_IN, INSURANCE, PRO_BONO - use literal to avoid truncation
    $valid_reg = ['WALK_IN', 'INSURANCE', 'PRO_BONO'];
    $raw_reg = $queue_data['registration_type'] ?? '';
    $reg_type = is_string($raw_reg) ? strtoupper(trim($raw_reg)) : 'WALK_IN';
    $registration_type = in_array($reg_type, $valid_reg, true) ? $reg_type : 'WALK_IN';
    $reg_safe = $conn->real_escape_string($registration_type);

    // Create new queue entry
    $insert_sql = "INSERT INTO patient_queue (
        queue_number, patient_id, visit_id, department_id,
        queue_status, priority, registration_type,
        patient_name, patient_number, phone_number, age, gender,
        service_type, chief_complaint, special_needs, is_vip,
        previous_department_id, transfer_reason, referred_by, transfer_notes,
        notification_preference, created_by
    ) VALUES (?, ?, ?, ?, 'WAITING', ?, '" . $reg_safe . "', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $referred_by = null;
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param(
        "siiisssssssssiisisisi",
        $new_queue_number,
        $queue_data['patient_id'],
        $queue_data['visit_id'],
        $target_department,
        $priority,
        $queue_data['patient_name'],
        $queue_data['patient_number'],
        $queue_data['phone_number'],
        $queue_data['age'],
        $queue_data['gender'],
        $queue_data['service_type'],
        $queue_data['chief_complaint'],
        $queue_data['special_needs'],
        $queue_data['is_vip'],
        $queue_data['department_id'],
        $transfer_reason,
        $referred_by,
        $transfer_notes,
        $queue_data['notification_preference'],
        $user_id
    );

    $stmt->execute();
    $new_queue_id = $conn->insert_id;

    // Update queue positions
    $conn->query("CALL UpdateQueuePositions($target_department)");
    $conn->query("CALL UpdateQueueWaitTimes($target_department)");

    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                    VALUES (?, 'TRANSFER', 'QUEUE', ?, 'QUEUE', ?, NOW())";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iis", $user_id, $new_queue_id, $ip_address);
    $stmt->execute();

    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Patient transferred successfully',
        'new_queue_number' => $new_queue_number
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Transfer failed: ' . $e->getMessage()
    ]);
}
?>