<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';
include 'layouts/smart_config.php'; // Add Smart configuration

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$errors = [];
$success_message = '';

// Fetch insurance providers (with Smart enabled flag)
$insurance_providers_sql = "SELECT provider_id, provider_name, provider_code, smart_enabled, smart_medical_aid_code 
                            FROM insurance_providers WHERE is_active = 1 ORDER BY provider_name";
$insurance_providers = $conn->query($insurance_providers_sql);

// Fetch active departments for queue routing
$departments_sql = "SELECT department_id, department_code, department_name, description, avg_service_time_minutes 
                    FROM departments WHERE is_active = 1 ORDER BY display_order";
$departments = $conn->query($departments_sql);

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $registration_type = $_POST['registration_type'] ?? '';
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone_primary = trim($_POST['phone_primary'] ?? '');
    $phone_secondary = trim($_POST['phone_secondary'] ?? '');
    $date_of_birth = $_POST['date_of_birth'] ?? '';
    $gender = $_POST['gender'] ?? '';
    $national_id = trim($_POST['national_id'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $emergency_contact_name = trim($_POST['emergency_contact_name'] ?? '');
    $emergency_contact_phone = trim($_POST['emergency_contact_phone'] ?? '');
    
    // Patient-specific fields
    $insurance_provider_id = $_POST['insurance_provider_id'] ?? null;
    $insurance_number = trim($_POST['insurance_number'] ?? '');
    $policy_number = trim($_POST['policy_number'] ?? '');
    $employer = trim($_POST['employer'] ?? '');
    $occupation = trim($_POST['occupation'] ?? '');
    $marital_status = $_POST['marital_status'] ?? '';
    $blood_group = $_POST['blood_group'] ?? '';
    $allergies = trim($_POST['allergies'] ?? '');
    $chronic_conditions = trim($_POST['chronic_conditions'] ?? '');
    $current_medications = trim($_POST['current_medications'] ?? '');
    $family_medical_history = trim($_POST['family_medical_history'] ?? '');
    $ent_history = trim($_POST['ent_history'] ?? '');
    
    // Corporate specific
    $corporate_name = trim($_POST['corporate_name'] ?? '');
    $employee_id = trim($_POST['employee_id'] ?? '');
    
    // Referral specific
    $referring_hospital = trim($_POST['referring_hospital'] ?? '');
    $referring_doctor = trim($_POST['referring_doctor'] ?? '');
    $referral_reason = trim($_POST['referral_reason'] ?? '');
    
    // Queue routing fields
    $route_to_department = $_POST['route_to_department'] ?? '';
    $queue_priority = $_POST['queue_priority'] ?? 'NORMAL';
    $chief_complaint = trim($_POST['chief_complaint'] ?? '');
    $service_type = trim($_POST['service_type'] ?? '');
    $special_needs = trim($_POST['special_needs'] ?? '');
    $is_vip = isset($_POST['is_vip']) ? 1 : 0;
    $notification_preference = $_POST['notification_preference'] ?? 'SMS';
    
    // Smart integration fields
    $smart_session_data = isset($_POST['smart_session_data']) ? json_decode($_POST['smart_session_data'], true) : null;
    $is_smart_enabled = isset($_POST['is_smart_enabled']) && $_POST['is_smart_enabled'] === '1';
    
    // Validation
    if (empty($full_name)) {
        $errors[] = "Full name is required";
    }
    
    if (empty($phone_primary)) {
        $errors[] = "Primary phone number is required";
    } elseif (!preg_match('/^(\+254|0)[7-9]\d{8}$/', $phone_primary)) {
        $errors[] = "Please enter a valid Kenyan phone number";
    }
    
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address";
    }
    
    if (empty($date_of_birth)) {
        $errors[] = "Date of birth is required";
    }
    
    if (empty($gender)) {
        $errors[] = "Gender is required";
    }
    
    if (empty($registration_type)) {
        $errors[] = "Registration type is required";
    }
    
    if (empty($route_to_department)) {
        $errors[] = "Please select a department to route the patient";
    }
    
    // Type-specific validation
    if ($registration_type === 'INSURANCE') {
        if (empty($insurance_provider_id)) {
            $errors[] = "Insurance provider is required for insurance registration";
        }
        if (empty($insurance_number)) {
            $errors[] = "Insurance number is required for insurance registration";
        }
        
        // Smart validation - check if provider is Smart-enabled
        if ($insurance_provider_id && $is_smart_enabled) {
            if (!$smart_session_data) {
                $errors[] = "Smart card session is required for this insurance provider. Please fetch the Smart card session.";
            }
        }
    }
    
    if ($registration_type === 'CORPORATE') {
        if (empty($corporate_name)) {
            $errors[] = "Company name is required for corporate registration";
        }
        $employer = $corporate_name;
    }
    
    if ($registration_type === 'ONLINE') {
        if (empty($email)) {
            $errors[] = "Email is required for online registration";
        }
    }
    
    // Check for duplicate phone
    if (empty($errors)) {
        $check_phone_sql = "SELECT user_id FROM users WHERE phone_primary = ?";
        $stmt = $conn->prepare($check_phone_sql);
        $stmt->bind_param("s", $phone_primary);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "A patient with this phone number already exists";
        }
    }
    
    // Check for duplicate email
    if (empty($errors) && !empty($email)) {
        $check_email_sql = "SELECT user_id FROM users WHERE email = ?";
        $stmt = $conn->prepare($check_email_sql);
        $stmt->bind_param("s", $email);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "A user with this email already exists";
        }
    }
    
    // If no errors, proceed with transaction
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            // Get patient role ID
            $patient_role_sql = "SELECT role_id FROM user_roles WHERE role_code = 'PATIENT'";
            $patient_role_result = $conn->query($patient_role_sql);
            $patient_role_id = $patient_role_result->fetch_assoc()['role_id'];
            
            // Insert into users table
            $user_sql = "INSERT INTO users (user_type, email, full_name, phone_primary, phone_secondary, 
                        role_id, status, date_of_birth, gender, national_id, address, 
                        emergency_contact_name, emergency_contact_phone, created_at) 
                        VALUES ('PATIENT', ?, ?, ?, ?, ?, 'ACTIVE', ?, ?, ?, ?, ?, ?, NOW())";
            
            $stmt = $conn->prepare($user_sql);
            $stmt->bind_param("ssssissssss", 
                $email, $full_name, $phone_primary, $phone_secondary, 
                $patient_role_id, $date_of_birth, $gender, $national_id, 
                $address, $emergency_contact_name, $emergency_contact_phone
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create user record");
            }
            
            $new_user_id = $conn->insert_id;
            
            // Generate patient number
            $patient_number_sql = "SELECT GeneratePatientNumber() as patient_number";
            $patient_number_result = $conn->query($patient_number_sql);
            $patient_number = $patient_number_result->fetch_assoc()['patient_number'];
            
            // Insert into patients table
            $patient_sql = "INSERT INTO patients (user_id, patient_number, registration_type, 
                           insurance_provider_id, insurance_number, policy_number, employer, 
                           occupation, marital_status, blood_group, allergies, chronic_conditions, 
                           current_medications, family_medical_history, ent_history, is_active, created_at) 
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())";
            
            $stmt = $conn->prepare($patient_sql);
            $stmt->bind_param("isssissssssssss", 
                $new_user_id, $patient_number, $registration_type, 
                $insurance_provider_id, $insurance_number, $policy_number, 
                $employer, $occupation, $marital_status, $blood_group, 
                $allergies, $chronic_conditions, $current_medications, 
                $family_medical_history, $ent_history
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create patient record");
            }
            
            $patient_id = $conn->insert_id;
            
            // Create patient visit record
            $visit_number = 'VST-' . date('Ymd') . '-' . str_pad($patient_id, 6, '0', STR_PAD_LEFT);
            $visit_sql = "INSERT INTO patient_visits (visit_number, patient_id, visit_type, registration_date, status, created_at)
                         VALUES (?, ?, 'OUT_PATIENT', CURDATE(), 'ACTIVE', NOW())";
            $stmt = $conn->prepare($visit_sql);
            $stmt->bind_param("si", $visit_number, $patient_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create visit record");
            }
            
            $visit_id = $conn->insert_id;
            
            // ============================================
            // SMART INTEGRATION - Handle Smart Session
            // ============================================
            $smart_status_message = '';
            $smart_session_activated = false;
            
            if ($registration_type === 'INSURANCE' && $is_smart_enabled && $smart_session_data) {
                try {
                    $smart_session_id = $smart_session_data['session_id'] ?? null;
                    $smart_patient_number = $smart_session_data['patient_number'] ?? $patient_number;
                    $smart_member_number = $smart_session_data['medicalaid_number'] ?? $insurance_number;
                    $smart_global_id = $smart_session_data['global_id'] ?? null;
                    $session_type = $smart_session_data['session_type'] ?? 'Outpatient';
                    $benefits_json = json_encode($smart_session_data['benefits'] ?? []);
                    $has_copay = isset($smart_session_data['has_copay']) && $smart_session_data['has_copay'] ? 1 : 0;
                    $copay_amount = $smart_session_data['co_pay_amount'] ?? 0;
                    
                    // Insert Smart session record
                    $smart_session_sql = "INSERT INTO smart_sessions (
                        patient_id, smart_session_id, smart_patient_number,
                        smart_member_number, smart_global_id, session_status,
                        session_type, benefits_data, created_at
                    ) VALUES (?, ?, ?, ?, ?, 'PENDING', ?, ?, NOW())";
                    
                    $stmt = $conn->prepare($smart_session_sql);
                    $stmt->bind_param(
                        "issssss",
                        $patient_id, $smart_session_id, $smart_patient_number,
                        $smart_member_number, $smart_global_id, $session_type,
                        $benefits_json
                    );
                    
                    if (!$stmt->execute()) {
                        throw new Exception("Failed to create Smart session record");
                    }
                    
                    $local_smart_session_id = $conn->insert_id;
                    
                    // Store individual benefits
                    if (isset($smart_session_data['benefits']) && is_array($smart_session_data['benefits'])) {
                        foreach ($smart_session_data['benefits'] as $benefit) {
                            $pool_number = $benefit['pool_nr'] ?? '';
                            $pool_desc = $benefit['pool_desc'] ?? '';
                            $amount = $benefit['amount'] ?? 0;
                            $claimable = isset($benefit['claimable']) && $benefit['claimable'] ? 1 : 0;
                            $parent_pool = $benefit['parent_pool_nr'] ?? null;
                            $service_groups_json = json_encode($benefit['groups'] ?? []);
                            
                            $benefit_sql = "INSERT INTO smart_benefits (
                                session_id, pool_number, pool_description, amount,
                                claimable, parent_pool_number, service_groups
                            ) VALUES (?, ?, ?, ?, ?, ?, ?)";
                            
                            $stmt = $conn->prepare($benefit_sql);
                            $stmt->bind_param(
                                "issidss",
                                $local_smart_session_id, $pool_number, $pool_desc,
                                $amount, $claimable, $parent_pool, $service_groups_json
                            );
                            $stmt->execute();
                        }
                    }
                    
                    // Activate Smart session with visit number
                    $activation_response = makeSmartAPIRequest(
                        "/api/visit/{$smart_session_id}/visit-number/{$visit_number}",
                        'PUT',
                        null,
                        $conn
                    );
                    
                    if ($activation_response['success']) {
                        // Update session status to ACTIVE
                        $update_session_sql = "UPDATE smart_sessions 
                                              SET session_status = 'ACTIVE', visit_id = ?, updated_at = NOW()
                                              WHERE id = ?";
                        $stmt = $conn->prepare($update_session_sql);
                        $stmt->bind_param("ii", $visit_id, $local_smart_session_id);
                        $stmt->execute();
                        
                        // Update visit with Smart session ID
                        $update_visit_sql = "UPDATE patient_visits 
                                            SET smart_session_id = ?
                                            WHERE visit_id = ?";
                        $stmt = $conn->prepare($update_visit_sql);
                        $stmt->bind_param("ii", $local_smart_session_id, $visit_id);
                        $stmt->execute();
                        
                        $smart_session_activated = true;
                        
                        // Fetch complete member benefits
                        $benefits_response = makeSmartAPIRequest(
                            "/api/member?patientNumber={$smart_patient_number}&sessionId={$smart_session_id}",
                            'GET',
                            null,
                            $conn
                        );
                        
                        if ($benefits_response['success'] && isset($benefits_response['data']['content'][0])) {
                            $member_data = $benefits_response['data']['content'][0];
                            
                            // Update benefits data with complete information
                            $full_benefits = json_encode($member_data['benefits'] ?? []);
                            $update_benefits_sql = "UPDATE smart_sessions 
                                                   SET benefits_data = ?, updated_at = NOW()
                                                   WHERE id = ?";
                            $stmt = $conn->prepare($update_benefits_sql);
                            $stmt->bind_param("si", $full_benefits, $local_smart_session_id);
                            $stmt->execute();
                            
                            // Update benefits table with complete info
                            foreach ($member_data['benefits'] as $benefit) {
                                $pool_number = $benefit['pool_nr'] ?? '';
                                $amount = $benefit['amount'] ?? 0;
                                
                                $update_benefit_sql = "UPDATE smart_benefits 
                                                      SET amount = ?, updated_at = NOW()
                                                      WHERE session_id = ? AND pool_number = ?";
                                $stmt = $conn->prepare($update_benefit_sql);
                                $stmt->bind_param("dis", $amount, $local_smart_session_id, $pool_number);
                                $stmt->execute();
                            }
                        }
                        
                        // Store copay rules if applicable
                        if ($has_copay && $copay_amount > 0) {
                            $copay_type = 'FIXED'; // Default to fixed, can be enhanced
                            $copay_sql = "INSERT INTO smart_copay_rules (
                                session_id, copay_type, amount, is_per_visit, created_at
                            ) VALUES (?, ?, ?, 0, NOW())";
                            $stmt = $conn->prepare($copay_sql);
                            $stmt->bind_param("isd", $local_smart_session_id, $copay_type, $copay_amount);
                            $stmt->execute();
                            
                            $smart_status_message .= "<br>- Copay Required: <span class='text-warning'>KES " . number_format($copay_amount, 2) . "</span>";
                        }
                        
                        $smart_status_message = "<br><br><strong class='text-success'>
                                                <i class='ri-shield-check-line'></i> Smart Card Integration Successful:</strong><br>
                                                - Session Activated: " . htmlspecialchars($smart_session_id) . "<br>
                                                - Member: " . htmlspecialchars($smart_member_number) . "<br>
                                                - Benefits Loaded: " . count($smart_session_data['benefits'] ?? []) . " pool(s)" .
                                                $smart_status_message;
                    } else {
                        // Log activation failure but don't rollback
                        error_log("Smart session activation failed: " . json_encode($activation_response));
                        $smart_status_message = "<br><br><strong class='text-warning'>
                                                <i class='ri-alert-line'></i> Smart Card Warning:</strong><br>
                                                Session created but not activated. Please activate manually in billing.";
                    }
                    
                } catch (Exception $smart_error) {
                    // Log Smart error but don't fail entire registration
                    error_log("Smart Integration Error: " . $smart_error->getMessage());
                    $smart_status_message = "<br><br><strong class='text-warning'>
                                            <i class='ri-alert-line'></i> Smart Card Warning:</strong><br>
                                            " . $smart_error->getMessage() . "<br>
                                            Patient registered successfully, but Smart integration incomplete.";
                }
            }
            
            // Generate queue number using function
            $queue_number_sql = "SELECT GenerateQueueNumber(?) as queue_number";
            $stmt = $conn->prepare($queue_number_sql);
            
            // Get department code
            $dept_code_sql = "SELECT department_code FROM departments WHERE department_id = ?";
            $dept_stmt = $conn->prepare($dept_code_sql);
            $dept_stmt->bind_param("i", $route_to_department);
            $dept_stmt->execute();
            $dept_code = $dept_stmt->get_result()->fetch_assoc()['department_code'];
            
            $stmt->bind_param("s", $dept_code);
            $stmt->execute();
            $queue_number = $stmt->get_result()->fetch_assoc()['queue_number'];
            
            // Calculate age for queue record
            $dob = new DateTime($date_of_birth);
            $now = new DateTime();
            $age = $now->diff($dob)->y;
            
            // Insert into patient queue
            $queue_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,
                            notification_preference, created_by, created_at
                         ) VALUES (?, ?, ?, ?, 'WAITING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $stmt = $conn->prepare($queue_sql);
            $stmt->bind_param("siiissssssisssiii",
                $queue_number, $patient_id, $visit_id, $route_to_department,
                $queue_priority, $registration_type,
                $full_name, $patient_number, $phone_primary, $age, $gender,
                $service_type, $chief_complaint, $special_needs, $is_vip,
                $notification_preference, $user_id
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to add patient to queue");
            }
            
            $queue_id = $conn->insert_id;
            
            // Update queue positions for the department
            $conn->query("CALL UpdateQueuePositions($route_to_department)");
            $conn->query("CALL UpdateQueueWaitTimes($route_to_department)");
            
            // ============================================
            // CREATE ACCOUNTING ENTRY FOR REGISTRATION
            // ============================================
            
            // Determine registration fee based on type
            $registration_fee = 0;
            switch ($registration_type) {
                case 'WALK_IN':
                    $registration_fee = 500.00;
                    break;
                case 'INSURANCE':
                    $registration_fee = 0; // No upfront fee for insurance
                    break;
                case 'CORPORATE':
                    $registration_fee = 0;
                    break;
                case 'ONLINE':
                    $registration_fee = 300.00;
                    break;
                case 'REFERRAL':
                    $registration_fee = 400.00;
                    break;
            }
            
            // Create accounting entry if there's a registration fee
            $journal_number = null;
            $journal_id = null;
            
            if ($registration_fee > 0) {
                $accounting_sql = "CALL CreatePatientRegistrationEntry(?, ?, ?, ?)";
                $stmt = $conn->prepare($accounting_sql);
                $stmt->bind_param("isdi", 
                    $patient_id, 
                    $registration_type, 
                    $registration_fee, 
                    $user_id
                );
                
                if (!$stmt->execute()) {
                    throw new Exception("Failed to create accounting entry: " . $stmt->error);
                }
                
                $accounting_result = $stmt->get_result();
                if ($accounting_result && $accounting_data = $accounting_result->fetch_assoc()) {
                    $journal_number = $accounting_data['journal_number'] ?? null;
                    $journal_id = $accounting_data['journal_id'] ?? null;
                }
                
                $stmt->close();
                while ($conn->more_results()) {
                    $conn->next_result();
                    if ($res = $conn->store_result()) {
                        $res->free();
                    }
                }
                
                if ($journal_id) {
                    $accounting_log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, 
                                           record_type, new_values, ip_address, logged_at) 
                                           VALUES (?, 'CREATE', 'ACCOUNTING', ?, 'JOURNAL_ENTRY', ?, ?, NOW())";
                    
                    $accounting_values = json_encode([
                        'journal_number' => $journal_number,
                        'patient_id' => $patient_id,
                        'patient_number' => $patient_number,
                        'registration_fee' => $registration_fee,
                        'registration_type' => $registration_type,
                        'entry_type' => 'AUTO_PATIENT_REG'
                    ]);
                    
                    $ip_address = $_SERVER['REMOTE_ADDR'];
                    
                    $stmt = $conn->prepare($accounting_log_sql);
                    $stmt->bind_param("iiss", 
                        $user_id, 
                        $journal_id, 
                        $accounting_values, 
                        $ip_address
                    );
                    $stmt->execute();
                }
            }
            
            // Log the patient registration activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                           new_values, ip_address, logged_at) 
                           VALUES (?, 'CREATE', 'PATIENT', ?, 'PATIENT', ?, ?, NOW())";
            
            $new_values = json_encode([
                'patient_number' => $patient_number,
                'full_name' => $full_name,
                'registration_type' => $registration_type,
                'phone_primary' => $phone_primary,
                'queue_number' => $queue_number,
                'department_id' => $route_to_department,
                'registration_fee' => $registration_fee,
                'journal_number' => $journal_number,
                'smart_integrated' => $smart_session_activated
            ]);
            
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            $stmt = $conn->prepare($activity_sql);
            $stmt->bind_param("iiss", $user_id, $patient_id, $new_values, $ip_address);
            $stmt->execute();
            
            // Commit the entire transaction
            $conn->commit();
            
            // Build success message
            $success_message = "Patient registered successfully!<br>
                              <strong>Patient Number:</strong> " . htmlspecialchars($patient_number) . "<br>
                              <strong>Queue Number:</strong> " . htmlspecialchars($queue_number);
            
            if ($registration_fee > 0) {
                $success_message .= "<br><strong>Registration Fee:</strong> KES " . number_format($registration_fee, 2);
                
                if ($journal_number) {
                    $success_message .= "<br><strong>Journal Entry:</strong> " . htmlspecialchars($journal_number) . " (Posted to General Ledger)";
                }
            }
            
            // Add Smart integration status
            $success_message .= $smart_status_message;
            
            // Clear form
            $_POST = array();
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Registration failed: " . $e->getMessage();
            error_log("Patient Registration Error: " . $e->getMessage());
        }
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Registration')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        /* Keep all your existing styles */
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            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;
        }
        
        .registration-type-cards, .department-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .registration-card, .department-card {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 1.25rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: white;
        }
        
        .registration-card:hover, .department-card:hover {
            border-color: #667eea;
            background: #f8faff;
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .registration-card.active, .department-card.active {
            border-color: #667eea;
            background: #eff6ff;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .registration-icon, .department-icon {
            font-size: 2.5rem;
            margin-bottom: 0.75rem;
        }
        
        .registration-title, .department-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
            font-size: 0.95rem;
        }
        
        .registration-desc, .department-desc {
            font-size: 0.875rem;
            color: #64748b;
            margin: 0;
        }
        
        .type-specific-fields {
            display: none;
            animation: fadeIn 0.3s ease-in;
        }
        
        .type-specific-fields.show {
            display: block;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .required {
            color: #ef4444;
        }
        
        .form-label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .section-title {
            font-size: 1rem;
            font-weight: 600;
            color: #475569;
            margin: 1.5rem 0 1rem 0;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .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 {
            border-color: #667eea;
            background: #eff6ff;
        }
        
        .priority-option.normal.active {
            border-color: #10b981;
            background: #d1fae5;
        }
        
        .priority-option.urgent.active {
            border-color: #f59e0b;
            background: #fef3c7;
        }
        
        .priority-option.emergency.active {
            border-color: #ef4444;
            background: #fee2e2;
        }
        
        .queue-info-box {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }
        
        .queue-info-box .info-item {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .queue-info-box .info-item:last-child {
            border-bottom: none;
        }
        
        .queue-info-box .info-label {
            font-weight: 500;
            color: #64748b;
        }
        
        .queue-info-box .info-value {
            font-weight: 600;
            color: #1e293b;
        }
        
        .accounting-info-box {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border: 2px solid #86efac;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }
        
        .accounting-info-box h6 {
            color: #15803d;
            margin-bottom: 0.75rem;
            font-weight: 600;
        }
        
        .accounting-info-box .accounting-detail {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            color: #166534;
        }
        
        /* Smart Card Integration Styles */
        .smart-card-section {
            background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
            border: 2px solid #60a5fa;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1rem;
        }
        
        .smart-card-section.active {
            border-color: #10b981;
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
        }
        
        .benefit-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
            margin: 0.25rem;
        }
        
        .benefit-badge.active {
            background: #d1fae5;
            color: #166534;
        }
        
        .benefit-badge.inactive {
            background: #f1f5f9;
            color: #64748b;
        }
        
        .smart-status-indicator {
            display: inline-flex;
            align-items: center;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 600;
            margin-bottom: 1rem;
        }
        
        .smart-status-indicator.pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        .smart-status-indicator.active {
            background: #d1fae5;
            color: #166534;
        }
        
        .smart-status-indicator.error {
            background: #fee2e2;
            color: #991b1b;
        }
    </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">Patient Registration & Queue Routing</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_patients.php">Patients</a></li>
                                        <li class="breadcrumb-item active">Register Patient</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong><i class="ri-error-warning-line me-2"></i>Registration 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><i class="ri-checkbox-circle-line me-2"></i>Success!</strong> 
                        <div class="mt-2"><?php echo $success_message; ?></div>
                        <div class="mt-3">
                            <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="register_patient.php" class="btn btn-sm btn-secondary">
                                <i class="ri-add-line me-1"></i> Register Another Patient
                            </a>
                            <?php if (isset($journal_number) && $journal_number): ?>
                            <a href="journal_entries.php" class="btn btn-sm btn-success">
                                <i class="ri-book-line me-1"></i> View Journal Entries
                            </a>
                            <?php endif; ?>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <form id="patientRegistrationForm" method="POST">
                        <!-- Hidden fields for Smart integration -->
                        <input type="hidden" name="smart_session_data" id="smartSessionDataInput" value="">
                        <input type="hidden" name="is_smart_enabled" id="isSmartEnabled" value="0">
                        
                        <!-- Registration Type -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-file-list-3-line me-2"></i>Registration Type
                                </h5>
                            </div>
                            <div class="form-body">
                                <div class="registration-type-cards">
                                    <div class="registration-card" data-type="WALK_IN" data-fee="500">
                                        <div class="registration-icon">💰</div>
                                        <div class="registration-title">Walk-in</div>
                                        <p class="registration-desc">Cash payment</p>
                                        <small class="text-success fw-bold">Fee: KES 500</small>
                                        <input type="radio" name="registration_type" value="WALK_IN" style="display: none;">
                                    </div>
                                    <div class="registration-card" data-type="INSURANCE" data-fee="0">
                                        <div class="registration-icon">🛡️</div>
                                        <div class="registration-title">Insurance</div>
                                        <p class="registration-desc">Medical cover</p>
                                        <small class="text-muted">Smart Card</small>
                                        <input type="radio" name="registration_type" value="INSURANCE" style="display: none;">
                                    </div>
                                    <div class="registration-card" data-type="CORPORATE" data-fee="0">
                                        <div class="registration-icon">🏢</div>
                                        <div class="registration-title">Corporate</div>
                                        <p class="registration-desc">Company</p>
                                        <small class="text-muted">Billed later</small>
                                        <input type="radio" name="registration_type" value="CORPORATE" style="display: none;">
                                    </div>
                                    <div class="registration-card" data-type="REFERRAL" data-fee="400">
                                        <div class="registration-icon">🏥</div>
                                        <div class="registration-title">Referral</div>
                                        <p class="registration-desc">Hospital referral</p>
                                        <small class="text-success fw-bold">Fee: KES 400</small>
                                        <input type="radio" name="registration_type" value="REFERRAL" style="display: none;">
                                    </div>
                                    <div class="registration-card" data-type="ONLINE" data-fee="300">
                                        <div class="registration-icon">💻</div>
                                        <div class="registration-title">Online</div>
                                        <p class="registration-desc">Web booking</p>
                                        <small class="text-success fw-bold">Fee: KES 300</small>
                                        <input type="radio" name="registration_type" value="ONLINE" style="display: none;">
                                    </div>
                                </div>
                                
                                <!-- Editable Registration Fee -->
                                <div class="card border-primary mt-3" id="registrationFeeCard" style="display: none;">
                                    <div class="card-header bg-light">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0">
                                                <i class="ri-money-dollar-circle-line me-2"></i>Registration Fee
                                            </h6>
                                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="showFeeSelector()">
                                                <i class="ri-edit-line me-1"></i>Change Fee
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="form-label">Selected Fee Type</label>
                                                <input type="text" class="form-control" id="selectedFeeType" readonly>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Amount (KES)</label>
                                                <div class="input-group">
                                                    <span class="input-group-text">KES</span>
                                                    <input type="number" step="0.01" class="form-control" name="registration_fee_amount" 
                                                           id="registrationFeeAmount" value="0.00" min="0">
                                                    <input type="hidden" name="registration_fee_type" id="registrationFeeType">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Accounting Preview Box -->
                                <div class="accounting-info-box" id="accountingPreview" style="display: none;">
                                    <h6><i class="ri-money-dollar-circle-line me-2"></i>Accounting Entry Preview</h6>
                                    <div class="accounting-detail">
                                        <span>Registration Fee:</span>
                                        <strong id="previewFee">KES 0.00</strong>
                                    </div>
                                    <div class="accounting-detail">
                                        <span>Debit Account:</span>
                                        <strong id="previewDebit">-</strong>
                                    </div>
                                    <div class="accounting-detail">
                                        <span>Credit Account:</span>
                                        <strong>Registration Revenue</strong>
                                    </div>
                                    <div class="accounting-detail" style="border-top: 2px solid #86efac; padding-top: 0.5rem; margin-top: 0.5rem;">
                                        <span>Journal Entry Type:</span>
                                        <strong>Auto - Patient Registration</strong>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Personal Information -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-user-line me-2"></i>Personal Information
                                </h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Full Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="full_name" id="fullNameInput"
                                               value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>" 
                                               placeholder="Enter full name" required>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Date of Birth <span class="required">*</span></label>
                                        <input type="date" class="form-control" name="date_of_birth" 
                                               value="<?php echo htmlspecialchars($_POST['date_of_birth'] ?? ''); ?>" 
                                               max="<?php echo date('Y-m-d'); ?>" required>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Gender <span class="required">*</span></label>
                                        <select class="form-select" name="gender" required>
                                            <option value="">Select</option>
                                            <option value="MALE" <?php echo ($_POST['gender'] ?? '') === 'MALE' ? 'selected' : ''; ?>>Male</option>
                                            <option value="FEMALE" <?php echo ($_POST['gender'] ?? '') === 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                            <option value="OTHER" <?php echo ($_POST['gender'] ?? '') === 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Primary Phone <span class="required">*</span></label>
                                        <input type="tel" class="form-control" name="phone_primary" id="phonePrimaryInput"
                                               value="<?php echo htmlspecialchars($_POST['phone_primary'] ?? ''); ?>" 
                                               placeholder="0712345678" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Secondary Phone</label>
                                        <input type="tel" class="form-control" name="phone_secondary" 
                                               value="<?php echo htmlspecialchars($_POST['phone_secondary'] ?? ''); ?>" 
                                               placeholder="0712345678">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Email</label>
                                        <input type="email" class="form-control" name="email" 
                                               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" 
                                               placeholder="patient@example.com">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">National ID</label>
                                        <input type="text" class="form-control" name="national_id" 
                                               value="<?php echo htmlspecialchars($_POST['national_id'] ?? ''); ?>">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Marital Status</label>
                                        <select class="form-select" name="marital_status">
                                            <option value="">Select</option>
                                            <option value="SINGLE">Single</option>
                                            <option value="MARRIED">Married</option>
                                            <option value="DIVORCED">Divorced</option>
                                            <option value="WIDOWED">Widowed</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Blood Group</label>
                                        <select class="form-select" name="blood_group">
                                            <option value="">Select</option>
                                            <option value="A+">A+</option>
                                            <option value="A-">A-</option>
                                            <option value="B+">B+</option>
                                            <option value="B-">B-</option>
                                            <option value="AB+">AB+</option>
                                            <option value="AB-">AB-</option>
                                            <option value="O+">O+</option>
                                            <option value="O-">O-</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-8 mb-3">
                                        <label class="form-label">Address</label>
                                        <textarea class="form-control" name="address" rows="2"><?php echo htmlspecialchars($_POST['address'] ?? ''); ?></textarea>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Occupation</label>
                                        <input type="text" class="form-control" name="occupation" 
                                               value="<?php echo htmlspecialchars($_POST['occupation'] ?? ''); ?>">
                                    </div>
                                </div>
                                
                                <div class="section-title">Emergency Contact</div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Contact Name</label>
                                        <input type="text" class="form-control" name="emergency_contact_name" 
                                               value="<?php echo htmlspecialchars($_POST['emergency_contact_name'] ?? ''); ?>">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Contact Phone</label>
                                        <input type="tel" class="form-control" name="emergency_contact_phone" 
                                               value="<?php echo htmlspecialchars($_POST['emergency_contact_phone'] ?? ''); ?>">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Insurance Fields with Smart Integration -->
                        <div class="form-card type-specific-fields" id="insuranceFields">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-shield-line me-2"></i>Insurance Information
                                </h5>
                            </div>
                            <div class="form-body">
                                <div class="alert alert-info">
                                    <i class="ri-information-line me-2"></i>
                                    <strong>Note:</strong> No upfront registration fee. Insurance will be billed directly.
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Provider <span class="required">*</span></label>
                                        <select class="form-select" name="insurance_provider_id" id="insuranceProvider">
                                            <option value="">Select Provider</option>
                                            <?php 
                                            $insurance_providers->data_seek(0);
                                            while ($provider = $insurance_providers->fetch_assoc()): 
                                            ?>
                                                <option value="<?php echo $provider['provider_id']; ?>"
                                                        data-smart-enabled="<?php echo $provider['smart_enabled']; ?>"
                                                        data-smart-code="<?php echo htmlspecialchars($provider['smart_medical_aid_code'] ?? ''); ?>">
                                                    <?php echo htmlspecialchars($provider['provider_name']); ?>
                                                    <?php if ($provider['smart_enabled']): ?>
                                                         🔷
                                                    <?php endif; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <small class="text-muted">🔷 = Smart Card Enabled</small>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Member Number <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="insurance_number" id="insuranceNumber">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Policy Number</label>
                                        <input type="text" class="form-control" name="policy_number" id="policyNumber">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Employer</label>
                                        <input type="text" class="form-control" name="employer">
                                    </div>
                                </div>
                                
                                <!-- Smart Card Integration Section -->
                                <div class="smart-card-section" id="smartCardSection" style="display: none;">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="mb-0">
                                            <i class="ri-shield-check-line me-2"></i>Smart Card Integration
                                        </h6>
                                        <div class="smart-status-indicator pending" id="smartStatusIndicator">
                                            <i class="ri-loader-4-line me-2"></i>Pending Card Forward
                                        </div>
                                    </div>
                                    
                                    <!-- SMARTLINK INSTRUCTIONS -->
                                    <div class="alert alert-info mb-3">
                                        <div class="d-flex align-items-start">
                                            <i class="ri-information-line me-2 mt-1" style="font-size: 1.5rem;"></i>
                                            <div>
                                                <h6 class="alert-heading mb-2">SmartLink Requirement</h6>
                                                <p class="mb-2"><strong>Before clicking "Fetch Smart Card Session":</strong></p>
                                                <ol class="mb-2 ps-3">
                                                    <li>Patient must present their Smart card at the <strong>SmartLink terminal</strong></li>
                                                    <li>Forward the card in the SmartLink system</li>
                                                    <li>Wait for confirmation that the card is successfully forwarded</li>
                                                    <li>Then return here and click the button below</li>
                                                </ol>
                                                <small class="text-muted">
                                                    <i class="ri-lightbulb-line me-1"></i>
                                                    <strong>Tip:</strong> If SmartLink terminal is at reception, have them forward the card before registering.
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- SMARTLINK STATUS CHECK -->
                                    <div class="card border-warning mb-3" id="smartLinkStatusCard">
                                        <div class="card-body p-3">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <h6 class="mb-1">
                                                        <i class="ri-computer-line me-2"></i>SmartLink Status
                                                    </h6>
                                                    <small class="text-muted">Check if SmartLink terminal is online and ready</small>
                                                </div>
                                                <button type="button" class="btn btn-sm btn-outline-warning" onclick="checkSmartLinkStatus()">
                                                    <i class="ri-refresh-line me-1"></i>Check Status
                                                </button>
                                            </div>
                                            <div id="smartLinkStatusResult" class="mt-2" style="display: none;"></div>
                                        </div>
                                    </div>
                                    
                                    <button type="button" class="btn btn-primary btn-lg mb-3" id="fetchSmartSessionBtn">
                                        <i class="ri-refresh-line me-2"></i>Fetch Smart Card Session
                                    </button>
                                    
                                    <!-- Smart Session Data Display -->
                                    <div id="smartSessionDisplay" style="display: none;">
                                        <div class="card border-success">
                                            <div class="card-header bg-success text-white">
                                                <h6 class="mb-0">
                                                    <i class="ri-checkbox-circle-line me-2"></i>Smart Card Data Retrieved Successfully
                                                </h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <p class="mb-2"><strong>Member Name:</strong> <span id="smartMemberName">-</span></p>
                                                        <p class="mb-2"><strong>Member Number:</strong> <span id="smartMemberNumber">-</span></p>
                                                        <p class="mb-2"><strong>Scheme:</strong> <span id="smartSchemeName">-</span></p>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <p class="mb-2"><strong>Policy ID:</strong> <span id="smartPolicyId">-</span></p>
                                                        <p class="mb-2"><strong>Session ID:</strong> <span id="smartSessionId">-</span></p>
                                                        <p class="mb-2"><strong>Copay:</strong> <span id="smartCopay">-</span></p>
                                                    </div>
                                                </div>
                                                
                                                <div class="mt-3">
                                                    <strong>Available Benefits:</strong>
                                                    <div id="smartBenefitsDisplay" class="mt-2">
                                                        <!-- Benefits will be populated here -->
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Keep all your other existing form sections: Corporate, Referral, Medical History, Queue Routing -->
                        <!-- Corporate Fields -->
                        <div class="form-card type-specific-fields" id="corporateFields">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-building-line me-2"></i>Corporate Information
                                </h5>
                            </div>
                            <div class="form-body">
                                <div class="alert alert-info">
                                    <i class="ri-information-line me-2"></i>
                                    <strong>Note:</strong> No upfront registration fee. Corporate account will be billed.
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Company Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="corporate_name">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Employee ID <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="employee_id">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Referral Fields -->
                        <div class="form-card type-specific-fields" id="referralFields">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-hospital-line me-2"></i>Referral Information
                                </h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Referring Hospital</label>
                                        <input type="text" class="form-control" name="referring_hospital">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Referring Doctor</label>
                                        <input type="text" class="form-control" name="referring_doctor">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">Referral Reason</label>
                                        <textarea class="form-control" name="referral_reason" rows="2"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Medical History -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-heart-pulse-line me-2"></i>Medical History
                                </h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Allergies</label>
                                        <textarea class="form-control" name="allergies" rows="3" placeholder="List any known allergies"></textarea>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Chronic Conditions</label>
                                        <textarea class="form-control" name="chronic_conditions" rows="3" placeholder="List any chronic conditions"></textarea>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Current Medications</label>
                                        <textarea class="form-control" name="current_medications" rows="3" placeholder="List current medications"></textarea>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Family Medical History</label>
                                        <textarea class="form-control" name="family_medical_history" rows="3" placeholder="Relevant family medical history"></textarea>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">ENT History</label>
                                        <textarea class="form-control" name="ent_history" rows="3" placeholder="Previous ENT issues or treatments"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Queue Routing Section -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">
                                    <i class="ri-route-line me-2"></i>Queue Routing & Department
                                </h5>
                            </div>
                            <div class="form-body">
                                <!-- Priority Selection -->
                                <div class="mb-3">
                                    <label class="form-label">Priority Level <span class="required">*</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>
                                            <small class="d-block">Standard</small>
                                            <input type="radio" name="queue_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>
                                            <small class="d-block">Needs prompt attention</small>
                                            <input type="radio" name="queue_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>
                                            <small class="d-block">Immediate care</small>
                                            <input type="radio" name="queue_priority" value="EMERGENCY" style="display: none;">
                                        </div>
                                    </div>
                                </div>

                                <!-- Department Selection -->
                                <div class="mb-3">
                                    <label class="form-label">Route to Department <span class="required">*</span></label>
                                    <p class="text-muted small">Select the department where the patient should be queued</p>
                                    <div class="department-cards">
                                        <?php 
                                        $departments->data_seek(0);
                                        $dept_icons = [
                                            'RECEPTION' => '🎫',
                                            'TRIAGE' => '🏥',
                                            'CONSULTATION' => '👨‍⚕️',
                                            'AUDIOLOGY' => '👂',
                                            'VESTIBULAR' => '⚖️',
                                            'ENDOSCOPY' => '🔬',
                                            'MINOR_PROC' => '⚕️',
                                            'LABORATORY' => '🧪',
                                            'PHARMACY' => '💊',
                                            'BILLING' => '💳',
                                            'FOLLOW_UP' => '📋'
                                        ];
                                        while ($dept = $departments->fetch_assoc()): 
                                            $icon = $dept_icons[$dept['department_code']] ?? '🏢';
                                        ?>
                                            <div class="department-card" data-dept="<?php echo $dept['department_id']; ?>">
                                                <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="route_to_department" value="<?php echo $dept['department_id']; ?>" style="display: none;">
                                            </div>
                                        <?php endwhile; ?>
                                    </div>
                                </div>

                                <!-- Service Details -->
                                <div class="row">
                                    <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., Consultation, Audiometry, etc.">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Notification Preference</label>
                                        <select class="form-select" name="notification_preference">
                                            <option value="SMS">SMS</option>
                                            <option value="WHATSAPP">WhatsApp</option>
                                            <option value="NONE">None</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Chief Complaint / Reason for Visit</label>
                                        <textarea class="form-control" name="chief_complaint" rows="2" 
                                                  placeholder="Brief description of patient's main concern"></textarea>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-10 mb-3">
                                        <label class="form-label">Special Needs / Requirements</label>
                                        <input type="text" class="form-control" name="special_needs" 
                                               placeholder="e.g., Wheelchair access, Interpreter needed, etc.">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">VIP Patient</label>
                                        <div class="form-check form-switch" style="padding-top: 0.5rem;">
                                            <input class="form-check-input" type="checkbox" name="is_vip" id="isVip" style="width: 3rem; height: 1.5rem;">
                                            <label class="form-check-label ms-2" for="isVip">Mark as VIP</label>
                                        </div>
                                    </div>
                                </div>

                                <!-- Queue Info Preview -->
                                <div class="queue-info-box" id="queueInfoBox" style="display: none;">
                                    <h6 class="mb-3"><i class="ri-information-line me-2"></i>Queue Information</h6>
                                    <div class="info-item">
                                        <span class="info-label">Selected Department:</span>
                                        <span class="info-value" id="selectedDeptName">-</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">Average Service Time:</span>
                                        <span class="info-value" id="avgServiceTime">-</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">Priority Level:</span>
                                        <span class="info-value" id="selectedPriority">Normal</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Fee Selector Modal -->
                        <div class="modal fade" id="feeSelectorModal" tabindex="-1">
                            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                                <div class="modal-content">
                                    <div class="modal-header bg-primary text-white">
                                        <h5 class="modal-title">
                                            <i class="ri-price-tag-3-line me-2"></i>Select Service Fee
                                        </h5>
                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <!-- Search Bar -->
                                        <div class="mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">
                                                    <i class="ri-search-line"></i>
                                                </span>
                                                <input type="text" class="form-control" id="feeSearchInput" 
                                                       placeholder="Search procedures...">
                                            </div>
                                        </div>
                                        
                                        <!-- Fee Categories -->
                                        <div class="accordion" id="feeCategoriesAccordion">
                                            <!-- Consultation Services -->
                                            <div class="accordion-item">
                                                <h2 class="accordion-header">
                                                    <button class="accordion-button" type="button" data-bs-toggle="collapse" 
                                                            data-bs-target="#consultationFees">
                                                        <i class="ri-stethoscope-line me-2"></i>Consultation Services
                                                    </button>
                                                </h2>
                                                <div id="consultationFees" class="accordion-collapse collapse show" 
                                                     data-bs-parent="#feeCategoriesAccordion">
                                                    <div class="accordion-body p-0">
                                                        <div class="list-group list-group-flush">
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="5000" data-name="First Consultation" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>First Consultation</span>
                                                                    <strong class="text-success">KES 5,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="3000" data-name="Hospital Visit, Daytime" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Hospital Visit, Daytime</span>
                                                                    <strong class="text-success">KES 3,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="4500" data-name="Hospital Visit, Emergency Night Time" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Hospital Visit, Emergency Night Time</span>
                                                                    <strong class="text-success">KES 4,500.00</strong>
                                                                </div>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Procedures Under Local Anesthesia -->
                                            <div class="accordion-item">
                                                <h2 class="accordion-header">
                                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                            data-bs-target="#localAnesthesiaFees">
                                                        <i class="ri-syringe-line me-2"></i>Procedures Under Local Anesthesia
                                                    </button>
                                                </h2>
                                                <div id="localAnesthesiaFees" class="accordion-collapse collapse" 
                                                     data-bs-parent="#feeCategoriesAccordion">
                                                    <div class="accordion-body p-0">
                                                        <div class="list-group list-group-flush">
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="7000" data-name="Myringoplasty" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Myringoplasty</span>
                                                                    <strong class="text-success">KES 7,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="5000" data-name="Cautery of Nose / EAC" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Cautery of Nose / EAC</span>
                                                                    <strong class="text-success">KES 5,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="10000" data-name="Chemical Cautery" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Chemical Cautery</span>
                                                                    <strong class="text-success">KES 10,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="6000" data-name="Examination Ear Nose Throat Under Microscope (EUM)" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>EUM (Ear, Nose, Throat Under Microscope)</span>
                                                                    <strong class="text-success">KES 6,000.00</strong>
                                                                </div>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Investigations -->
                                            <div class="accordion-item">
                                                <h2 class="accordion-header">
                                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                            data-bs-target="#investigationFees">
                                                        <i class="ri-test-tube-line me-2"></i>Investigations
                                                    </button>
                                                </h2>
                                                <div id="investigationFees" class="accordion-collapse collapse" 
                                                     data-bs-parent="#feeCategoriesAccordion">
                                                    <div class="accordion-body p-0">
                                                        <div class="list-group list-group-flush">
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="7500" data-name="Endoscopy - Flexible" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Endoscopy - Flexible</span>
                                                                    <strong class="text-success">KES 7,500.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="7500" data-name="Flexible Of Nasopharynx" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Flexible Of Nasopharynx</span>
                                                                    <strong class="text-success">KES 7,500.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="5000" data-name="Flexible Of Laryngopharynx" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Flexible Of Laryngopharynx</span>
                                                                    <strong class="text-success">KES 5,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="6000" data-name="Foreign Body FB Removal (Ear, Nose)" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Foreign Body Removal (Ear, Nose)</span>
                                                                    <strong class="text-success">KES 6,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="7000" data-name="Nasopharynx Swab" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Nasopharynx Swab</span>
                                                                    <strong class="text-success">KES 7,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="5000" data-name="Larynx Video Endoscopy" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Larynx Video Endoscopy</span>
                                                                    <strong class="text-success">KES 5,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="5000" data-name="Injection and Oral Feeding E & B Abscess (Neck, Scar)" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Injection and Oral Feeding (Neck, Scar)</span>
                                                                    <strong class="text-success">KES 5,000.00</strong>
                                                                </div>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Hearing Assessment -->
                                            <div class="accordion-item">
                                                <h2 class="accordion-header">
                                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                            data-bs-target="#hearingFees">
                                                        <i class="ri-ear-line me-2"></i>Hearing Assessment
                                                    </button>
                                                </h2>
                                                <div id="hearingFees" class="accordion-collapse collapse" 
                                                     data-bs-parent="#feeCategoriesAccordion">
                                                    <div class="accordion-body p-0">
                                                        <div class="list-group list-group-flush">
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="2500" data-name="Audiometry" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Audiometry</span>
                                                                    <strong class="text-success">KES 2,500.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="2500" data-name="Tympanometry" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Tympanometry</span>
                                                                    <strong class="text-success">KES 2,500.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="3000" data-name="BERA/ABR" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>BERA/ABR</span>
                                                                    <strong class="text-success">KES 3,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="3500" data-name="Screening Audiometry" 
                                                                    data-category="Investigation">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Screening Audiometry</span>
                                                                    <strong class="text-success">KES 3,500.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="2500" data-name="Ear Wax (Cerumen) Removal and Fitting" 
                                                                    data-category="Treatment">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Ear Wax Removal and Fitting</span>
                                                                    <strong class="text-success">KES 2,500.00</strong>
                                                                </div>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Surgery Fees (Sample - Add all from your list) -->
                                            <div class="accordion-item">
                                                <h2 class="accordion-header">
                                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                            data-bs-target="#surgeryFees">
                                                        <i class="ri-surgical-mask-line me-2"></i>Surgery Procedures
                                                    </button>
                                                </h2>
                                                <div id="surgeryFees" class="accordion-collapse collapse" 
                                                     data-bs-parent="#feeCategoriesAccordion">
                                                    <div class="accordion-body p-0">
                                                        <div class="list-group list-group-flush">
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="40000" data-name="Adenoidectomy (AD) - Children" 
                                                                    data-category="Surgery">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Adenoidectomy (AD) - Children</span>
                                                                    <strong class="text-success">KES 40,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="60000" data-name="Adenotonsillectomy" 
                                                                    data-category="Surgery">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Adenotonsillectomy</span>
                                                                    <strong class="text-success">KES 60,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="80000" data-name="Antrostomy - Adult" 
                                                                    data-category="Surgery">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Antrostomy - Adult</span>
                                                                    <strong class="text-success">KES 80,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="50000" data-name="Tonsillectomy - Children" 
                                                                    data-category="Surgery">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Tonsillectomy - Children</span>
                                                                    <strong class="text-success">KES 50,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="150000" data-name="Tympanoplasty" 
                                                                    data-category="Surgery">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Tympanoplasty</span>
                                                                    <strong class="text-success">KES 150,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <button type="button" class="list-group-item list-group-item-action fee-item" 
                                                                    data-fee="120000" data-name="Mastoidectomy" 
                                                                    data-category="Surgery">
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>Mastoidectomy</span>
                                                                    <strong class="text-success">KES 120,000.00</strong>
                                                                </div>
                                                            </button>
                                                            <!-- Add more surgery items here based on your price list -->
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Custom Amount Option -->
                                        <div class="card mt-3 border-primary">
                                            <div class="card-body">
                                                <h6 class="card-title">Custom Amount</h6>
                                                <div class="row">
                                                    <div class="col-md-6 mb-2">
                                                        <input type="text" class="form-control" id="customFeeName" 
                                                               placeholder="Service name">
                                                    </div>
                                                    <div class="col-md-4 mb-2">
                                                        <input type="number" step="0.01" class="form-control" id="customFeeAmount" 
                                                               placeholder="Amount (KES)">
                                                    </div>
                                                    <div class="col-md-2 mb-2">
                                                        <button type="button" class="btn btn-primary w-100" onclick="applyCustomFee()">
                                                            Apply
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="form-card">
                            <div class="form-body">
                                <div class="d-flex justify-content-between">
                                    <a href="list_patients.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back
                                    </a>
                                    <div>
                                        <button type="button" class="btn btn-secondary me-2" onclick="clearForm()">
                                            <i class="ri-refresh-line me-1"></i> Clear
                                        </button>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Register Patient & Add to Queue
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </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 registrationCards = document.querySelectorAll('.registration-card');
    const departmentCards = document.querySelectorAll('.department-card');
    const priorityOptions = document.querySelectorAll('.priority-option');
    const insuranceFields = document.getElementById('insuranceFields');
    const corporateFields = document.getElementById('corporateFields');
    const referralFields = document.getElementById('referralFields');
    const emailInput = document.querySelector('input[name="email"]');
    const queueInfoBox = document.getElementById('queueInfoBox');
    const accountingPreview = document.getElementById('accountingPreview');
    const smartCardSection = document.getElementById('smartCardSection');
    const insuranceProviderSelect = document.getElementById('insuranceProvider');
    const registrationFeeCard = document.getElementById('registrationFeeCard');
    
    // Smart session data storage
    let smartSessionData = null;
    let isSmartEnabled = false;
    let currentRegistrationType = '';
    
    // Department data for queue info
    const departmentData = {};
    <?php 
    $departments->data_seek(0);
    while ($dept = $departments->fetch_assoc()): 
    ?>
    departmentData[<?php echo $dept['department_id']; ?>] = {
        name: '<?php echo addslashes($dept['department_name']); ?>',
        avgTime: <?php echo $dept['avg_service_time_minutes']; ?>
    };
    <?php endwhile; ?>
    
    // Registration fees - Default values
    const registrationFees = {
        'WALK_IN': { fee: 500, debit: 'Cash - Main Account', name: 'Walk-in Registration' },
        'INSURANCE': { fee: 0, debit: 'Accounts Receivable - Insurance', name: 'Insurance Registration' },
        'CORPORATE': { fee: 0, debit: 'Accounts Receivable - Corporate', name: 'Corporate Registration' },
        'REFERRAL': { fee: 400, debit: 'Cash - Main Account', name: 'Referral Registration' },
        'ONLINE': { fee: 300, debit: 'Cash - Main Account', name: 'Online Booking' }
    };
    
    // Complete fee structure from your price list
    const feeStructure = {
        consultation: [
            { name: 'First Consultation', fee: 5000, category: 'Treatment' },
            { name: 'Hospital Visit, Daytime', fee: 3000, category: 'Treatment' },
            { name: 'Hospital Visit, Emergency Night Time', fee: 4500, category: 'Treatment' }
        ],
        localAnesthesia: [
            { name: 'Myringoplasty', fee: 7000, category: 'Treatment' },
            { name: 'Cautery of Nose / EAC', fee: 5000, category: 'Treatment' },
            { name: 'Chemical Cautery', fee: 10000, category: 'Treatment' },
            { name: 'EUM (Ear, Nose, Throat Under Microscope)', fee: 6000, category: 'Treatment' },
            { name: 'Drainage of Facial Abscess or I&D Furuncle', fee: 25000, category: 'Surgery' },
            { name: 'Direct Laryngoscopy', fee: 7500, category: 'Investigation' },
            { name: 'Drainage of Septal Abscess or Hematoma', fee: 25000, category: 'Surgery' }
        ],
        investigations: [
            { name: 'Endoscopy - Flexible', fee: 7500, category: 'Investigation' },
            { name: 'Flexible Of Nasopharynx', fee: 7500, category: 'Investigation' },
            { name: 'Flexible Of Laryngopharynx', fee: 5000, category: 'Investigation' },
            { name: 'Foreign Body FB Removal (Ear, Nose)', fee: 6000, category: 'Investigation' },
            { name: 'Nasopharynx Swab', fee: 7000, category: 'Investigation' },
            { name: 'Larynx Video Endoscopy', fee: 5000, category: 'Investigation' },
            { name: 'Injection and Oral Feeding (Neck, Scar)', fee: 5000, category: 'Investigation' },
            { name: 'Insertion of Vent Tube', fee: 2500, category: 'Treatment' },
            { name: 'Needle Aspiration of Hematoma & Biopsy', fee: 5000, category: 'Investigation' },
            { name: 'Polypectomy', fee: 7500, category: 'Surgery' },
            { name: 'Thiersch Meatoplasty & Voice Assessment', fee: 7500, category: 'Investigation' },
            { name: 'Uvulopalatoplasty', fee: 7500, category: 'Surgery' },
            { name: 'Nasal Toilet', fee: 5000, category: 'Treatment' },
            { name: 'Nasal Cautery Abscess I&D', fee: 7500, category: 'Treatment' },
            { name: 'Nasal Packing Postoperative', fee: 2500, category: 'Treatment' },
            { name: 'Punch Biopsy', fee: 5000, category: 'Investigation' },
            { name: 'Simple Nasal Biopsy LA', fee: 5000, category: 'Investigation' },
            { name: 'Paranasal Sinus X-ray', fee: 3000, category: 'Investigation' },
            { name: 'Peritonsillar Abscess Drainage- LA', fee: 25000, category: 'Surgery' },
            { name: 'Peritonsillar Abscess Drainage- LA', fee: 15000, category: 'Surgery' },
            { name: 'Suture Removal / Dressing Ear', fee: 2500, category: 'Treatment' },
            { name: 'Video Otoscopy', fee: 1000, category: 'Investigation' },
            { name: 'Endoscopic Nasal Cauterization', fee: 7500, category: 'Treatment' },
            { name: 'Foreign Body Removal', fee: 5000, category: 'Treatment' },
            { name: 'Eardrops Ofloxacin L&G Function GA', fee: 20000, category: 'Treatment' }
        ],
        hearing: [
            { name: 'Audiometry', fee: 2500, category: 'Investigation' },
            { name: 'Tympanometry', fee: 2500, category: 'Investigation' },
            { name: 'BERA/ABR', fee: 3000, category: 'Investigation' },
            { name: 'Screening Audiometry', fee: 3500, category: 'Investigation' },
            { name: 'Ear Wax (Cerumen) Removal and Fitting', fee: 2500, category: 'Treatment' }
        ],
        surgery: [
            { name: 'Adenoidectomy (AD) - Children', fee: 40000, category: 'Surgery' },
            { name: 'Adenotonsillectomy', fee: 60000, category: 'Surgery' },
            { name: 'Antrostomy - Adult', fee: 80000, category: 'Surgery' },
            { name: 'Tonsillectomy - Children', fee: 50000, category: 'Surgery' },
            { name: 'Tonsillectomy - Adult', fee: 60000, category: 'Surgery' },
            { name: 'Bronchoscopy & Dilatation', fee: 65000, category: 'Surgery' },
            { name: 'Bronchoscopy & Foreign Body, TR Removal', fee: 65000, category: 'Surgery' },
            { name: 'Bronchoscopy & Foreign Body Removal Laryngotrachny', fee: 65000, category: 'Surgery' },
            { name: 'Caudal Septoplasty (Minor Repair Unilateral)', fee: 65000, category: 'Surgery' },
            { name: 'DL Biopsy & Zombie Nasopharyngoscopy', fee: 35000, category: 'Surgery' },
            { name: 'DL Dysphonia - Larynx & Vocal Cords', fee: 115000, category: 'Surgery' },
            { name: 'EUM Polypectomy', fee: 35000, category: 'Surgery' },
            { name: 'Nasal Cautery-GA', fee: 25000, category: 'Surgery' },
            { name: 'IMMTN', fee: 20000, category: 'Surgery' },
            { name: 'Myringoplasty', fee: 100000, category: 'Surgery' },
            { name: 'Myringoplasty & Insertion of T-Tube/ Grommet', fee: 50000, category: 'Surgery' },
            { name: 'Caldwell Luc', fee: 70000, category: 'Surgery' },
            { name: 'Choanal Atresia', fee: 70000, category: 'Surgery' },
            { name: 'Incision of Aural Cholesteatoma', fee: 80000, category: 'Surgery' },
            { name: 'ENT and Head Surgery', fee: 65000, category: 'Surgery' },
            { name: 'Endoscopic DCR', fee: 65000, category: 'Surgery' },
            { name: 'Endoscopic Excision of Nasal Mass', fee: 80000, category: 'Surgery' },
            { name: 'Esophagoscopy with Foreign Body Extraction', fee: 65000, category: 'Surgery' },
            { name: 'Ethmoidectomy', fee: 80000, category: 'Surgery' },
            { name: 'EUA & Biopsy - FNS', fee: 40000, category: 'Surgery' },
            { name: 'EUA & Biopsy (Submucosal)', fee: 40000, category: 'Surgery' },
            { name: 'EUA & Removal of Intranasal Body', fee: 40000, category: 'Surgery' },
            { name: 'EUA & Submucusal Diathermy', fee: 40000, category: 'Surgery' },
            { name: 'Examination Under GA Ears Throat Nose', fee: 40000, category: 'Surgery' },
            { name: 'Examination of Nose', fee: 40000, category: 'Surgery' },
            { name: 'Exploration of Hematoma', fee: 40000, category: 'Surgery' },
            { name: 'Caldwell Luc (Antral Window)', fee: 65000, category: 'Surgery' },
            { name: 'Excision of Adenoids', fee: 60000, category: 'Surgery' },
            { name: 'Excision of Cervical Node-GA', fee: 25000, category: 'Surgery' },
            { name: 'Excision of Laryngeal Mass', fee: 60000, category: 'Surgery' },
            { name: 'Excision of Neck Cyst [Lymph Node] (incomplete)', fee: 40000, category: 'Surgery' },
            { name: 'Excision of Thyroglossal Duct(cyst, Sebrick Procedure', fee: 90000, category: 'Surgery' },
            { name: 'Excision of Tonsils', fee: 60000, category: 'Surgery' },
            { name: 'Excision of Vocal Cord', fee: 60000, category: 'Surgery' },
            { name: 'Excision of Polyp', fee: 60000, category: 'Surgery' },
            { name: 'Microlaryngoscopy Dilatation [excerciation Laryngeal Papilloma', fee: 70000, category: 'Surgery' },
            { name: 'Foreign Body Removal', fee: 40000, category: 'Surgery' },
            { name: 'Frontoethmoidectomy', fee: 145000, category: 'Surgery' },
            { name: 'Functional Endoscopic Sinus Surgery (FESS) - GA', fee: 175000, category: 'Surgery' },
            { name: 'Drainage Of Abscess', fee: 40000, category: 'Surgery' },
            { name: 'Hypophysectomy & Excision Vestibular Swelling', fee: 85000, category: 'Surgery' },
            { name: 'Hypophysectomy & Sphenoidotomy', fee: 85000, category: 'Surgery' },
            { name: 'Intranasal Antrostomy (pharasal drainage Excision of', fee: 65000, category: 'Surgery' },
            { name: 'I & D and Biopsy', fee: 50000, category: 'Surgery' },
            { name: 'Intranasal Ethmoidectomy', fee: 90000, category: 'Surgery' },
            { name: 'Intranasal Ethmoidectomy & Removal Of Antral G.A.', fee: 90000, category: 'Surgery' },
            { name: 'Laryngoplasty Rigid', fee: 18000, category: 'Investigation' },
            { name: 'Laryngeal Reconstruction', fee: 132000, category: 'Surgery' },
            { name: 'Laryngofissure', fee: 145000, category: 'Surgery' },
            { name: 'Laryngectomy & Excision of Parotid Tumor', fee: 120000, category: 'Surgery' },
            { name: 'Vocal Fold Medialization', fee: 75000, category: 'Surgery' },
            { name: 'Laryngeal Biopsy, LA', fee: 25000, category: 'Investigation' },
            { name: 'Laryngoscopy', fee: 5000, category: 'Investigation' },
            { name: 'Mastoidectomy cortical', fee: 90000, category: 'Surgery' },
            { name: 'Mastoidectomy', fee: 120000, category: 'Surgery' },
            { name: 'Mastoidectomy Radical', fee: 115000, category: 'Surgery' },
            { name: 'Medialization Thyroplasty', fee: 125000, category: 'Surgery' },
            { name: 'Manipulation', fee: 40000, category: 'Surgery' },
            { name: 'MMCN', fee: 90000, category: 'Surgery' },
            { name: 'Myringoplasty & Insertion of (Grommet)- GA', fee: 40000, category: 'Surgery' },
            { name: 'Myringotomy (Bilateral) & Insertion of Tube', fee: 40000, category: 'Surgery' },
            { name: 'Myringoplasty', fee: 115000, category: 'Surgery' },
            { name: 'Myringoplasty & Ossicular Reconstruction', fee: 155000, category: 'Surgery' },
            { name: 'Neck dissection-Unilateral(lateral)', fee: 150000, category: 'Surgery' },
            { name: 'Neck dissection-Modified(lateral)', fee: 250000, category: 'Surgery' },
            { name: 'Neck dissection-Radical', fee: 250000, category: 'Surgery' },
            { name: 'Otoplasty', fee: 100000, category: 'Surgery' },
            { name: 'Palatoplasty Ateriofiouraid', fee: 40000, category: 'Surgery' },
            { name: 'Pharyngolaryngectomy with Surgery (FESS)', fee: 180000, category: 'Surgery' },
            { name: 'Perforation Closure- Removal of bone', fee: 100000, category: 'Surgery' },
            { name: 'Reduction of Nasal Fracture, GA', fee: 40000, category: 'Surgery' },
            { name: 'Olfactory Neurectomy', fee: 40000, category: 'Surgery' },
            { name: 'Revision Of Tracheostomy', fee: 20000, category: 'Surgery' },
            { name: 'Removal of Foreign Body-GA', fee: 35000, category: 'Surgery' },
            { name: 'Removal of Nasopharyngeal Mass-GA', fee: 60000, category: 'Surgery' },
            { name: 'Removal of Grommets', fee: 20000, category: 'Surgery' },
            { name: 'Removal of Juvenile Angiofibroma', fee: 145000, category: 'Surgery' },
            { name: 'Removal of Nasal Polyps-GA', fee: 65000, category: 'Surgery' },
            { name: 'Removal of osteofibral teeth', fee: 50000, category: 'Surgery' },
            { name: 'Removal of Parotid-GA', fee: 85000, category: 'Surgery' },
            { name: 'Removal of Nasal Polyp-GA', fee: 65000, category: 'Surgery' },
            { name: 'Rhinoplasty', fee: 145000, category: 'Surgery' },
            { name: 'Nasal EUA', fee: 160000, category: 'Surgery' },
            { name: 'Rhinoplasty', fee: 175000, category: 'Surgery' },
            { name: 'Septo-Rhinoplasty', fee: 175000, category: 'Surgery' },
            { name: 'Septoplasty', fee: 145000, category: 'Surgery' },
            { name: 'Sinus Neurectomy/BPH', fee: 120000, category: 'Surgery' },
            { name: 'Submandibular Gland Excision (Submucous)', fee: 65000, category: 'Surgery' },
            { name: 'Subtotal(perilous/internal Turbinate (Excision)', fee: 70000, category: 'Surgery' },
            { name: 'Thyroplasty', fee: 80000, category: 'Surgery' },
            { name: 'Tongue Tie Release, GA', fee: 20000, category: 'Surgery' },
            { name: 'Tracheostomy', fee: 40000, category: 'Surgery' },
            { name: 'Cricothyroidectomy (lateral)', fee: 40000, category: 'Surgery' },
            { name: 'Uvuloplasty(posterior/Lateral)', fee: 60000, category: 'Surgery' },
            { name: 'Uvulopalatoplasty of Tonque for -GA', fee: 85000, category: 'Surgery' },
            { name: 'Uvulopharyngoplasty & Turbinectomy', fee: 115000, category: 'Surgery' },
            { name: 'Uvulopalatoplasty of Laser', fee: 80000, category: 'Surgery' },
            { name: 'Vocal Cord Lateralization', fee: 90000, category: 'Surgery' },
            { name: 'Operatories for Tracheostomy', fee: 125000, category: 'Surgery' }
        ]
    };
    
    // Registration type selection with fee management
    registrationCards.forEach(card => {
        card.addEventListener('click', function() {
            registrationCards.forEach(c => c.classList.remove('active'));
            this.classList.add('active');
            
            const type = this.getAttribute('data-type');
            const radioInput = this.querySelector('input[type="radio"]');
            radioInput.checked = true;
            currentRegistrationType = type;
            
            // Hide all type-specific fields
            document.querySelectorAll('.type-specific-fields').forEach(field => {
                field.classList.remove('show');
            });
            
            // Reset required fields
            document.getElementById('insuranceProvider').required = false;
            document.querySelector('input[name="insurance_number"]').required = false;
            document.querySelector('input[name="corporate_name"]').required = false;
            document.querySelector('input[name="employee_id"]').required = false;
            emailInput.required = false;
            
            // Show relevant fields
            if (type === 'INSURANCE') {
                insuranceFields.classList.add('show');
                document.getElementById('insuranceProvider').required = true;
                document.querySelector('input[name="insurance_number"]').required = true;
            } else if (type === 'CORPORATE') {
                corporateFields.classList.add('show');
                document.querySelector('input[name="corporate_name"]').required = true;
                document.querySelector('input[name="employee_id"]').required = true;
            } else if (type === 'REFERRAL') {
                referralFields.classList.add('show');
            } else if (type === 'ONLINE') {
                emailInput.required = true;
            }
            
            // Show/Hide registration fee card and set default fees
            if (type === 'WALK_IN' || type === 'ONLINE' || type === 'REFERRAL') {
                registrationFeeCard.style.display = 'block';
                const feeInfo = registrationFees[type];
                document.getElementById('registrationFeeAmount').value = feeInfo.fee.toFixed(2);
                document.getElementById('registrationFeeType').value = feeInfo.name;
                document.getElementById('selectedFeeType').value = feeInfo.name;
            } else {
                registrationFeeCard.style.display = 'none';
            }
            
            // Update accounting preview
            updateAccountingPreview(type);
        });
    });
    
    // Insurance provider change handler - Check for Smart enabled
    insuranceProviderSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        isSmartEnabled = selectedOption.getAttribute('data-smart-enabled') === '1';
        const smartCode = selectedOption.getAttribute('data-smart-code');
        
        // Update hidden field
        document.getElementById('isSmartEnabled').value = isSmartEnabled ? '1' : '0';
        
        if (isSmartEnabled) {
            smartCardSection.style.display = 'block';
            updateSmartStatusIndicator('pending');
        } else {
            smartCardSection.style.display = 'none';
            smartSessionData = null;
            document.getElementById('smartSessionDataInput').value = '';
            document.getElementById('smartSessionDisplay').style.display = 'none';
        }
    });
    
    // Fetch Smart Card Session
    const fetchSmartBtn = document.getElementById('fetchSmartSessionBtn');
    if (fetchSmartBtn) {
        fetchSmartBtn.addEventListener('click', function() {
            const memberNumber = document.getElementById('insuranceNumber').value;
            const patientName = document.getElementById('fullNameInput').value;
            
            if (!memberNumber) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Member Number Required',
                    text: 'Please enter the insurance member number first.'
                });
                return;
            }
            
            const button = this;
            const originalHtml = button.innerHTML;
            button.innerHTML = '<i class="ri-loader-4-line ri-spin me-2"></i>Fetching Smart session...';
            button.disabled = true;
            
            // Call Smart API to fetch pending session
            fetch('smart/smart_handler.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=fetch_pending_session&patient_number=' + encodeURIComponent(memberNumber)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.sessions && data.sessions.length > 0) {
                    smartSessionData = data.sessions[0];
                    displaySmartSessionData(smartSessionData);
                    updateSmartStatusIndicator('active');
                    
                    // Store in hidden field
                    document.getElementById('smartSessionDataInput').value = JSON.stringify(smartSessionData);
                    
                    // Auto-populate fields
                    document.getElementById('insuranceNumber').value = smartSessionData.medicalaid_number || memberNumber;
                    document.getElementById('policyNumber').value = smartSessionData.policy_id || '';
                    
                    // Auto-populate patient name if matches
                    if (smartSessionData.member_name && !document.getElementById('fullNameInput').value) {
                        document.getElementById('fullNameInput').value = smartSessionData.member_name;
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Smart Card Data Retrieved',
                        text: 'Member benefits loaded successfully!',
                        timer: 2000,
                        showConfirmButton: false
                    });
                } else {
                    // NO SESSION FOUND - Show detailed instructions
                    updateSmartStatusIndicator('error');
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Smart Card Not Found',
                        html: `
                            <div class="text-start">
                                <p><strong>No Smart card session found for member: ${memberNumber}</strong></p>
                                
                                <div class="alert alert-warning mt-3">
                                    <h6><i class="ri-alert-line me-2"></i>Required Steps:</h6>
                                    <ol class="mb-0">
                                        <li><strong>Forward the card on SmartLink</strong>
                                            <ul>
                                                <li>Patient must present their Smart card at the SmartLink terminal</li>
                                                <li>Staff must forward the card in SmartLink system</li>
                                                <li>Wait for confirmation that card is forwarded</li>
                                            </ul>
                                        </li>
                                        <li><strong>Then click "Fetch Smart Card Session" again</strong></li>
                                    </ol>
                                </div>
                                
                                <div class="mt-3">
                                    <p><strong>Common Issues:</strong></p>
                                    <ul>
                                        <li>Card not yet forwarded on SmartLink</li>
                                        <li>Wrong member number entered</li>
                                        <li>Card already used for another active visit</li>
                                        <li>SmartLink device offline or not connected</li>
                                    </ul>
                                </div>
                                
                                <div class="alert alert-info mt-3">
                                    <strong>Note:</strong> You can still register the patient manually, but you won't be able to verify benefits or process insurance claims electronically.
                                </div>
                            </div>
                        `,
                        width: 700,
                        confirmButtonText: 'I Understand',
                        confirmButtonColor: '#dc3545',
                        showCancelButton: true,
                        cancelButtonText: 'Register Without Smart',
                        cancelButtonColor: '#6c757d'
                    }).then((result) => {
                        if (result.dismiss === Swal.DismissReason.cancel) {
                            // User chose to register without Smart
                            Swal.fire({
                                icon: 'warning',
                                title: 'Continue Without Smart?',
                                html: `
                                    <p>Registering without Smart card verification means:</p>
                                    <ul class="text-start">
                                        <li>Cannot verify patient benefits</li>
                                        <li>Cannot check available coverage</li>
                                        <li>Cannot submit electronic claims</li>
                                        <li>Manual billing required</li>
                                    </ul>
                                    <p><strong>Are you sure you want to continue?</strong></p>
                                `,
                                showCancelButton: true,
                                confirmButtonText: 'Yes, Continue Anyway',
                                cancelButtonText: 'No, Wait for Smart Card',
                                confirmButtonColor: '#f59e0b'
                            }).then((confirmResult) => {
                                if (confirmResult.isConfirmed) {
                                    // Allow registration without Smart
                                    document.getElementById('isSmartEnabled').value = '0';
                                    smartSessionData = null;
                                    document.getElementById('smartSessionDataInput').value = '';
                                    
                                    Swal.fire({
                                        icon: 'info',
                                        title: 'Proceeding Without Smart',
                                        text: 'Patient will be registered without Smart card verification.',
                                        timer: 2000,
                                        showConfirmButton: false
                                    });
                                }
                            });
                        }
                    });
                }
            })
            .catch(error => {
                updateSmartStatusIndicator('error');
                
                Swal.fire({
                    icon: 'error',
                    title: 'Smart Connection Error',
                    html: `
                        <div class="text-start">
                            <p><strong>Unable to connect to Smart Health Systems</strong></p>
                            
                            <div class="alert alert-danger mt-3">
                                <h6><i class="ri-error-warning-line me-2"></i>Connection Failed</h6>
                                <p class="mb-0">${error.message}</p>
                            </div>
                            
                            <div class="mt-3">
                                <p><strong>Possible Causes:</strong></p>
                                <ul>
                                    <li>Smart API server is down</li>
                                    <li>Internet connection issue</li>
                                    <li>Invalid API credentials in system settings</li>
                                    <li>Network firewall blocking connection</li>
                                </ul>
                            </div>
                            
                            <div class="alert alert-info mt-3">
                                <strong>What to do:</strong><br>
                                1. Check your internet connection<br>
                                2. Verify Smart API settings in System Settings<br>
                                3. Contact IT support if issue persists<br>
                                4. You can register patient manually without Smart verification
                            </div>
                        </div>
                    `,
                    width: 700,
                    confirmButtonText: 'Check System Settings',
                    confirmButtonColor: '#667eea',
                    showCancelButton: true,
                    cancelButtonText: 'Register Without Smart'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Redirect to system settings
                        window.open('system_settings.php#smart', '_blank');
                    } else if (result.dismiss === Swal.DismissReason.cancel) {
                        // Allow manual registration
                        document.getElementById('isSmartEnabled').value = '0';
                        smartSessionData = null;
                    }
                });
                
                console.error('Smart API Error:', error);
            })
            .finally(() => {
                button.innerHTML = originalHtml;
                button.disabled = false;
            });
        });
    }
    
    // Display Smart session data
    function displaySmartSessionData(sessionData) {
        document.getElementById('smartSessionDisplay').style.display = 'block';
        
        // Populate member info
        document.getElementById('smartMemberName').textContent = sessionData.member_name || 'N/A';
        document.getElementById('smartMemberNumber').textContent = sessionData.medicalaid_number || 'N/A';
        document.getElementById('smartSchemeName').textContent = sessionData.medicalaid_scheme_name || 'N/A';
        document.getElementById('smartPolicyId').textContent = sessionData.policy_id || 'N/A';
        document.getElementById('smartSessionId').textContent = sessionData.session_id || 'N/A';
        
        // Display copay info
        if (sessionData.has_copay && sessionData.co_pay_amount > 0) {
            document.getElementById('smartCopay').innerHTML = `<span class="badge bg-warning">KES ${parseFloat(sessionData.co_pay_amount).toFixed(2)}</span>`;
        } else {
            document.getElementById('smartCopay').innerHTML = '<span class="badge bg-success">No Copay</span>';
        }
        
        // Display benefits
        const benefitsDisplay = document.getElementById('smartBenefitsDisplay');
        if (sessionData.benefits && sessionData.benefits.length > 0) {
            let benefitsHtml = '<div class="row">';
            sessionData.benefits.forEach(function(benefit) {
                const badgeClass = benefit.claimable ? 'active' : 'inactive';
                benefitsHtml += `
                    <div class="col-md-6 mb-2">
                        <div class="card">
                            <div class="card-body p-2">
                                <small><strong>${benefit.pool_desc}</strong></small><br>
                                <span class="text-success fw-bold">KES ${parseFloat(benefit.amount).toLocaleString('en-KE', {minimumFractionDigits: 2})}</span>
                                <span class="benefit-badge ${badgeClass} ms-2">${benefit.claimable ? 'Active' : 'Inactive'}</span>
                            </div>
                        </div>
                    </div>
                `;
            });
            benefitsHtml += '</div>';
            benefitsDisplay.innerHTML = benefitsHtml;
        } else {
            benefitsDisplay.innerHTML = '<p class="text-muted">No benefits available</p>';
        }
        
        // Update Smart card section styling
        smartCardSection.classList.add('active');
    }
    
    // Update Smart status indicator
    function updateSmartStatusIndicator(status) {
        const indicator = document.getElementById('smartStatusIndicator');
        indicator.className = 'smart-status-indicator ' + status;
        
        switch(status) {
            case 'pending':
                indicator.innerHTML = '<i class="ri-loader-4-line me-2"></i>Pending Card Forward';
                break;
            case 'active':
                indicator.innerHTML = '<i class="ri-checkbox-circle-line me-2"></i>Card Data Retrieved';
                break;
            case 'error':
                indicator.innerHTML = '<i class="ri-error-warning-line me-2"></i>Card Not Found';
                break;
        }
    }
    
    // Update accounting preview
    function updateAccountingPreview(type) {
        const feeInfo = registrationFees[type];
        
        if (feeInfo.fee > 0) {
            accountingPreview.style.display = 'block';
            document.getElementById('previewFee').textContent = 'KES ' + feeInfo.fee.toFixed(2);
            document.getElementById('previewDebit').textContent = feeInfo.debit;
        } else {
            accountingPreview.style.display = 'block';
            document.getElementById('previewFee').textContent = 'KES 0.00 (Billed Later)';
            document.getElementById('previewDebit').textContent = feeInfo.debit;
        }
    }
    
    // Department selection
    departmentCards.forEach(card => {
        card.addEventListener('click', function() {
            departmentCards.forEach(c => c.classList.remove('active'));
            this.classList.add('active');
            
            const deptId = this.getAttribute('data-dept');
            const radioInput = this.querySelector('input[type="radio"]');
            radioInput.checked = true;
            
            // Update queue info box
            if (departmentData[deptId]) {
                document.getElementById('selectedDeptName').textContent = departmentData[deptId].name;
                document.getElementById('avgServiceTime').textContent = departmentData[deptId].avgTime + ' minutes';
                queueInfoBox.style.display = 'block';
            }
        });
    });
    
    // Priority selection
    priorityOptions.forEach(option => {
        option.addEventListener('click', function() {
            priorityOptions.forEach(o => o.classList.remove('active'));
            this.classList.add('active');
            
            const priority = this.getAttribute('data-priority');
            const radioInput = this.querySelector('input[type="radio"]');
            radioInput.checked = true;
            
            // Update queue info
            document.getElementById('selectedPriority').textContent = 
                priority.charAt(0) + priority.slice(1).toLowerCase();
        });
    });
    
    // Set initial state if form submitted
    <?php if (!empty($_POST['registration_type'])): ?>
    const selectedType = '<?php echo $_POST['registration_type']; ?>';
    const selectedCard = document.querySelector(`[data-type="${selectedType}"]`);
    if (selectedCard) {
        selectedCard.click();
    }
    <?php endif; ?>
    
    <?php if (!empty($_POST['route_to_department'])): ?>
    const selectedDept = '<?php echo $_POST['route_to_department']; ?>';
    const selectedDeptCard = document.querySelector(`[data-dept="${selectedDept}"]`);
    if (selectedDeptCard) {
        selectedDeptCard.click();
    }
    <?php endif; ?>
    
    // Form validation with Smart integration check
    const form = document.getElementById('patientRegistrationForm');
    form.addEventListener('submit', function(e) {
        const registrationType = document.querySelector('input[name="registration_type"]:checked');
        const department = document.querySelector('input[name="route_to_department"]:checked');
        
        if (!registrationType) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: 'Registration Type Required',
                text: 'Please select a registration type.'
            });
            return false;
        }
        
        if (!department) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: 'Department Required',
                text: 'Please select a department to route the patient.'
            });
            return false;
        }
        
        // Type-specific validation
        if (registrationType.value === 'INSURANCE') {
            const provider = document.getElementById('insuranceProvider').value;
            const number = document.querySelector('input[name="insurance_number"]').value;
            
            if (!provider || !number) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Insurance Info Required',
                    text: 'Please provide insurance provider and member number.'
                });
                return false;
            }
            
            // Check if Smart-enabled provider requires Smart session
            if (isSmartEnabled && !smartSessionData) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Smart Card Session Required',
                    html: 'This insurance provider requires Smart card validation.<br><br>Please click "Fetch Smart Card Session" button to retrieve the card data.',
                    confirmButtonText: 'OK, I understand'
                });
                return false;
            }
        }
        
        if (registrationType.value === 'CORPORATE') {
            const corporate = document.querySelector('input[name="corporate_name"]').value;
            const employeeId = document.querySelector('input[name="employee_id"]').value;
            
            if (!corporate || !employeeId) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Corporate Info Required',
                    text: 'Please provide company name and employee ID.'
                });
                return false;
            }
        }
        
        if (registrationType.value === 'ONLINE') {
            const email = emailInput.value;
            
            if (!email) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Email Required',
                    text: 'Email is required for online registration.'
                });
                return false;
            }
        }
        
        // Show loading with Smart integration message
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        let loadingText = '<i class="ri-loader-2-line me-1 spinner-border spinner-border-sm"></i> Registering Patient';
        
        if (isSmartEnabled && smartSessionData) {
            loadingText += ' & Activating Smart Session...';
        } else {
            loadingText += ' & Creating Accounting Entry...';
        }
        
        submitBtn.innerHTML = loadingText;
        submitBtn.disabled = true;
        
        // Reset button after 15 seconds (increased for Smart processing)
        setTimeout(() => {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }, 15000);
    });
    
    // Phone number formatting
    const phoneInputs = document.querySelectorAll('input[type="tel"]');
    phoneInputs.forEach(input => {
        input.addEventListener('input', function() {
            let value = this.value.replace(/\D/g, '');
            
            if (value.startsWith('254')) {
                value = '+' + value;
            } else if (value.length > 0 && !value.startsWith('0')) {
                value = '0' + value;
            }
            
            this.value = value;
        });
    });
    
    // Age validation
    const dobInput = document.querySelector('input[name="date_of_birth"]');
    dobInput.addEventListener('change', function() {
        const dob = new Date(this.value);
        const today = new Date();
        const age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
        
        if (age < 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Invalid Date',
                text: 'Date of birth cannot be in the future.'
            });
            this.value = '';
        } else if (age > 120) {
            Swal.fire({
                icon: 'warning',
                title: 'Invalid Date',
                text: 'Please check the date of birth.'
            });
            this.value = '';
        }
    });
    
    // Fee search functionality
    const feeSearchInput = document.getElementById('feeSearchInput');
    if (feeSearchInput) {
        feeSearchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const feeItems = document.querySelectorAll('.fee-item');
            
            feeItems.forEach(item => {
                const feeName = item.getAttribute('data-name').toLowerCase();
                if (feeName.includes(searchTerm)) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    }
    
    // Handle fee item selection from modal
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('fee-item') || e.target.closest('.fee-item')) {
            const feeItem = e.target.classList.contains('fee-item') ? e.target : e.target.closest('.fee-item');
            const fee = parseFloat(feeItem.getAttribute('data-fee'));
            const name = feeItem.getAttribute('data-name');
            const category = feeItem.getAttribute('data-category');
            
            // Apply fee
            document.getElementById('registrationFeeAmount').value = fee.toFixed(2);
            document.getElementById('registrationFeeType').value = name;
            document.getElementById('selectedFeeType').value = name + ' (' + category + ')';
            
            // Update accounting preview
            document.getElementById('previewFee').textContent = 'KES ' + fee.toFixed(2);
            
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('feeSelectorModal'));
            if (modal) {
                modal.hide();
            }
            
            Swal.fire({
                icon: 'success',
                title: 'Fee Updated',
                text: 'Registration fee set to KES ' + fee.toFixed(2),
                timer: 1500,
                showConfirmButton: false
            });
        }
    });
    
    // Listen for registration fee amount changes
    const feeAmountInput = document.getElementById('registrationFeeAmount');
    if (feeAmountInput) {
        feeAmountInput.addEventListener('change', function() {
            const amount = parseFloat(this.value) || 0;
            document.getElementById('previewFee').textContent = 'KES ' + amount.toFixed(2);
        });
    }
});

