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

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

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

// Get patient ID from query parameter
$patient_id = isset($_GET['patient_id']) ? (int)$_GET['patient_id'] : 0;

// Fetch patient details if patient_id is provided
$patient = null;
if ($patient_id > 0) {
    $patient_sql = "SELECT p.*, u.full_name, u.phone_primary, u.email,
                           ip.provider_name, ip.provider_id, ip.phone as insurance_phone
                    FROM patients p
                    INNER JOIN users u ON p.user_id = u.user_id
                    LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
                    WHERE p.patient_id = ?";
    $stmt = $conn->prepare($patient_sql);
    $stmt->bind_param('i', $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $patient = $result->fetch_assoc();
}

// Fetch all patients for dropdown
$all_patients_sql = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary,
                            ip.provider_name, p.insurance_provider_id
                     FROM patients p
                     INNER JOIN users u ON p.user_id = u.user_id
                     LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
                     ORDER BY u.full_name";
$all_patients = $conn->query($all_patients_sql);

// Fetch all insurance providers for dropdown
$providers_sql = "SELECT provider_id, provider_name, provider_code FROM insurance_providers WHERE is_active = 1 ORDER BY provider_name";
$providers = $conn->query($providers_sql);

// Fetch doctors for dropdown
$doctors_sql = "SELECT d.doctor_id, u.user_id, u.full_name, d.specialization
                FROM doctors d
                INNER JOIN users u ON d.user_id = u.user_id
                WHERE d.is_active = 1
                ORDER BY u.full_name";
$doctors = $conn->query($doctors_sql);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'create_preauth') {
        try {
            $conn->begin_transaction();

            // Generate pre-authorization number
            $preauth_number_sql = "SELECT GeneratePreauthNumber() as preauth_number";
            $preauth_number = $conn->query($preauth_number_sql)->fetch_assoc()['preauth_number'];

            // Prepare values with defaults for empty fields
            $valid_from = !empty($_POST['valid_from']) ? $_POST['valid_from'] : null;
            $valid_until = !empty($_POST['valid_until']) ? $_POST['valid_until'] : null;
            $follow_up_required = isset($_POST['follow_up_required']) ? 1 : 0;

            // Process insurer-specific form data
            $preauth_form_data = null;
            if (isset($_POST['preauth_data']) && is_array($_POST['preauth_data'])) {
                // Get provider code for reference
                $provider_code_sql = "SELECT provider_code FROM insurance_providers WHERE provider_id = ?";
                $provider_stmt = $conn->prepare($provider_code_sql);
                $provider_stmt->bind_param('i', $_POST['provider_id']);
                $provider_stmt->execute();
                $provider_result = $provider_stmt->get_result();
                $provider_row = $provider_result->fetch_assoc();
                $provider_code = $provider_row ? $provider_row['provider_code'] : '';

                // Build the form data array with provider code
                $form_data = [
                    'provider_code' => $provider_code,
                    'submitted_at' => date('Y-m-d H:i:s')
                ];

                // Clean and add all submitted preauth_data fields
                foreach ($_POST['preauth_data'] as $key => $value) {
                    if (is_array($value)) {
                        // Handle nested arrays (like previous admissions table)
                        $cleaned_array = [];
                        foreach ($value as $idx => $item) {
                            if (is_array($item)) {
                                $cleaned_item = array_filter($item, function($v) {
                                    return $v !== '' && $v !== null;
                                });
                                if (!empty($cleaned_item)) {
                                    $cleaned_array[] = $cleaned_item;
                                }
                            } else {
                                if ($item !== '' && $item !== null) {
                                    $cleaned_array[$idx] = htmlspecialchars($item, ENT_QUOTES, 'UTF-8');
                                }
                            }
                        }
                        if (!empty($cleaned_array)) {
                            $form_data[$key] = $cleaned_array;
                        }
                    } else {
                        // Handle simple values
                        if ($value !== '' && $value !== null) {
                            $form_data[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
                        }
                    }
                }

                $preauth_form_data = json_encode($form_data);
            }

            // Insert main pre-authorization record
            $insert_sql = "INSERT INTO insurance_pre_authorizations (
                preauth_number, patient_id, provider_id, service_type, service_category,
                urgency_level, diagnosis_code, diagnosis_description, clinical_indication,
                treatment_plan, estimated_duration, requested_by, requesting_department,
                estimated_cost, requested_amount, patient_copay, auth_status, priority_status,
                request_date, valid_from, valid_until, follow_up_required, internal_notes,
                created_by, preauth_form_data
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param(
                'siissssssssisdddsssssiiss',
                $preauth_number,
                $_POST['patient_id'],
                $_POST['provider_id'],
                $_POST['service_type'],
                $_POST['service_category'],
                $_POST['urgency_level'],
                $_POST['diagnosis_code'],
                $_POST['diagnosis_description'],
                $_POST['clinical_indication'],
                $_POST['treatment_plan'],
                $_POST['estimated_duration'],
                $_POST['requested_by'],
                $_POST['requesting_department'],
                $_POST['estimated_cost'],
                $_POST['requested_amount'],
                $_POST['patient_copay'],
                $_POST['auth_status'],
                $_POST['priority_status'],
                $_POST['request_date'],
                $valid_from,
                $valid_until,
                $follow_up_required,
                $_POST['internal_notes'],
                $_SESSION['user_id'],
                $preauth_form_data
            );

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

            // Log status history
            $history_sql = "INSERT INTO preauth_status_history (preauth_id, new_status, changed_by, change_reason)
                           VALUES (?, ?, ?, ?)";
            $hist_stmt = $conn->prepare($history_sql);
            $reason = "Pre-authorization created";
            $hist_stmt->bind_param('isis', $preauth_id, $_POST['auth_status'], $_SESSION['user_id'], $reason);
            $hist_stmt->execute();

            $conn->commit();

            $_SESSION['success_message'] = "Pre-authorization {$preauth_number} created successfully!";
            header("Location: view_preauthorization.php?id={$preauth_id}");
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['error_message'] = "Error creating pre-authorization: " . $e->getMessage();
        }
    }
}

