<?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'];
$errors = [];
$success_message = '';

// Get queue ID from URL
$queue_id = $_GET['queue_id'] ?? 0;

if (empty($queue_id)) {
    header('Location: queue_dashboard.php');
    exit();
}

// Fetch current queue details
$queue_sql = "SELECT q.*, p.patient_id, u.full_name, u.phone_primary, u.date_of_birth, u.gender,
              d.department_name as current_department_name, d.department_id as current_dept_id
              FROM patient_queue q
              INNER JOIN patients p ON q.patient_id = p.patient_id
              INNER JOIN users u ON p.user_id = u.user_id
              INNER JOIN departments d ON q.department_id = d.department_id
              WHERE q.queue_id = ?";

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

if ($queue_result->num_rows === 0) {
    header('Location: queue_dashboard.php');
    exit();
}

$queue_data = $queue_result->fetch_assoc();

// Fetch available departments (excluding current department)
$departments_sql = "SELECT department_id, department_code, department_name, description, avg_service_time_minutes
                   FROM departments 
                   WHERE is_active = 1 AND department_id != ?
                   ORDER BY display_order";
$stmt = $conn->prepare($departments_sql);
$stmt->bind_param("i", $queue_data['current_dept_id']);
$stmt->execute();
$departments = $stmt->get_result();

// Process transfer form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $target_department = $_POST['target_department'] ?? '';
    $transfer_priority = $_POST['transfer_priority'] ?? 'NORMAL';
    $transfer_reason = trim($_POST['transfer_reason'] ?? '');
    $transfer_notes = trim($_POST['transfer_notes'] ?? '');
    $service_type = trim($_POST['service_type'] ?? '');
    $update_complaint = trim($_POST['update_complaint'] ?? '');
    
    // Validation
    if (empty($target_department)) {
        $errors[] = "Please select a target department";
    }
    
    if (empty($transfer_reason)) {
        $errors[] = "Please provide a reason for transfer";
    }
    
    // Process transfer if no errors
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            // Mark current queue as transferred
            $update_sql = "UPDATE patient_queue 
                          SET queue_status = 'TRANSFERRED',
                              service_end_time = NOW(),
                              total_service_minutes = TIMESTAMPDIFF(MINUTE, service_start_time, NOW()),
                              updated_by = ?
                          WHERE queue_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ii", $user_id, $queue_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to update current queue record");
            }
            
            // Generate new queue number for target department
            $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'];
            
            // Update chief complaint if provided
            $chief_complaint = empty($update_complaint) ? $queue_data['chief_complaint'] : $update_complaint;
            
            // 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,
                            previous_department_id, transfer_reason, referred_by, transfer_notes,
                            notification_preference, created_by, created_at
                          ) VALUES (?, ?, ?, ?, 'WAITING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("siiisssssississsisi",
                $new_queue_number,
                $queue_data['patient_id'],
                $queue_data['visit_id'],
                $target_department,
                $transfer_priority,
                $queue_data['registration_type'],
                $queue_data['patient_name'],
                $queue_data['patient_number'],
                $queue_data['phone_number'],
                $queue_data['age'],
                $queue_data['gender'],
                $service_type,
                $chief_complaint,
                $queue_data['special_needs'],
                $queue_data['is_vip'],
                $queue_data['current_dept_id'],
                $transfer_reason,
                $user_id,
                $transfer_notes,
                $queue_data['notification_preference'],
                $user_id
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create new queue entry");
            }
            
            $new_queue_id = $conn->insert_id();
            
            // Update queue positions for target department
            $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, new_values, ip_address, logged_at)
                           VALUES (?, 'TRANSFER', 'QUEUE', ?, 'QUEUE', ?, ?, NOW())";
            
            $new_values = json_encode([
                'from_department' => $queue_data['current_department_name'],
                'to_department_id' => $target_department,
                'transfer_reason' => $transfer_reason,
                'new_queue_number' => $new_queue_number,
                'patient_name' => $queue_data['patient_name']
            ]);
            
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            $stmt = $conn->prepare($activity_sql);
            $stmt->bind_param("iiss", $user_id, $new_queue_id, $new_values, $ip_address);
            $stmt->execute();
            
            $conn->commit();
            
            $success_message = "Patient successfully transferred!<br>New Queue Number: <strong>" . $new_queue_number . "</strong>";
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Transfer failed: " . $e->getMessage();
        }
    }
}

// Calculate age
$dob = new DateTime($queue_data['date_of_birth']);
$now = new DateTime();
$age = $now->diff($dob)->y;
?>