// Global functions

// Show fee selector modal
function showFeeSelector() {
    const modal = new bootstrap.Modal(document.getElementById('feeSelectorModal'));
    modal.show();
}

// Apply custom fee
function applyCustomFee() {
    const customName = document.getElementById('customFeeName').value.trim();
    const customAmount = parseFloat(document.getElementById('customFeeAmount').value);
    
    if (!customName) {
        Swal.fire({
            icon: 'warning',
            title: 'Service Name Required',
            text: 'Please enter a service name.'
        });
        return;
    }
    
    if (isNaN(customAmount) || customAmount < 0) {
        Swal.fire({
            icon: 'warning',
            title: 'Invalid Amount',
            text: 'Please enter a valid amount.'
        });
        return;
    }
    
    // Apply custom fee
    document.getElementById('registrationFeeAmount').value = customAmount.toFixed(2);
    document.getElementById('registrationFeeType').value = customName;
    document.getElementById('selectedFeeType').value = customName + ' (Custom)';
    
    // Update accounting preview
    document.getElementById('previewFee').textContent = 'KES ' + customAmount.toFixed(2);
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('feeSelectorModal'));
    if (modal) {
        modal.hide();
    }
    
    // Clear custom inputs
    document.getElementById('customFeeName').value = '';
    document.getElementById('customFeeAmount').value = '';
    
    Swal.fire({
        icon: 'success',
        title: 'Custom Fee Applied',
        text: 'Registration fee set to KES ' + customAmount.toFixed(2),
        timer: 1500,
        showConfirmButton: false
    });
}