// Fetch existing pre-authorizations for the patient
$existing_preauths = null;
if ($patient_id > 0) {
    $preauth_sql = "SELECT pa.*, ip.provider_name, u.full_name as doctor_name
                    FROM insurance_pre_authorizations pa
                    LEFT JOIN insurance_providers ip ON pa.provider_id = ip.provider_id
                    LEFT JOIN users u ON pa.requested_by = u.user_id
                    WHERE pa.patient_id = ?
                    ORDER BY pa.created_at DESC
                    LIMIT 10";
    $stmt = $conn->prepare($preauth_sql);
    $stmt->bind_param('i', $patient_id);
    $stmt->execute();
    $existing_preauths = $stmt->get_result();
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pre-Authorization Request')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet">

    <style>
        .preauth-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }

        .preauth-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }

        .form-section {
            margin-bottom: 2rem;
            padding-bottom: 2rem;
            border-bottom: 2px solid #e2e8f0;
        }

        .form-section:last-child {
            border-bottom: none;
        }

        .form-section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .status-badge {
            display: inline-block;
            padding: 0.35rem 0.75rem;
            border-radius: 6px;
            font-size: 0.8125rem;
            font-weight: 600;
        }

        .status-draft { background: #e0e7ff; color: #3730a3; }
        .status-submitted { background: #dbeafe; color: #1e40af; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-approved { background: #d1fae5; color: #065f46; }
        .status-rejected { background: #fee2e2; color: #991b1b; }

        .patient-info-box {
            background: #f1f5f9;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }

        /* ICD-10 Search Result Styling */
        .icd10-result {
            padding: 0.5rem 0;
        }

        .icd10-result .fw-bold {
            font-size: 0.9rem;
            color: #1e293b;
        }

        .icd10-result .text-muted {
            font-size: 0.8rem;
            display: block;
            margin-top: 0.25rem;
        }

        .icd10-result .badge {
            font-size: 0.7rem;
            padding: 0.15rem 0.4rem;
        }

        /* Select2 Loading State */
        .select2-results__option--loading {
            padding: 0.75rem;
            text-align: center;
            color: #667eea;
        }

        /* Select2 No Results */
        .select2-results__option.select2-results__message {
            padding: 0.75rem;
            text-align: center;
            color: #94a3b8;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Insurance Pre-Authorization Request</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <?php if ($patient): ?>
                                        <li class="breadcrumb-item"><a href="patient_profile.php?id=<?php echo $patient_id; ?>">Patient Profile</a></li>
                                        <?php endif; ?>
                                        <li class="breadcrumb-item active">Pre-Authorization</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Header -->
                    <div class="preauth-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3 class="mb-2">Create Letter of Undertaking</h3>
                                <p class="mb-0">Request insurance pre-authorization for medical services</p>
                            </div>
                            <div>
                                <i class="ri-shield-check-line" style="font-size: 3rem; opacity: 0.3;"></i>
                            </div>
                        </div>
                    </div>

                    <!-- Patient Information (if selected) -->
                    <?php if ($patient): ?>
                    <div class="patient-info-box">
                        <div class="row">
                            <div class="col-md-3">
                                <strong>Patient:</strong> <?php echo htmlspecialchars($patient['full_name']); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Patient Number:</strong> <?php echo htmlspecialchars($patient['patient_number']); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Insurance:</strong> <?php echo htmlspecialchars($patient['provider_name'] ?: 'Not Set'); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Policy #:</strong> <?php echo htmlspecialchars($patient['policy_number'] ?: 'N/A'); ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Pre-Authorization Form -->
                    <form method="POST" id="preauthForm" novalidate>
                        <input type="hidden" name="action" value="create_preauth">

                        <div class="preauth-card">
                            <!-- Patient Selection -->
                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class="ri-user-line"></i> Patient Information
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Patient <span class="text-danger">*</span></label>
                                            <select class="form-select select2-patient" name="patient_id" id="patientSelect" required <?php echo $patient ? 'disabled' : ''; ?>>
                                                <option value="">Select Patient</option>
                                                <?php if ($patient): ?>
                                                    <option value="<?php echo $patient['patient_id']; ?>" selected>
                                                        <?php echo htmlspecialchars($patient['full_name'] . ' - ' . $patient['patient_number']); ?>
                                                    </option>
                                                <?php else: ?>
                                                    <?php 
                                                    $all_patients->data_seek(0);
                                                    while ($pat = $all_patients->fetch_assoc()): 
                                                    ?>
                                                        <option value="<?php echo $pat['patient_id']; ?>"
                                                                data-provider-id="<?php echo $pat['insurance_provider_id']; ?>"
                                                                data-provider-name="<?php echo htmlspecialchars($pat['provider_name'] ?: ''); ?>">
                                                            <?php echo htmlspecialchars($pat['full_name'] . ' - ' . $pat['patient_number']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                <?php endif; ?>
                                            </select>
                                            <?php if ($patient): ?>
                                                <input type="hidden" name="patient_id" value="<?php echo $patient['patient_id']; ?>">
                                            <?php endif; ?>
                                            <div class="invalid-feedback">Please select a patient.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Insurance Provider <span class="text-danger">*</span></label>
                                            <select class="form-select select2-provider" name="provider_id" id="providerSelect" required>
                                                <option value="">Select Insurance Provider</option>
                                                <?php if ($patient && $patient['provider_id']): ?>
                                                    <option value="<?php echo $patient['provider_id']; ?>" selected>
                                                        <?php echo htmlspecialchars($patient['provider_name']); ?>
                                                    </option>
                                                <?php endif; ?>
                                                <?php
                                                $providers->data_seek(0);
                                                while ($provider = $providers->fetch_assoc()):
                                                ?>
                                                    <option value="<?php echo $provider['provider_id']; ?>"
                                                            data-provider-code="<?php echo htmlspecialchars($provider['provider_code']); ?>">
                                                        <?php echo htmlspecialchars($provider['provider_name'] . ' (' . $provider['provider_code'] . ')'); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                            <div class="invalid-feedback">Please select an insurance provider.</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Service Details -->
                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class="ri-service-line"></i> Service Details
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Service Type <span class="text-danger">*</span></label>
                                            <select class="form-select" name="service_type" required>
                                                <option value="">Select Type</option>
                                                <option value="CONSULTATION">Consultation</option>
                                                <option value="PROCEDURE">ENT Procedure</option>
                                                <option value="LAB_TEST">Laboratory Test</option>
                                                <option value="ADMISSION">Hospital Admission</option>
                                                <option value="MULTIPLE">Multiple Services</option>
                                            </select>
                                            <div class="invalid-feedback">Please select a service type.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Service Category</label>
                                            <input type="text" class="form-control" name="service_category" placeholder="e.g., Otology, Rhinology">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Urgency Level <span class="text-danger">*</span></label>
                                            <select class="form-select" name="urgency_level" required>
                                                <option value="ROUTINE">Routine</option>
                                                <option value="URGENT">Urgent</option>
                                                <option value="EMERGENCY">Emergency</option>
                                            </select>
                                            <div class="invalid-feedback">Please select an urgency level.</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Medical Information -->
                            <div class="form-section" id="default-medical-section">
                                <div class="form-section-title">
                                    <i class="ri-heart-pulse-line"></i> Medical Information
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">ICD-10 Diagnosis Code</label>
                                            <select class="form-select select2-diagnosis" name="diagnosis_code" id="diagnosisSelect">
                                                <option value="">Type to search ICD-10 codes...</option>
                                            </select>
                                            <small class="text-muted">Type at least 2 characters to search</small>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Estimated Duration</label>
                                            <input type="text" class="form-control" name="estimated_duration" placeholder="e.g., 1-2 hours, 3 days">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="mb-3">
                                            <label class="form-label">Diagnosis Description <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="diagnosis_description" id="diagnosisDescription" rows="2" required placeholder="Brief description of the diagnosis"></textarea>
                                            <div class="invalid-feedback">Please provide a diagnosis description.</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="mb-3">
                                            <label class="form-label">Clinical Indication / Medical Necessity <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="clinical_indication" rows="3" required placeholder="Explain why this service is medically necessary"></textarea>
                                            <div class="invalid-feedback">Please provide clinical indication.</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="mb-3">
                                            <label class="form-label">Treatment Plan <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="treatment_plan" rows="3" required placeholder="Describe the proposed treatment plan"></textarea>
                                            <div class="invalid-feedback">Please provide a treatment plan.</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Insurer-Specific Fields Container -->
                            <div id="insurer-specific-fields-container">
                                <!-- Dynamic insurer-specific form fields will be loaded here via AJAX -->
                                <div id="insurer-form-loading" class="text-center py-4" style="display: none;">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="mt-2 text-muted">Loading insurer-specific form...</p>
                                </div>
                                <div id="insurer-specific-fields">
                                    <!-- Form fields will be injected here -->
                                </div>
                            </div>

                            <!-- Requesting Doctor -->
                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class="ri-stethoscope-line"></i> Requesting Doctor
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Doctor <span class="text-danger">*</span></label>
                                            <select class="form-select select2-doctor" name="requested_by" id="doctorSelect" required>
                                                <option value="">Select Doctor</option>
                                                <?php 
                                                $doctors->data_seek(0);
                                                while ($doctor = $doctors->fetch_assoc()): 
                                                ?>
                                                    <option value="<?php echo $doctor['user_id']; ?>"
                                                            <?php echo $doctor['user_id'] == $_SESSION['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($doctor['full_name'] . ' - ' . $doctor['specialization']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                            <div class="invalid-feedback">Please select a doctor.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Department</label>
                                            <input type="text" class="form-control" name="requesting_department" value="ENT" readonly>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Financial Information -->
                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class="ri-money-dollar-circle-line"></i> Financial Information
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Estimated Cost (KES) <span class="text-danger">*</span></label>
                                            <input type="number" step="0.01" class="form-control" name="estimated_cost" required>
                                            <div class="invalid-feedback">Please enter estimated cost.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Requested Amount (KES) <span class="text-danger">*</span></label>
                                            <input type="number" step="0.01" class="form-control" name="requested_amount" required>
                                            <div class="invalid-feedback">Please enter requested amount.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Patient Co-pay (KES)</label>
                                            <input type="number" step="0.01" class="form-control" name="patient_copay" value="0.00">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Authorization Details -->
                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class="ri-calendar-line"></i> Authorization Details
                                </div>
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="mb-3">
                                            <label class="form-label">Status <span class="text-danger">*</span></label>
                                            <select class="form-select" name="auth_status" required>
                                                <option value="DRAFT" selected>Draft</option>
                                                <option value="SUBMITTED">Submit Now</option>
                                                <option value="PENDING">Pending</option>
                                            </select>
                                            <div class="invalid-feedback">Please select a status.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="mb-3">
                                            <label class="form-label">Priority</label>
                                            <select class="form-select" name="priority_status">
                                                <option value="STANDARD">Standard</option>
                                                <option value="PRIORITY">Priority</option>
                                                <option value="URGENT">Urgent</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label class="form-label">Request Date <span class="text-danger">*</span></label>
                                            <input type="date" class="form-control" name="request_date" value="<?php echo date('Y-m-d'); ?>" required>
                                            <div class="invalid-feedback">Please select request date.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label class="form-label">Valid From</label>
                                            <input type="date" class="form-control" name="valid_from">
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label class="form-label">Valid Until</label>
                                            <input type="date" class="form-control" name="valid_until">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="follow_up_required" value="1" id="followUpCheck">
                                            <label class="form-check-label" for="followUpCheck">
                                                Follow-up Required
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Internal Notes -->
                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class="ri-file-text-line"></i> Internal Notes
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="mb-3">
                                            <label class="form-label">Internal Notes (Not visible to insurance)</label>
                                            <textarea class="form-control" name="internal_notes" rows="3" placeholder="Add any internal notes for staff"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Actions -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="d-flex gap-2 justify-content-end">
                                        <a href="<?php echo $patient ? 'patient_profile.php?id=' . $patient_id : 'list_preauthorizations.php'; ?>" class="btn btn-secondary">
                                            <i class="ri-close-line me-1"></i> Cancel
                                        </a>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Create Pre-Authorization
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

                    <!-- Existing Pre-Authorizations -->
                    <?php if ($existing_preauths && $existing_preauths->num_rows > 0): ?>
                    <div class="preauth-card">
                        <div class="form-section-title">
                            <i class="ri-history-line"></i> Recent Pre-Authorizations
                        </div>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Pre-Auth #</th>
                                        <th>Date</th>
                                        <th>Provider</th>
                                        <th>Service</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($preauth = $existing_preauths->fetch_assoc()): ?>
                                    <tr>
                                        <td><strong><?php echo htmlspecialchars($preauth['preauth_number']); ?></strong></td>
                                        <td><?php echo date('d M Y', strtotime($preauth['request_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($preauth['provider_name']); ?></td>
                                        <td><?php echo ucfirst(str_replace('_', ' ', strtolower($preauth['service_type']))); ?></td>
                                        <td>KES <?php echo number_format($preauth['requested_amount'],2); ?></td>
                                        <td>
                                            <span class="status-badge status-<?php echo strtolower($preauth['auth_status']); ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($preauth['auth_status']))); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="view_preauthorization.php?id=<?php echo $preauth['preauth_id']; ?>" class="btn btn-sm btn-info">
                                                <i class="ri-eye-line"></i> View
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        $(document).ready(function() {
            
            // ============================================
            // INITIALIZE SELECT2 WITH BOOTSTRAP 5 THEME
            // ============================================
            
            // Common configuration for all Select2 instances
            const select2DefaultConfig = {
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: function() {
                    return $(this).data('placeholder') || 'Select an option';
                },
                allowClear: true,
                minimumResultsForSearch: 5,
                language: {
                    noResults: function() {
                        return "No results found";
                    }
                }
            };
            
            // Initialize Patient Select2
            $('#patientSelect').select2({
                ...select2DefaultConfig,
                placeholder: 'Select Patient',
                templateResult: formatPatientResult,
                templateSelection: formatPatientSelection
            });
            
            // Initialize Insurance Provider Select2
            $('#providerSelect').select2({
                ...select2DefaultConfig,
                placeholder: 'Select Insurance Provider'
            });
            
            // Initialize Doctor Select2
            $('#doctorSelect').select2({
                ...select2DefaultConfig,
                placeholder: 'Select Doctor'
            });
            
            // ============================================
            // ICD-10 SELECT2 WITH AJAX INITIALIZATION
            // ============================================
            
            // Initialize ICD-10 Select2 with AJAX
            $('#diagnosisSelect').select2({
                theme: 'bootstrap-5',
                placeholder: 'Type to search ICD-10 codes...',
                allowClear: true,
                minimumInputLength: 2,
                ajax: {
                    url: 'ajax/search_icd10_codes.php',
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term,
                            page: params.page || 1
                        };
                    },
                    processResults: function(data) {
                        if (data.error) {
                            console.error('ICD-10 Search Error:', data.error);
                            return { results: [] };
                        }
                        return {
                            results: data.results,
                            pagination: data.pagination
                        };
                    },
                    cache: true
                },
                templateResult: formatICD10Result,
                templateSelection: formatICD10Selection
            });

            // Auto-populate diagnosis description when ICD-10 code is selected
            $('#diagnosisSelect').on('select2:select', function(e) {
                const data = e.params.data;
                
                // Auto-fill diagnosis description if empty
                const descriptionField = $('#diagnosisDescription');
                if (descriptionField.length && !descriptionField.val()) {
                    // Use full description if available, otherwise use short description
                    const description = data.full_description || data.description;
                    if (description) {
                        descriptionField.val(description);
                    }
                }
                
                // Show success notification
                showToast('success', 'ICD-10 code selected: ' + data.code);
            });

            // Format ICD-10 results in dropdown
            function formatICD10Result(data) {
                if (data.loading) {
                    return data.text;
                }

                // If data doesn't have code property, return simple text
                if (!data.code) {
                    return data.text;
                }

                // Build badges
                let badges = '';
                if (data.commonly_used == 1 || data.commonly_used === true) {
                    badges += '<span class="badge bg-primary-subtle text-primary ms-2" style="font-size: 0.7rem;">Common</span>';
                }
                if (data.is_ent_related == 1 || data.is_ent_related === true) {
                    badges += '<span class="badge bg-success-subtle text-success ms-2" style="font-size: 0.7rem;">ENT</span>';
                }

                // Build category text
                let categoryText = '';
                if (data.category) {
                    categoryText = `<small class="text-muted d-block mt-1" style="font-size: 0.8rem;">${escapeHtml(data.category)}</small>`;
                }

                // Create formatted result
                let $result = $(`
                    <div class="icd10-result py-2">
                        <div class="fw-bold" style="font-size: 0.9rem; color: #1e293b;">
                            ${escapeHtml(data.code)} - ${escapeHtml(data.description)}${badges}
                        </div>
                        ${categoryText}
                    </div>
                `);
                
                return $result;
            }

            // Format selected ICD-10 code (what shows in the input when selected)
            function formatICD10Selection(data) {
                if (data.code && data.description) {
                    return data.code + ' - ' + data.description;
                }
                return data.text;
            }

            // Helper function to escape HTML
            function escapeHtml(text) {
                if (!text) return '';
                const map = {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                };
                return text.replace(/[&<>"']/g, function(m) { return map[m]; });
            }
            
            // ============================================
            // CUSTOM FORMATTERS (OPTIONAL)
            // ============================================
            
            function formatPatientResult(patient) {
                if (!patient.id) {
                    return patient.text;
                }
                return $('<span>' + patient.text + '</span>');
            }
            
            function formatPatientSelection(patient) {
                return patient.text || patient.id;
            }
            
            // ============================================
            // AUTO-POPULATE INSURANCE ON PATIENT SELECT
            // ============================================

            $('#patientSelect').on('select2:select', function(e) {
                const selectedOption = $(this).find('option:selected');
                const providerId = selectedOption.data('provider-id');
                const providerName = selectedOption.data('provider-name');

                if (providerId && providerId !== '') {
                    // Set and trigger change on provider select
                    $('#providerSelect').val(providerId).trigger('change');

                    // Optional: Show notification
                    showToast('info', 'Insurance provider auto-populated');
                } else {
                    // Clear provider selection if patient has no insurance
                    $('#providerSelect').val('').trigger('change');
                }
            });

            // ============================================
            // LOAD INSURER-SPECIFIC FORM FIELDS
            // ============================================

            $('#providerSelect').on('change', function() {
                loadInsurerSpecificForm();
            });

            function loadInsurerSpecificForm() {
                const providerId = $('#providerSelect').val();
                const patientId = $('#patientSelect').val();
                const container = $('#insurer-specific-fields');
                const loadingIndicator = $('#insurer-form-loading');

                // Clear previous form
                container.html('');

                if (!providerId) {
                    return;
                }

                // Show loading indicator
                loadingIndicator.show();

                // Make AJAX request to get form
                $.ajax({
                    url: 'ajax/get_preauth_form.php',
                    type: 'POST',
                    data: {
                        provider_id: providerId,
                        patient_id: patientId || 0
                    },
                    dataType: 'json',
                    success: function(response) {
                        loadingIndicator.hide();

                        if (response.success && response.html) {
                            // Inject the form HTML
                            container.html(response.html);

                            // Show notification about form type
                            if (response.form_type === 'custom') {
                                showToast('success', response.provider_name + ' form loaded');
                                
                                // Hide the default medical info section as it's redundant with the custom form
                                $('#default-medical-section').hide();
                                // Remove required attribute from hidden fields to allow submission
                                $('#default-medical-section textarea').prop('required', false);
                            } else {
                                // Show default section if no custom form
                                $('#default-medical-section').show();
                                $('#default-medical-section textarea').prop('required', true);
                            }

                            // Re-initialize any dynamic components (Select2, datepickers, etc.)
                            initializeDynamicFormComponents();
                        } else if (response.success && !response.html) {
                            // No specific form for this provider
                            container.html('');
                            // Show default section
                            $('#default-medical-section').show();
                            $('#default-medical-section textarea').prop('required', true);
                        }
                    },
                    error: function(xhr, status, error) {
                        loadingIndicator.hide();
                        console.error('Error loading form:', error);
                        showToast('error', 'Failed to load insurer form');
                    }
                });
            }

            function initializeDynamicFormComponents() {
                // Re-initialize Select2 dropdowns in the dynamic form
                $('#insurer-specific-fields select.select2').each(function() {
                    if (!$(this).data('select2')) {
                        $(this).select2({
                            theme: 'bootstrap-5',
                            width: '100%'
                        });
                    }
                });

                // Initialize any date pickers if needed
                $('#insurer-specific-fields input[type="date"]').each(function() {
                    // Default browser date picker is already functional
                });

                // Initialize tooltips
                var tooltipTriggerList = [].slice.call(document.querySelectorAll('#insurer-specific-fields [data-bs-toggle="tooltip"]'));
                var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                    return new bootstrap.Tooltip(tooltipTriggerEl);
                });
            }

            // Load form on page load if provider is already selected
            if ($('#providerSelect').val()) {
                loadInsurerSpecificForm();
            }
            
            // ============================================
            // AUTO-CALCULATE REQUESTED AMOUNT
            // ============================================
            
            $('input[name="estimated_cost"]').on('input', function() {
                const estimatedCost = parseFloat($(this).val()) || 0;
                $('input[name="requested_amount"]').val(estimatedCost.toFixed(2));
            });
            
            // ============================================
            // FORM VALIDATION
            // ============================================
            
            // Bootstrap form validation
            const form = document.getElementById('preauthForm');
            
            form.addEventListener('submit', function(event) {
                event.preventDefault();
                event.stopPropagation();
                
                // Check if form is valid
                if (!form.checkValidity()) {
                    form.classList.add('was-validated');
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please fill in all required fields correctly',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#dc3545'
                    });
                    
                    return false;
                }
                
                // Validate Select2 fields manually
                const requiredSelects = [
                    { id: '#patientSelect', name: 'Patient', disabled: <?php echo $patient ? 'true' : 'false'; ?> },
                    { id: '#providerSelect', name: 'Insurance Provider', disabled: false },
                    { id: '#doctorSelect', name: 'Doctor', disabled: false }
                ];
                
                for (let field of requiredSelects) {
                    if (!field.disabled && !$(field.id).val()) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Required Field',
                            text: `Please select a ${field.name}`,
                            confirmButtonText: 'OK',
                            confirmButtonColor: '#dc3545'
                        });
                        
                        $(field.id).select2('open');
                        return false;
                    }
                }
                
                // Custom validation: Requested amount vs Estimated cost
                const estimatedCost = parseFloat($('input[name="estimated_cost"]').val()) || 0;
                const requestedAmount = parseFloat($('input[name="requested_amount"]').val()) || 0;
                
                if (requestedAmount > estimatedCost) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Amount',
                        text: 'Requested amount cannot exceed estimated cost',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ffc107'
                    });
                    return false;
                }
                
                if (estimatedCost <= 0 || requestedAmount <= 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Amount',
                        text: 'Please enter valid amounts greater than zero',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ffc107'
                    });
                    return false;
                }
                
                // All validations passed - show loading and submit
                Swal.fire({
                    title: 'Creating Pre-Authorization...',
                    text: 'Please wait while we process your request',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    allowEnterKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // Submit the form
                form.submit();
            });
            
            // ============================================
            // UTILITY FUNCTIONS
            // ============================================
            
            function showToast(icon, message) {
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true,
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer);
                        toast.addEventListener('mouseleave', Swal.resumeTimer);
                    }
                });
                
                Toast.fire({
                    icon: icon,
                    title: message
                });
            }
            
            // ============================================
            // CURRENCY FORMATTING
            // ============================================
            
            $('input[name="estimated_cost"], input[name="requested_amount"], input[name="patient_copay"]').on('blur', function() {
                const value = parseFloat($(this).val()) || 0;
                $(this).val(value.toFixed(2));
            });
            
            // ============================================
            // DATE VALIDATION
            // ============================================
            
            $('input[name="valid_from"], input[name="valid_until"]').on('change', function() {
                const validFrom = $('input[name="valid_from"]').val();
                const validUntil = $('input[name="valid_until"]').val();
                
                if (validFrom && validUntil && validFrom > validUntil) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Date Range',
                        text: 'Valid Until date must be after Valid From date',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ffc107'
                    });
                    $('input[name="valid_until"]').val('');
                }
            });
            
            // ============================================
            // SELECT2 EVENT HANDLERS
            // ============================================
            
            // Handle Select2 opening
            $('.select2-patient, .select2-provider, .select2-diagnosis, .select2-doctor').on('select2:opening', function(e) {
                // Add any pre-opening logic here
                console.log('Select2 opening:', $(this).attr('id'));
            });
            
            // Handle Select2 selection
            $('.select2-patient, .select2-provider, .select2-diagnosis, .select2-doctor').on('select2:select', function(e) {
                console.log('Selected:', e.params.data);
                
                // Remove is-invalid class on selection
                $(this).removeClass('is-invalid');
            });
            
            // Handle Select2 clearing
            $('.select2-patient, .select2-provider, .select2-diagnosis, .select2-doctor').on('select2:clear', function(e) {
                console.log('Cleared:', $(this).attr('id'));
            });
            
            // ============================================
            // MODAL/TAB SUPPORT
            // ============================================
            
            // Reinitialize Select2 when shown in modals
            $('.modal').on('shown.bs.modal', function() {
                $(this).find('.select2-patient, .select2-provider, .select2-diagnosis, .select2-doctor').each(function() {
                    if (!$(this).data('select2')) {
                        $(this).select2(select2DefaultConfig);
                    }
                });
            });
            
            // Reinitialize Select2 when tab is shown
            $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function() {
                $('.select2-patient, .select2-provider, .select2-diagnosis, .select2-doctor').each(function() {
                    $(this).select2('destroy').select2(select2DefaultConfig);
                });
            });
            
            // ============================================
            // RESPONSIVE HANDLING
            // ============================================
            
            let resizeTimer;
            $(window).on('resize', function() {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function() {
                    // Recalculate Select2 widths on resize
                    $('.select2-patient, .select2-provider, .select2-diagnosis, .select2-doctor').each(function() {
                        $(this).select2('destroy').select2(select2DefaultConfig);
                    });
                }, 250);
            });
            
            // ============================================
            // KEYBOARD SHORTCUTS
            // ============================================
            
            // Ctrl+S to submit form
            $(document).on('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                    e.preventDefault();
                    $('#preauthForm').submit();
                }
            });
            
            // ============================================
            // DISPLAY SUCCESS/ERROR MESSAGES
            // ============================================
            
            <?php if (isset($_SESSION['success_message'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo addslashes($_SESSION['success_message']); ?>',
                timer: 3000,
                timerProgressBar: true,
                showConfirmButton: false
            });
            <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['error_message'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: '<?php echo addslashes($_SESSION['error_message']); ?>',
                showConfirmButton: true,
                confirmButtonText: 'OK',
                confirmButtonColor: '#dc3545'
            });
            <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>
            
            // ============================================
            // PREVENT ACCIDENTAL NAVIGATION
            // ============================================
            
            let formChanged = false;
            
            $('#preauthForm input, #preauthForm select, #preauthForm textarea').on('change', function() {
                formChanged = true;
            });
            
            $(window).on('beforeunload', function(e) {
                if (formChanged) {
                    const message = 'You have unsaved changes. Are you sure you want to leave?';
                    e.returnValue = message;
                    return message;
                }
            });
            
            $('#preauthForm').on('submit', function() {
                formChanged = false;
            });
            
            // ============================================
            // AUTO-SAVE DRAFT (OPTIONAL)
            // ============================================
            
            function saveDraft() {
                const formData = {
                    patient_id: $('#patientSelect').val(),
                    provider_id: $('#providerSelect').val(),
                    service_type: $('select[name="service_type"]').val(),
                    diagnosis_code: $('#diagnosisSelect').val(),
                    diagnosis_description: $('#diagnosisDescription').val(),
                    clinical_indication: $('textarea[name="clinical_indication"]').val(),
                    treatment_plan: $('textarea[name="treatment_plan"]').val(),
                    estimated_cost: $('input[name="estimated_cost"]').val(),
                    requested_amount: $('input[name="requested_amount"]').val()
                };
                
                // Save to localStorage
                localStorage.setItem('preauth_draft', JSON.stringify(formData));
                console.log('Draft saved');
            }
            
            function loadDraft() {
                const draft = localStorage.getItem('preauth_draft');
                if (draft) {
                    const formData = JSON.parse(draft);
                    
                    Swal.fire({
                        title: 'Load Draft?',
                        text: 'A saved draft was found. Would you like to load it?',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, load it',
                        cancelButtonText: 'No, discard',
                        confirmButtonColor: '#0d6efd',
                        cancelButtonColor: '#6c757d'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Load draft data
                            if (formData.patient_id) $('#patientSelect').val(formData.patient_id).trigger('change');
                            if (formData.provider_id) $('#providerSelect').val(formData.provider_id).trigger('change');
                            if (formData.service_type) $('select[name="service_type"]').val(formData.service_type);
                            if (formData.diagnosis_code) {
                                // Create option and select it for Select2
                                const newOption = new Option(formData.diagnosis_code, formData.diagnosis_code, true, true);
                                $('#diagnosisSelect').append(newOption).trigger('change');
                            }
                            if (formData.diagnosis_description) $('#diagnosisDescription').val(formData.diagnosis_description);
                            if (formData.clinical_indication) $('textarea[name="clinical_indication"]').val(formData.clinical_indication);
                            if (formData.treatment_plan) $('textarea[name="treatment_plan"]').val(formData.treatment_plan);
                            if (formData.estimated_cost) $('input[name="estimated_cost"]').val(formData.estimated_cost);
                            if (formData.requested_amount) $('input[name="requested_amount"]').val(formData.requested_amount);
                            
                            showToast('success', 'Draft loaded successfully');
                        } else {
                            localStorage.removeItem('preauth_draft');
                        }
                    });
                }
            }
            
            // Check for draft on page load (only if not editing existing)
            <?php if (!$patient_id): ?>
            setTimeout(loadDraft, 500);
            <?php endif; ?>
            
            // Auto-save every 30 seconds
            setInterval(function() {
                if (formChanged) {
                    saveDraft();
                }
            }, 30000);
            
            // Clear draft on successful submission
            $('#preauthForm').on('submit', function() {
                localStorage.removeItem('preauth_draft');
            });
            
            // ============================================
            // CONSOLE LOG FOR DEBUGGING
            // ============================================
            
            console.log('Pre-Authorization Form Initialized');
            console.log('Select2 Theme: bootstrap-5');
            console.log('ICD-10 AJAX Search: Enabled');
            console.log('Patient preselected:', <?php echo $patient_id ? 'true' : 'false'; ?>);
            
        });
    </script>
</body>
</html>