<?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>
        .patient-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .patient-card .patient-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: white;
            color: #667eea;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 1rem;
        }
        
        .patient-card h4 {
            margin-bottom: 0.5rem;
        }
        
        .patient-card .info-row {
            display: flex;
            gap: 2rem;
            margin-top: 1rem;
            flex-wrap: wrap;
        }
        
        .patient-card .info-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }
        
        .form-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin: 0;
        }
        
        .form-body {
            padding: 1.5rem;
        }
        
        .department-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .department-card {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 1.25rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .department-card:hover {
            border-color: #667eea;
            background: #f8faff;
            transform: translateY(-2px);
        }
        
        .department-card.active {
            border-color: #667eea;
            background: #eff6ff;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .department-icon {
            font-size: 2.5rem;
            margin-bottom: 0.75rem;
        }
        
        .department-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .department-desc {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .priority-selector {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .priority-option {
            flex: 1;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .priority-option:hover {
            border-color: #667eea;
        }
        
        .priority-option.active.normal {
            border-color: #10b981;
            background: #d1fae5;
        }
        
        .priority-option.active.urgent {
            border-color: #f59e0b;
            background: #fef3c7;
        }
        
        .priority-option.active.emergency {
            border-color: #ef4444;
            background: #fee2e2;
        }
        
        .transfer-summary {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1rem;
        }
        
        .transfer-summary .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .transfer-summary .summary-item:last-child {
            border-bottom: none;
        }
        
        .summary-label {
            font-weight: 500;
            color: #64748b;
        }
        
        .summary-value {
            font-weight: 600;
            color: #1e293b;
        }
        
        .current-dept-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            background: white;
            color: #667eea;
            border-radius: 8px;
            font-weight: 600;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <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-left-right-line me-2"></i>Transfer Patient
                                </h4>
                                <div class="page-title-right">
                                    <a href="queue_dashboard.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back to Queue
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Transfer Failed!</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Success!</strong> <?php echo $success_message; ?>
                        <div class="mt-2">
                            <a href="queue_dashboard.php" class="btn btn-sm btn-primary">
                                <i class="ri-dashboard-line me-1"></i> View Queue Dashboard
                            </a>
                            <a href="transfer_patient.php?queue_id=<?php echo $queue_id; ?>" class="btn btn-sm btn-secondary">
                                <i class="ri-refresh-line me-1"></i> Transfer Another
                            </a>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if (empty($success_message)): ?>
                    <!-- Patient Information Card -->
                    <div class="patient-card">
                        <div class="patient-avatar">
                            <?php echo strtoupper(substr($queue_data['full_name'], 0, 1)); ?>
                        </div>
                        <h4><?php echo htmlspecialchars($queue_data['full_name']); ?></h4>
                        <div class="info-row">
                            <div class="info-item">
                                <i class="ri-user-line"></i>
                                <span><?php echo $queue_data['patient_number']; ?></span>
                            </div>
                            <div class="info-item">
                                <i class="ri-phone-line"></i>
                                <span><?php echo $queue_data['phone_primary']; ?></span>
                            </div>
                            <div class="info-item">
                                <i class="ri-calendar-line"></i>
                                <span><?php echo $age; ?> Years • <?php echo $queue_data['gender']; ?></span>
                            </div>
                            <div class="info-item">
                                <i class="ri-ticket-2-line"></i>
                                <span><?php echo $queue_data['queue_number']; ?></span>
                            </div>
                        </div>
                        <div class="mt-3">
                            <strong>Current Department:</strong>
                            <span class="current-dept-badge ms-2">
                                <?php echo htmlspecialchars($queue_data['current_department_name']); ?>
                            </span>
                        </div>
                    </div>

                    <form id="transferForm" method="POST">
                        <!-- Target Department Selection -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-hospital-line me-2"></i>Select Target Department
                                </h5>
                            </div>
                            <div class="form-body">
                                <div class="department-cards">
                                    <?php 
                                    $dept_icons = [
                                        'RECEPTION' => '🎫',
                                        'TRIAGE' => '🏥',
                                        'CONSULTATION' => '👨‍⚕️',
                                        'AUDIOLOGY' => '👂',
                                        'VESTIBULAR' => '⚖️',
                                        'ENDOSCOPY' => '🔬',
                                        'MINOR_PROC' => '⚕️',
                                        'LABORATORY' => '🧪',
                                        'PHARMACY' => '💊',
                                        'BILLING' => '💳',
                                        'FOLLOW_UP' => '📋'
                                    ];
                                    
                                    $departments->data_seek(0);
                                    while ($dept = $departments->fetch_assoc()): 
                                        $icon = $dept_icons[$dept['department_code']] ?? '🏢';
                                    ?>
                                    <div class="department-card" data-dept="<?php echo $dept['department_id']; ?>" 
                                         data-name="<?php echo htmlspecialchars($dept['department_name']); ?>">
                                        <div class="department-icon"><?php echo $icon; ?></div>
                                        <div class="department-title"><?php echo htmlspecialchars($dept['department_name']); ?></div>
                                        <p class="department-desc">~<?php echo $dept['avg_service_time_minutes']; ?> min</p>
                                        <input type="radio" name="target_department" value="<?php echo $dept['department_id']; ?>" style="display: none;" required>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Transfer Details -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-file-list-3-line me-2"></i>Transfer Details
                                </h5>
                            </div>
                            <div class="form-body">
                                <!-- Priority -->
                                <div class="mb-3">
                                    <label class="form-label">Priority Level <span class="text-danger">*</span></label>
                                    <div class="priority-selector">
                                        <div class="priority-option normal active" data-priority="NORMAL">
                                            <div style="font-size: 1.5rem;">🟢</div>
                                            <strong>Normal</strong>
                                            <input type="radio" name="transfer_priority" value="NORMAL" checked style="display: none;">
                                        </div>
                                        <div class="priority-option urgent" data-priority="URGENT">
                                            <div style="font-size: 1.5rem;">🟡</div>
                                            <strong>Urgent</strong>
                                            <input type="radio" name="transfer_priority" value="URGENT" style="display: none;">
                                        </div>
                                        <div class="priority-option emergency" data-priority="EMERGENCY">
                                            <div style="font-size: 1.5rem;">🔴</div>
                                            <strong>Emergency</strong>
                                            <input type="radio" name="transfer_priority" value="EMERGENCY" style="display: none;">
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Transfer Reason <span class="text-danger">*</span></label>
                                        <select class="form-select" name="transfer_reason" required>
                                            <option value="">Select Reason</option>
                                            <option value="Further Investigation">Further Investigation Required</option>
                                            <option value="Specialist Consultation">Specialist Consultation</option>
                                            <option value="Diagnostic Test">Diagnostic Test</option>
                                            <option value="Treatment">Treatment/Procedure</option>
                                            <option value="Follow-up">Follow-up Care</option>
                                            <option value="Medication">Medication Dispensing</option>
                                            <option value="Billing">Billing/Payment</option>
                                            <option value="Other">Other</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Service Type</label>
                                        <input type="text" class="form-control" name="service_type" placeholder="e.g., Audiometry, Endoscopy">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Update Chief Complaint (Optional)</label>
                                        <textarea class="form-control" name="update_complaint" rows="2" 
                                                  placeholder="Update or add to the patient's complaint if needed"><?php echo htmlspecialchars($queue_data['chief_complaint']); ?></textarea>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Transfer Notes</label>
                                        <textarea class="form-control" name="transfer_notes" rows="3" 
                                                  placeholder="Additional information for the receiving department"></textarea>
                                    </div>
                                </div>

                                <!-- Transfer Summary -->
                                <div class="transfer-summary" id="transferSummary" style="display: none;">
                                    <h6 class="mb-3"><i class="ri-information-line me-2"></i>Transfer Summary</h6>
                                    <div class="summary-item">
                                        <span class="summary-label">From Department:</span>
                                        <span class="summary-value"><?php echo htmlspecialchars($queue_data['current_department_name']); ?></span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">To Department:</span>
                                        <span class="summary-value" id="targetDeptName">-</span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Patient:</span>
                                        <span class="summary-value"><?php echo htmlspecialchars($queue_data['full_name']); ?></span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Current Queue Number:</span>
                                        <span class="summary-value"><?php echo $queue_data['queue_number']; ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="form-card">
                            <div class="form-body">
                                <div class="d-flex justify-content-between">
                                    <a href="queue_dashboard.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Cancel
                                    </a>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="ri-arrow-right-line me-1"></i> Transfer Patient
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const departmentCards = document.querySelectorAll('.department-card');
        const priorityOptions = document.querySelectorAll('.priority-option');
        const transferSummary = document.getElementById('transferSummary');
        const targetDeptName = document.getElementById('targetDeptName');
        
        // Department selection
        departmentCards.forEach(card => {
            card.addEventListener('click', function() {
                departmentCards.forEach(c => c.classList.remove('active'));
                this.classList.add('active');
                
                const radio = this.querySelector('input[type="radio"]');
                radio.checked = true;
                
                const deptName = this.getAttribute('data-name');
                targetDeptName.textContent = deptName;
                transferSummary.style.display = 'block';
            });
        });
        
        // Priority selection
        priorityOptions.forEach(option => {
            option.addEventListener('click', function() {
                priorityOptions.forEach(o => o.classList.remove('active'));
                this.classList.add('active');
                
                const radio = this.querySelector('input[type="radio"]');
                radio.checked = true;
            });
        });
        
        // Form validation
        const form = document.getElementById('transferForm');
        form.addEventListener('submit', function(e) {
            const department = document.querySelector('input[name="target_department"]:checked');
            const reason = document.querySelector('select[name="transfer_reason"]').value;
            
            if (!department) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Department Required',
                    text: 'Please select a target department'
                });
                return false;
            }
            
            if (!reason) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Reason Required',
                    text: 'Please select a transfer reason'
                });
                return false;
            }
            
            // Show confirmation
            e.preventDefault();
            const deptName = department.parentElement.getAttribute('data-name');
            
            Swal.fire({
                title: 'Confirm Transfer',
                html: `Transfer <strong><?php echo htmlspecialchars($queue_data['full_name']); ?></strong> to <strong>${deptName}</strong>?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#667eea',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, Transfer Patient'
            }).then((result) => {
                if (result.isConfirmed) {
                    const submitBtn = form.querySelector('button[type="submit"]');
                    submitBtn.innerHTML = '<i class="ri-loader-2-line me-1"></i> Transferring...';
                    submitBtn.disabled = true;
                    form.submit();
                }
            });
        });
    });
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>