// Check SmartLink terminal status
function checkSmartLinkStatus() {
    const button = event.target;
    const originalHtml = button.innerHTML;
    button.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Checking...';
    button.disabled = true;
    
    const resultDiv = document.getElementById('smartLinkStatusResult');
    resultDiv.style.display = 'none';
    
    fetch('smart/smart_handler.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=check_smartlink_status'
    })
    .then(response => response.json())
    .then(data => {
        resultDiv.style.display = 'block';
        
        if (data.success && data.online) {
            resultDiv.innerHTML = `
                <div class="alert alert-success mb-0">
                    <i class="ri-checkbox-circle-line me-2"></i>
                    <strong>SmartLink Online</strong><br>
                    <small>Terminal is connected and ready to forward cards</small>
                    ${data.last_activity ? '<br><small class="text-muted">Last activity: ' + data.last_activity + '</small>' : ''}
                </div>
            `;
        } else {
            resultDiv.innerHTML = `
                <div class="alert alert-danger mb-0">
                    <i class="ri-error-warning-line me-2"></i>
                    <strong>SmartLink Offline</strong><br>
                    <small>${data.message || 'Unable to connect to SmartLink terminal'}</small><br>
                    <small class="text-muted mt-2 d-block">
                        Please ensure:<br>
                        • SmartLink device is powered on<br>
                        • Device is connected to network<br>
                        • SmartLink software is running
                    </small>
                </div>
            `;
        }
        
        button.innerHTML = originalHtml;
        button.disabled = false;
    })
    .catch(error => {
        resultDiv.style.display = 'block';
        resultDiv.innerHTML = `
            <div class="alert alert-warning mb-0">
                <i class="ri-alert-line me-2"></i>
                <strong>Status Check Failed</strong><br>
                <small>${error.message}</small>
            </div>
        `;
        
        button.innerHTML = originalHtml;
        button.disabled = false;
    });
}

