<?php
header('Content-Type: application/json');
session_start();
include '../layouts/dbconn.php';

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

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

// Verify nurse access
if ($role_code !== 'HEAD_NURSE' && $role_code !== 'ENT_NURSE') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Get form data
$queue_id = $_POST['queue_id'] ?? null;
$target_department_id = $_POST['target_department_id'] ?? null;
$routing_notes = trim($_POST['routing_notes'] ?? '');

if (!$queue_id || !$target_department_id) {
    echo json_encode(['success' => false, 'message' => 'Queue ID and target department are required']);
    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");
    }
    
    // Get target department code
    $dept_sql = "SELECT department_code, department_name FROM departments WHERE department_id = ? AND is_active = 1";
    $stmt = $conn->prepare($dept_sql);
    $stmt->bind_param("i", $target_department_id);
    $stmt->execute();
    $dept_result = $stmt->get_result();
    
    if ($dept_result->num_rows === 0) {
        throw new Exception("Target department not found");
    }
    
    $target_dept = $dept_result->fetch_assoc();
    $stmt->close();
    
    // Mark current triage queue as COMPLETED (removed from triage)
    $update_sql = "UPDATE patient_queue 
                  SET queue_status = 'COMPLETED',
                      service_end_time = NOW(),
                      total_service_minutes = TIMESTAMPDIFF(MINUTE, queue_entry_time, NOW()),
                      updated_by = ?
                  WHERE queue_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ii", $user_id, $queue_id);
    $stmt->execute();
    $stmt->close();
    
    // Generate new queue number for target department
    $date_str = date('Ymd');
    $seq_sql = "SELECT COUNT(*) as count FROM patient_queue 
                WHERE department_id = ? AND DATE(queue_entry_time) = CURDATE()";
    $stmt = $conn->prepare($seq_sql);
    $stmt->bind_param("i", $target_department_id);
    $stmt->execute();
    $seq_result = $stmt->get_result();
    $seq_row = $seq_result->fetch_assoc();
    $sequence = str_pad($seq_row['count'] + 1, 3, '0', STR_PAD_LEFT);
    $new_queue_number = $target_dept['department_code'] . '-' . $date_str . '-' . $sequence;
    $stmt->close();
    
    // Calculate position in new queue
    $position_sql = "SELECT COUNT(*) + 1 as position FROM patient_queue 
                     WHERE department_id = ? 
                     AND DATE(queue_entry_time) = CURDATE()
                     AND queue_status = 'WAITING'";
    $stmt = $conn->prepare($position_sql);
    $stmt->bind_param("i", $target_department_id);
    $stmt->execute();
    $position_result = $stmt->get_result();
    $position_row = $position_result->fetch_assoc();
    $position = $position_row['position'];
    $stmt->close();
    
    // Calculate estimated wait time
    $estimated_wait = ($position - 1) * 15;
    
    // Create new queue entry in target department
    $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,
        vitals_taken,
        vital_signs_id,
        previous_department_id,
        transfer_reason,
        referred_by,
        transfer_notes,
        position_in_queue,
        estimated_wait_minutes,
        notification_preference,
        created_by,
        created_at
    ) VALUES (?, ?, ?, ?, 'WAITING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Routed from Triage', ?, ?, ?, ?, ?, ?, NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    $transfer_reason = 'Routed from Triage after vitals';
    $referred_by = $user_id;
    
    $stmt->bind_param(
        "siiissssssisssiiisissiiis",
        $new_queue_number,
        $queue_data['patient_id'],
        $queue_data['visit_id'],
        $target_department_id,
        $queue_data['priority'],
        $queue_data['registration_type'],
        $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['vitals_taken'],
        $queue_data['vital_signs_id'],
        $queue_data['department_id'],
        $transfer_reason,
        $referred_by,
        $routing_notes,
        $position,
        $estimated_wait,
        $queue_data['notification_preference'] ?? 'SMS',
        $user_id
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to create new queue entry: " . $stmt->error);
    }
    
    $new_queue_id = $conn->insert_id;
    $stmt->close();
    
    // Update queue positions for target department
    $conn->query("CALL UpdateQueuePositions($target_department_id)");
    $conn->query("CALL UpdateQueueWaitTimes($target_department_id)");
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent, session_id) 
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt_log = $conn->prepare($activity_sql);
    if (!$stmt_log) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    $action = 'TRANSFER';
    $module = 'NURSING';
    $record_type = 'QUEUE';
    $old_values = json_encode(['department_id' => $queue_data['department_id'], 'queue_status' => 'IN_SERVICE']);
    $new_values = json_encode(['department_id' => $target_department_id, 'queue_status' => 'WAITING', 'queue_number' => $new_queue_number]);
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $session_id = session_id();
    
    $stmt_log->bind_param("ississssss", 
        $user_id, 
        $action, 
        $module, 
        $new_queue_id, 
        $record_type,
        $old_values,
        $new_values,
        $ip_address,
        $user_agent,
        $session_id
    );
    $stmt_log->execute();
    $stmt_log->close();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Patient routed successfully',
        'new_queue_number' => $new_queue_number,
        'target_department' => $target_dept['department_name'],
        'position' => $position
    ]);
    
} catch (Exception $e) {
    if (isset($conn) && $conn !== null) {
        $conn->rollback();
    }
    error_log("Route patient error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

if (isset($conn)) {
    $conn->close();
}
?>
