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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

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

// Get queue_id from parameter
$queue_id = isset($_GET['queue_id']) ? intval($_GET['queue_id']) : 0;

if ($queue_id == 0) {
    $_SESSION['error'] = "Invalid queue ID";
    header('Location: queue_dashboard.php');
    exit();
}

// Fetch queue and patient details
$queue_sql = "SELECT
    q.*,
    d.department_name as current_department,
    d.department_code,
    p.blood_group,
    p.allergies,
    p.chronic_conditions,
    u.full_name as patient_full_name,
    u.email as patient_email,
    u.phone_primary as patient_phone
FROM patient_queue q
INNER JOIN departments d ON q.department_id = d.department_id
LEFT JOIN patients p ON q.patient_id = p.patient_id
LEFT JOIN users u ON p.user_id = u.user_id
WHERE q.queue_id = ? AND q.queue_status IN ('WAITING', 'IN_SERVICE')";

$stmt = $conn->prepare($queue_sql);
$stmt->bind_param("i", $queue_id);
$stmt->execute();
$queue_result = $stmt->get_result();

if ($queue_result->num_rows == 0) {
    $_SESSION['error'] = "Queue entry not found or already completed";
    header('Location: queue_dashboard.php');
    exit();
}

$queue = $queue_result->fetch_assoc();

// Fetch available departments (excluding current)
$dept_sql = "SELECT 
    department_id, 
    department_name, 
    department_code,
    max_queue_capacity,
    (SELECT COUNT(*) FROM patient_queue 
     WHERE department_id = departments.department_id 
     AND queue_status IN ('WAITING', 'IN_SERVICE')
     AND DATE(queue_entry_time) = CURDATE()) as current_count
FROM departments 
WHERE is_active = 1 
AND department_id != ?
ORDER BY display_order";