// Clear form function
function clearForm() {
    Swal.fire({
        title: 'Clear Form?',
        text: 'This will clear all entered data including Smart card session and selected fees.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, clear it!'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('patientRegistrationForm').reset();
            
            // Reset registration cards
            document.querySelectorAll('.registration-card').forEach(card => {
                card.classList.remove('active');
            });
            
            // Reset department cards
            document.querySelectorAll('.department-card').forEach(card => {
                card.classList.remove('active');
            });
            
            // Reset priority options
            document.querySelectorAll('.priority-option').forEach(option => {
                option.classList.remove('active');
            });
            document.querySelector('.priority-option[data-priority="NORMAL"]').classList.add('active');
            
            // Hide type-specific fields
            document.querySelectorAll('.type-specific-fields').forEach(field => {
                field.classList.remove('show');
            });
            
            // Hide info boxes
            document.getElementById('queueInfoBox').style.display = 'none';
            document.getElementById('accountingPreview').style.display = 'none';
            document.getElementById('registrationFeeCard').style.display = 'none';
            
            // Reset Smart integration
            document.getElementById('smartCardSection').style.display = 'none';
            document.getElementById('smartSessionDisplay').style.display = 'none';
            document.getElementById('smartSessionDataInput').value = '';
            document.getElementById('isSmartEnabled').value = '0';
            
            // Reset fee fields
            document.getElementById('registrationFeeAmount').value = '0.00';
            document.getElementById('registrationFeeType').value = '';
            document.getElementById('selectedFeeType').value = '';
            
            Swal.fire({
                icon: 'success',
                title: 'Form Cleared',
                timer: 1500,
                showConfirmButton: false
            });
        }
    });
}
</script>

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