$dept_stmt = $conn->prepare($dept_sql);
$dept_stmt->bind_param("i", $queue['department_id']);
$dept_stmt->execute();
$dept_result = $dept_stmt->get_result();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['transfer_action'])) {
    $target_dept_id = intval($_POST['target_department']);
    $transfer_reason = trim($_POST['transfer_reason']);
    $transfer_notes = trim($_POST['transfer_notes']);
    $maintain_priority = isset($_POST['maintain_priority']) ? 1 : 0;
    
    // Validate target department
    if ($target_dept_id == 0 || $target_dept_id == $queue['department_id']) {
        $_SESSION['error'] = "Please select a valid target department";
    } elseif (empty($transfer_reason)) {
        $_SESSION['error'] = "Transfer reason is required";
    } else {
        // Begin transaction
        $conn->begin_transaction();
        
        try {
            // Update current queue entry to TRANSFERRED
            $update_sql = "UPDATE patient_queue SET 
                queue_status = 'TRANSFERRED',
                service_end_time = NOW(),
                total_wait_minutes = TIMESTAMPDIFF(MINUTE, queue_entry_time, NOW()),
                updated_at = NOW(),
                updated_by = ?
            WHERE queue_id = ?";
            
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("ii", $user_id, $queue_id);
            $update_stmt->execute();
            
            // Add transfer details to queue_history with notes
            $history_sql = "INSERT INTO queue_history (
                queue_id,
                patient_id,
                visit_id,
                department_id,
                department_name,
                action,
                from_status,
                to_status,
                queue_position,
                performed_by,
                performed_by_name,
                notes,
                timestamp
            ) SELECT
                ?,
                q.patient_id,
                q.visit_id,
                q.department_id,
                d.department_name,
                'TRANSFERRED',
                'IN_SERVICE',
                'TRANSFERRED',
                q.position_in_queue,
                ?,
                u.full_name,
                CONCAT('[TRANSFER] Reason: ', ?, '\nNotes: ', ?),
                NOW()
            FROM patient_queue q
            INNER JOIN departments d ON q.department_id = d.department_id
            LEFT JOIN users u ON u.user_id = ?
            WHERE q.queue_id = ?";
            
            $history_stmt = $conn->prepare($history_sql);
            $history_stmt->bind_param("iissii", $queue_id, $user_id, $transfer_reason, $transfer_notes, $user_id, $queue_id);
            $history_stmt->execute();
            
            // Get target department details
            $target_dept_sql = "SELECT department_name, department_code FROM departments WHERE department_id = ?";
            $target_stmt = $conn->prepare($target_dept_sql);
            $target_stmt->bind_param("i", $target_dept_id);
            $target_stmt->execute();
            $target_dept = $target_stmt->get_result()->fetch_assoc();
            
            // Generate new queue number for target department
            $date_code = date('Ymd');
            $queue_number_sql = "SELECT queue_number FROM patient_queue 
                WHERE department_id = ? 
                AND DATE(queue_entry_time) = CURDATE() 
                ORDER BY queue_id DESC LIMIT 1";
            
            $qn_stmt = $conn->prepare($queue_number_sql);
            $qn_stmt->bind_param("i", $target_dept_id);
            $qn_stmt->execute();
            $qn_result = $qn_stmt->get_result();
            
            if ($qn_result->num_rows > 0) {
                $last_queue = $qn_result->fetch_assoc();
                $last_number = intval(substr($last_queue['queue_number'], -4));
                $new_number = $last_number + 1;
            } else {
                $new_number = 1;
            }
            
            $new_queue_number = $target_dept['department_code'] . '-' . $date_code . '-' . str_pad($new_number, 4, '0', STR_PAD_LEFT);
            
            // Calculate position in new queue
            $position_sql = "SELECT MAX(position_in_queue) as max_position 
                FROM patient_queue 
                WHERE department_id = ? 
                AND queue_status = 'WAITING'
                AND DATE(queue_entry_time) = CURDATE()";
            
            $pos_stmt = $conn->prepare($position_sql);
            $pos_stmt->bind_param("i", $target_dept_id);
            $pos_stmt->execute();
            $pos_result = $pos_stmt->get_result()->fetch_assoc();
            $new_position = ($pos_result['max_position'] ?? 0) + 1;
            
            // Determine priority for new queue entry
            $new_priority = $maintain_priority ? $queue['priority'] : 'NORMAL';
            
            // Create new queue entry in target department
            $insert_sql = "INSERT INTO patient_queue (
                queue_number,
                patient_id,
                patient_name,
                patient_number,
                phone_number,
                age,
                gender,
                department_id,
                queue_status,
                priority,
                registration_type,
                position_in_queue,
                service_type,
                chief_complaint,
                triage_category,
                vitals_taken,
                has_appointment,
                is_vip,
                special_needs,
                previous_department_id,
                created_by,
                created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'WAITING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $insert_stmt = $conn->prepare($insert_sql);
            $insert_stmt->bind_param(
                "ssssssssssisssiiiiii",
                $new_queue_number,
                $queue['patient_id'],
                $queue['patient_name'],
                $queue['patient_number'],
                $queue['phone_number'],
                $queue['age'],
                $queue['gender'],
                $target_dept_id,
                $new_priority,
                $queue['registration_type'],
                $new_position,
                $queue['service_type'],
                $queue['chief_complaint'],
                $queue['triage_category'],
                $queue['vitals_taken'],
                $queue['has_appointment'],
                $queue['is_vip'],
                $queue['special_needs'],
                $queue['department_id'],
                $user_id
            );
            
            $insert_stmt->execute();
            $new_queue_id = $conn->insert_id;
            
            // Add entry to queue_history for the new queue
            $new_history_sql = "INSERT INTO queue_history (
                queue_id,
                patient_id,
                visit_id,
                department_id,
                department_name,
                action,
                from_status,
                to_status,
                queue_position,
                performed_by,
                performed_by_name,
                notes,
                timestamp
            ) VALUES (?, ?, ?, ?, ?, 'QUEUED', NULL, 'WAITING', ?, ?, ?, ?, NOW())";
            
            $transfer_note = "TRANSFERRED FROM: " . $queue['current_department'] . " | Reason: " . $transfer_reason . " | Notes: " . $transfer_notes;
            $performed_by_name = $_SESSION['full_name'] ?? 'Unknown';
            
            $new_hist_stmt = $conn->prepare($new_history_sql);
            $new_hist_stmt->bind_param(
                "iiiisiiss",
                $new_queue_id,
                $queue['patient_id'],
                $queue['visit_id'],
                $target_dept_id,
                $target_dept['department_name'],
                $new_position,
                $user_id,
                $performed_by_name,
                $transfer_note
            );
            $new_hist_stmt->execute();
            
            // Log the transfer activity
            $log_sql = "INSERT INTO activity_logs (
                user_id,
                action,
                entity_type,
                entity_id,
                description,
                ip_address,
                status,
                created_at
            ) VALUES (?, 'UPDATE', 'QUEUE', ?, ?, ?, 'SUCCESS', NOW())";
            
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $log_description = "Transferred patient {$queue['patient_name']} ({$queue['patient_number']}) from {$queue['current_department']} to {$target_dept['department_name']}. Reason: {$transfer_reason}";
            
            $log_stmt = $conn->prepare($log_sql);
            $log_stmt->bind_param("iiss", $user_id, $queue_id, $log_description, $ip_address);
            $log_stmt->execute();
            
            // Commit transaction
            $conn->commit();
            
            $_SESSION['success'] = "Patient transferred successfully to " . $target_dept['department_name'];
            header('Location: queue_dashboard.php');
            exit();
            
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['error'] = "Transfer failed: " . $e->getMessage();
        }
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Transfer Patient')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .transfer-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px 12px 0 0;
            margin: -1.5rem -1.5rem 1.5rem -1.5rem;
        }
        
        .patient-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .patient-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 2rem;
            margin-right: 1.5rem;
        }
        
        .patient-info-group {
            margin-bottom: 1rem;
        }
        
        .patient-info-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
            margin-bottom: 0.25rem;
        }
        
        .patient-info-value {
            font-size: 1rem;
            color: #1e293b;
            font-weight: 600;
        }
        
        .priority-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .priority-normal {
            background: #dcfce7;
            color: #166534;
        }
        
        .priority-urgent {
            background: #fef3c7;
            color: #92400e;
        }
        
        .priority-emergency {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-waiting {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-in-service {
            background: #fef3c7;
            color: #92400e;
        }
        
        .dept-option {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .dept-option:hover {
            border-color: #667eea;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .dept-option.selected {
            border-color: #667eea;
            background: #eff6ff;
        }
        
        .dept-option input[type="radio"] {
            display: none;
        }
        
        .dept-name {
            font-weight: 600;
            color: #1e293b;
            font-size: 1.1rem;
            margin-bottom: 0.5rem;
        }
        
        .dept-capacity {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .capacity-bar {
            flex: 1;
            height: 6px;
            background: #e2e8f0;
            border-radius: 3px;
            overflow: hidden;
        }
        
        .capacity-fill {
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            transition: width 0.3s;
        }
        
        .capacity-fill.warning {
            background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%);
        }
        
        .form-section {
            background: #f8fafc;
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
        }
        
        .form-section-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .info-alert {
            background: #eff6ff;
            border-left: 4px solid #3b82f6;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1.5rem;
        }
        
        .warning-alert {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1.5rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">
                                    <i class="ri-arrow-right-line me-2"></i>Transfer Patient
                                </h4>
                                <div class="page-title-right">
                                    <button class="btn btn-secondary" onclick="history.back()">
                                        <i class="ri-arrow-left-line me-1"></i> Back to Queue
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i>
                        <?php 
                        echo $_SESSION['error']; 
                        unset($_SESSION['error']);
                        ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <form method="POST" id="transferForm">
                        <input type="hidden" name="transfer_action" value="1">
                        
                        <div class="row">
                            <!-- Patient Information Card -->
                            <div class="col-xl-4">
                                <div class="card">
                                    <div class="transfer-header">
                                        <h5 class="mb-0">
                                            <i class="ri-user-line me-2"></i>Patient Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-flex mb-3">
                                            <div class="patient-avatar">
                                                <?php echo strtoupper(substr($queue['patient_name'], 0, 1)); ?>
                                            </div>
                                            <div class="flex-grow-1">
                                                <h5 class="mb-1"><?php echo htmlspecialchars($queue['patient_name']); ?></h5>
                                                <p class="text-muted mb-0"><?php echo $queue['patient_number']; ?></p>
                                            </div>
                                        </div>
                                        
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Age & Gender</div>
                                            <div class="patient-info-value">
                                                <?php echo $queue['age']; ?> Years • <?php echo $queue['gender']; ?>
                                            </div>
                                        </div>
                                        
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Phone Number</div>
                                            <div class="patient-info-value">
                                                <?php echo htmlspecialchars($queue['phone_number']); ?>
                                            </div>
                                        </div>
                                        
                                        <?php if ($queue['blood_group']): ?>
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Blood Group</div>
                                            <div class="patient-info-value">
                                                <?php echo htmlspecialchars($queue['blood_group']); ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Registration Type</div>
                                            <div class="patient-info-value">
                                                <?php echo htmlspecialchars($queue['registration_type']); ?>
                                            </div>
                                        </div>
                                        
                                        <hr>
                                        
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Current Department</div>
                                            <div class="patient-info-value text-primary">
                                                <i class="ri-hospital-line me-1"></i>
                                                <?php echo htmlspecialchars($queue['current_department']); ?>
                                            </div>
                                        </div>
                                        
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Queue Number</div>
                                            <div class="patient-info-value">
                                                <?php echo $queue['queue_number']; ?>
                                            </div>
                                        </div>
                                        
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Priority</div>
                                            <div>
                                                <span class="priority-badge priority-<?php echo strtolower($queue['priority']); ?>">
                                                    <?php echo $queue['priority']; ?>
                                                </span>
                                            </div>
                                        </div>
                                        
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Current Status</div>
                                            <div>
                                                <span class="status-badge status-<?php echo str_replace('_', '-', strtolower($queue['queue_status'])); ?>">
                                                    <?php echo str_replace('_', ' ', $queue['queue_status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        
                                        <?php if ($queue['chief_complaint']): ?>
                                        <hr>
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Chief Complaint</div>
                                            <div class="patient-info-value" style="font-weight: normal;">
                                                <?php echo nl2br(htmlspecialchars($queue['chief_complaint'])); ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($queue['special_needs']): ?>
                                        <div class="patient-info-group">
                                            <div class="patient-info-label">Special Needs</div>
                                            <div class="patient-info-value" style="font-weight: normal;">
                                                <?php echo nl2br(htmlspecialchars($queue['special_needs'])); ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Transfer Form -->
                            <div class="col-xl-8">
                                <div class="card">
                                    <div class="transfer-header">
                                        <h5 class="mb-0">
                                            <i class="ri-arrow-right-line me-2"></i>Transfer Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="info-alert">
                                            <i class="ri-information-line me-2"></i>
                                            <strong>Transfer Process:</strong> The patient will be moved from their current queue to the selected department's queue. The original queue entry will be marked as transferred.
                                        </div>
                                        
                                        <!-- Target Department Selection -->
                                        <div class="form-section">
                                            <div class="form-section-title">
                                                <i class="ri-hospital-line"></i>
                                                Select Target Department <span class="text-danger">*</span>
                                            </div>
                                            
                                            <?php if ($dept_result->num_rows > 0): ?>
                                                <?php while ($dept = $dept_result->fetch_assoc()): 
                                                    $capacity_percent = ($dept['current_count'] / $dept['max_queue_capacity']) * 100;
                                                    $is_warning = $capacity_percent > 80;
                                                ?>
                                                <label class="dept-option">
                                                    <input type="radio" 
                                                           name="target_department" 
                                                           value="<?php echo $dept['department_id']; ?>" 
                                                           required>
                                                    <div class="dept-name">
                                                        <i class="ri-arrow-right-circle-line me-2"></i>
                                                        <?php echo htmlspecialchars($dept['department_name']); ?>
                                                        <span class="text-muted" style="font-size: 0.875rem; font-weight: normal;">
                                                            (<?php echo $dept['department_code']; ?>)
                                                        </span>
                                                    </div>
                                                    <div class="dept-capacity">
                                                        <span>Queue: <?php echo $dept['current_count']; ?>/<?php echo $dept['max_queue_capacity']; ?></span>
                                                        <div class="capacity-bar">
                                                            <div class="capacity-fill <?php echo $is_warning ? 'warning' : ''; ?>" 
                                                                 style="width: <?php echo min($capacity_percent, 100); ?>%"></div>
                                                        </div>
                                                        <span><?php echo round($capacity_percent); ?>%</span>
                                                    </div>
                                                    <?php if ($is_warning): ?>
                                                    <div class="mt-2">
                                                        <small class="text-warning">
                                                            <i class="ri-alert-line"></i> High capacity - May have longer wait times
                                                        </small>
                                                    </div>
                                                    <?php endif; ?>
                                                </label>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <div class="warning-alert">
                                                    <i class="ri-alert-line me-2"></i>
                                                    No other departments available for transfer.
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- Transfer Reason -->
                                        <div class="form-section">
                                            <div class="form-section-title">
                                                <i class="ri-file-text-line"></i>
                                                Transfer Reason <span class="text-danger">*</span>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <select class="form-select" name="transfer_reason" id="transferReason" required>
                                                    <option value="">Select reason for transfer</option>
                                                    <option value="Specialized Care Required">Specialized Care Required</option>
                                                    <option value="Department Overload">Department Overload</option>
                                                    <option value="Equipment/Facility Unavailable">Equipment/Facility Unavailable</option>
                                                    <option value="Staff Unavailable">Staff Unavailable</option>
                                                    <option value="Patient Request">Patient Request</option>
                                                    <option value="Clinical Assessment">Clinical Assessment</option>
                                                    <option value="Referral">Referral</option>
                                                    <option value="Other">Other (Specify in notes)</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Transfer Notes</label>
                                                <textarea class="form-control" 
                                                          name="transfer_notes" 
                                                          rows="4" 
                                                          placeholder="Provide additional details about the transfer..."></textarea>
                                                <small class="text-muted">Include any relevant clinical information or instructions for the receiving department</small>
                                            </div>
                                        </div>
                                        
                                        <!-- Additional Options -->
                                        <div class="form-section">
                                            <div class="form-section-title">
                                                <i class="ri-settings-3-line"></i>
                                                Transfer Options
                                            </div>
                                            
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" 
                                                       type="checkbox" 
                                                       name="maintain_priority" 
                                                       id="maintainPriority" 
                                                       checked>
                                                <label class="form-check-label" for="maintainPriority">
                                                    <strong>Maintain Priority Level</strong>
                                                    <div class="text-muted small">
                                                        Keep the current priority (<?php echo $queue['priority']; ?>) in the new department queue
                                                    </div>
                                                </label>
                                            </div>
                                            
                                            <div class="info-alert">
                                                <i class="ri-information-line me-2"></i>
                                                <strong>Note:</strong> The patient will be assigned a new queue number in the target department. Position in queue will be determined by priority and entry time.
                                            </div>
                                        </div>
                                        
                                        <!-- Action Buttons -->
                                        <div class="d-flex justify-content-end gap-2 mt-4">
                                            <button type="button" class="btn btn-secondary" onclick="history.back()">
                                                <i class="ri-close-line me-1"></i> Cancel
                                            </button>
                                            <button type="submit" class="btn btn-primary" id="transferBtn">
                                                <i class="ri-arrow-right-line me-1"></i> Complete Transfer
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        // Department selection interaction
        document.querySelectorAll('.dept-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.dept-option').forEach(opt => {
                    opt.classList.remove('selected');
                });
                this.classList.add('selected');
                this.querySelector('input[type="radio"]').checked = true;
            });
        });
        
        // Form submission with confirmation
        document.getElementById('transferForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const targetDeptRadio = document.querySelector('input[name="target_department"]:checked');
            const transferReason = document.getElementById('transferReason').value;
            
            if (!targetDeptRadio) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Department Required',
                    text: 'Please select a target department for transfer'
                });
                return;
            }
            
            if (!transferReason) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Reason Required',
                    text: 'Please select a reason for the transfer'
                });
                return;
            }
            
            const targetDeptName = targetDeptRadio.closest('.dept-option').querySelector('.dept-name').textContent.trim();
            
            Swal.fire({
                title: 'Confirm Transfer',
                html: `
                    <div class="text-start">
                        <p>You are about to transfer:</p>
                        <ul>
                            <li><strong>Patient:</strong> <?php echo htmlspecialchars($queue['patient_name']); ?></li>
                            <li><strong>From:</strong> <?php echo htmlspecialchars($queue['current_department']); ?></li>
                            <li><strong>To:</strong> ${targetDeptName}</li>
                            <li><strong>Reason:</strong> ${transferReason}</li>
                        </ul>
                        <p class="text-muted">This action will create a new queue entry and notify the receiving department.</p>
                    </div>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Transfer Patient',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#667eea',
                cancelButtonColor: '#6c757d'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading
                    Swal.fire({
                        title: 'Processing Transfer...',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Submit the form
                    e.target.submit();
                }
            });
        });
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>