<?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', 'RECEPTIONIST', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    
    try {
        // Validate required fields
        $patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;
        $provider_id = isset($_POST['provider_id']) ? (int)$_POST['provider_id'] : 0;
        $visit_id = isset($_POST['visit_id']) ? (int)$_POST['visit_id'] : null;
        $claim_date = $_POST['claim_date'];
        $service_date = $_POST['service_date'];
        $claim_amount = (float)$_POST['claim_amount'];
        $diagnosis_code = trim($_POST['diagnosis_code']);
        $treatment_description = trim($_POST['treatment_description']);
        
        if (!$patient_id || !$provider_id || !$claim_date || !$service_date || $claim_amount <= 0) {
            throw new Exception('Please fill all required fields');
        }
        
        // Verify patient has insurance with this provider
        $verify_sql = "SELECT insurance_provider_id FROM patients WHERE patient_id = ?";
        $stmt = $conn->prepare($verify_sql);
        $stmt->bind_param('i', $patient_id);
        $stmt->execute();
        $patient_provider = $stmt->get_result()->fetch_assoc();
        
        if ($patient_provider['insurance_provider_id'] != $provider_id) {
            throw new Exception('Patient insurance does not match selected provider');
        }
        
        // Generate claim number using function
        $claim_number_sql = "SELECT GenerateClaimNumber() as claim_number";
        $claim_number = $conn->query($claim_number_sql)->fetch_assoc()['claim_number'];
        
        // Prepare claim items if any
        $claim_items = [];
        if (isset($_POST['item_description']) && is_array($_POST['item_description'])) {
            for ($i = 0; $i < count($_POST['item_description']); $i++) {
                if (!empty($_POST['item_description'][$i])) {
                    $claim_items[] = [
                        'description' => $_POST['item_description'][$i],
                        'quantity' => (int)$_POST['item_quantity'][$i],
                        'unit_price' => (float)$_POST['item_price'][$i],
                        'total' => (float)$_POST['item_total'][$i]
                    ];
                }
            }
        }
        
        $claim_items_json = !empty($claim_items) ? json_encode($claim_items) : null;
        
        // Insert claim
        $insert_sql = "INSERT INTO insurance_claims (
                        claim_number, patient_id, visit_id, provider_id,
                        claim_date, service_date, claim_amount,
                        diagnosis_code, treatment_description, claim_items,
                        claim_status, notes, created_by, created_at
                      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', ?, ?, NOW())";
        
        $stmt = $conn->prepare($insert_sql);
        $notes = trim($_POST['notes']);
        $stmt->bind_param('siiissdssssi',
            $claim_number, $patient_id, $visit_id, $provider_id,
            $claim_date, $service_date, $claim_amount,
            $diagnosis_code, $treatment_description, $claim_items_json,
            $notes, $user_id
        );
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to submit claim');
        }
        
        $claim_id = $conn->insert_id();
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                   VALUES (?, 'CREATE', 'INSURANCE_CLAIMS', ?, 'CLAIM', ?, NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $log_stmt->bind_param('iis', $user_id, $claim_id, $ip_address);
        $log_stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = 'Insurance claim submitted successfully';
        header('Location: view_claim.php?id=' . $claim_id);
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Submit Insurance Claim')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/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" />
    
    <style>
        :root {
            --primary-color: #3b82f6;
            --primary-dark: #2563eb;
            --success-color: #10b981;
            --danger-color: #ef4444;
            --warning-color: #f59e0b;
            --info-color: #06b6d4;
            --gray-50: #f9fafb;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-300: #d1d5db;
            --gray-600: #4b5563;
            --gray-700: #374151;
            --gray-900: #111827;
        }

        body {
            background: var(--gray-50);
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
        }

        .page-content {
            padding: 2rem 0;
        }

        /* Modern Page Header */
        .page-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            border-radius: 16px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .page-header h1 {
            color: white;
            font-size: 1.875rem;
            font-weight: 700;
            margin: 0 0 0.5rem 0;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .page-header p {
            color: rgba(255, 255, 255, 0.9);
            margin: 0;
            font-size: 0.95rem;
        }

        /* Modern Form Sections */
        .form-section {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            margin-bottom: 1.5rem;
            border: 1px solid var(--gray-200);
            transition: all 0.3s ease;
        }

        .form-section:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .section-header {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--gray-100);
        }

        .section-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.25rem;
        }

        .section-header h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: var(--gray-900);
            margin: 0;
            flex: 1;
        }

        /* Modern Form Inputs */
        .form-label {
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            display: block;
        }

        .required::after {
            content: '*';
            color: var(--danger-color);
            margin-left: 0.25rem;
        }

        .form-control, .form-select {
            border: 2px solid var(--gray-200);
            border-radius: 8px;
            padding: 0.625rem 0.875rem;
            font-size: 0.9375rem;
            transition: all 0.2s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }

        .form-text {
            font-size: 0.8125rem;
            color: var(--gray-600);
            margin-top: 0.25rem;
        }

        /* Patient Info Card */
        .patient-info-card {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-radius: 12px;
            padding: 1.5rem;
            border-left: 4px solid var(--info-color);
            margin-top: 1rem;
        }

        .patient-info-card h6 {
            color: var(--gray-900);
            font-weight: 600;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }

        .info-item small {
            display: block;
            color: var(--gray-600);
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.25rem;
        }

        .info-item div {
            color: var(--gray-900);
            font-weight: 500;
            font-size: 0.9375rem;
        }

        /* Modern Table */
        .claim-items-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin-top: 1rem;
        }

        .claim-items-table thead {
            background: var(--gray-50);
        }

        .claim-items-table th {
            padding: 0.875rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.8125rem;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 2px solid var(--gray-200);
        }

        .claim-items-table td {
            padding: 0.75rem;
            border-bottom: 1px solid var(--gray-200);
        }

        .claim-items-table tbody tr:last-child td {
            border-bottom: none;
        }

        .claim-items-table tbody tr:hover {
            background: var(--gray-50);
        }

        .claim-items-table input {
            border: 2px solid var(--gray-200);
            border-radius: 6px;
            padding: 0.5rem;
            font-size: 0.875rem;
            width: 100%;
        }

        .claim-items-table input:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        /* Modern Buttons */
        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            font-size: 0.9375rem;
            transition: all 0.2s ease;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, var(--success-color), #059669);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
        }

        .btn-secondary {
            background: var(--gray-200);
            color: var(--gray-700);
        }

        .btn-secondary:hover {
            background: var(--gray-300);
        }

        .btn-outline-secondary {
            background: transparent;
            border: 2px solid var(--gray-300);
            color: var(--gray-700);
        }

        .btn-outline-secondary:hover {
            background: var(--gray-100);
        }

        .btn-sm {
            padding: 0.5rem 1rem;
            font-size: 0.875rem;
        }

        .btn-remove-item {
            background: #fee2e2;
            color: #991b1b;
            border: none;
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }

        .btn-remove-item:hover {
            background: #fecaca;
            transform: scale(1.05);
        }

        /* Alert Styles */
        .alert-custom {
            padding: 1rem 1.25rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            border-left: 4px solid;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border-color: var(--danger-color);
        }

        /* Select2 Customization */
        .select2-container--default .select2-selection--single {
            height: 42px;
            border: 2px solid var(--gray-200);
            border-radius: 8px;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 38px;
            padding-left: 0.875rem;
            color: var(--gray-900);
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 38px;
        }

        .select2-container--default.select2-container--focus .select2-selection--single {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .select2-dropdown {
            border: 2px solid var(--primary-color);
            border-radius: 8px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .select2-results__option {
            padding: 0.75rem 1rem;
        }

        .select2-results__option--highlighted {
            background: var(--primary-color) !important;
        }

        /* Custom Select2 Results Styling */
        .select2-patient-result {
            padding: 0.25rem 0;
        }
        
        .select2-patient-result .patient-name {
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 0.25rem;
        }
        
        .select2-patient-result .patient-details {
            font-size: 0.8125rem;
        }
        
        .select2-patient-result .badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }
        
        /* ICD-10 Select2 styling */
        .select2-icd10-result {
            padding: 0.5rem 0;
        }
        
        .select2-icd10-result .icd10-code {
            font-weight: 700;
            color: #1e40af;
            font-family: monospace;
            margin-right: 0.5rem;
            background: #dbeafe;
            padding: 0.125rem 0.375rem;
            border-radius: 4px;
        }
        
        .select2-icd10-result .icd10-desc {
            color: var(--gray-900);
        }
        
        .select2-icd10-result .badge-sm {
            font-size: 0.65rem;
            padding: 0.15rem 0.4rem;
        }

        .select2-icd10-result .category-text {
            display: block;
            color: var(--gray-600);
            font-size: 0.75rem;
            margin-top: 0.25rem;
        }

        /* Action Bar */
        .action-bar {
            display: flex;
            gap: 0.75rem;
            flex-wrap: wrap;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .page-header {
                padding: 1.5rem;
            }

            .page-header h1 {
                font-size: 1.5rem;
            }

            .form-section {
                padding: 1.25rem;
            }

            .info-grid {
                grid-template-columns: 1fr;
            }

            .action-bar {
                flex-direction: column;
            }

            .action-bar .btn {
                width: 100%;
                justify-content: center;
            }
        }

        /* Loading State */
        .border-success {
            border-color: var(--success-color) !important;
            transition: border-color 0.3s ease;
        }
        
        /* Animation for new rows */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-10px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Modern Page Header -->
                    <div class="page-header">
                        <h1>
                            <i class="ri-health-book-line"></i>
                            Submit Insurance Claim
                        </h1>
                        <p>Create and submit a new insurance claim for patient services and treatments</p>
                    </div>

                    <?php if (isset($error_message)): ?>
                    <div class="alert-custom alert-danger">
                        <i class="ri-error-warning-line" style="font-size: 1.5rem;"></i>
                        <div>
                            <strong>Error:</strong> <?php echo htmlspecialchars($error_message); ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <form method="POST" id="claimForm">
                        <!-- Patient & Provider Information -->
                        <div class="form-section">
                            <div class="section-header">
                                <div class="section-icon">
                                    <i class="ri-user-heart-line"></i>
                                </div>
                                <h5>Patient & Insurance Provider</h5>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Select Patient</label>
                                    <select class="form-select" name="patient_id" id="patientSelect" required>
                                        <option value="">Search for patient...</option>
                                    </select>
                                    <small class="form-text">Type patient name, number, or phone to search</small>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Insurance Provider</label>
                                    <select class="form-select" name="provider_id" id="providerSelect" required>
                                        <option value="">Select Provider</option>
                                        <?php 
                                        $providers_result->data_seek(0);
                                        while ($provider = $providers_result->fetch_assoc()): 
                                        ?>
                                        <option value="<?php echo $provider['provider_id']; ?>" 
                                                data-coverage="<?php echo $provider['coverage_percentage']; ?>">
                                            <?php echo htmlspecialchars($provider['provider_name']); ?> 
                                            (<?php echo $provider['coverage_percentage']; ?>% coverage)
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div id="patientInfo" class="patient-info-card" style="display: none;">
                                <h6>
                                    <i class="ri-information-line"></i>
                                    Patient Information
                                </h6>
                                <div class="info-grid">
                                    <div class="info-item">
                                        <small>Full Name</small>
                                        <div id="patientName">-</div>
                                    </div>
                                    <div class="info-item">
                                        <small>Patient Number</small>
                                        <div id="patientNumber">-</div>
                                    </div>
                                    <div class="info-item">
                                        <small>Insurance Number</small>
                                        <div id="insuranceNumber">-</div>
                                    </div>
                                    <div class="info-item">
                                        <small>Insurance Provider</small>
                                        <div id="insuranceProvider">-</div>
                                    </div>
                                    <div class="info-item">
                                        <small>Phone Number</small>
                                        <div id="patientPhone">-</div>
                                    </div>
                                    <div class="info-item">
                                        <small>Registration Type</small>
                                        <div id="registrationType">-</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Visit & Service Information -->
                        <div class="form-section">
                            <div class="section-header">
                                <div class="section-icon">
                                    <i class="ri-hospital-line"></i>
                                </div>
                                <h5>Visit & Service Information</h5>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Related Visit (Optional)</label>
                                    <select class="form-select" name="visit_id" id="visitSelect">
                                        <option value="">No visit selected</option>
                                    </select>
                                    <small class="form-text">Link to patient visit if applicable</small>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">Service Date</label>
                                    <input type="date" class="form-control" name="service_date" 
                                           max="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">Claim Date</label>
                                    <input type="date" class="form-control" name="claim_date" 
                                           value="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                            </div>
                        </div>

                        <!-- Medical Information -->
                        <div class="form-section">
                            <div class="section-header">
                                <div class="section-icon">
                                    <i class="ri-medicine-bottle-line"></i>
                                </div>
                                <h5>Medical Information</h5>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Diagnosis Code (ICD-10)</label>
                                    <select class="form-select" name="diagnosis_code" id="icd10Select">
                                        <option value="">Search for diagnosis code...</option>
                                    </select>
                                    <small class="form-text">Type to search ICD-10 diagnosis codes</small>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Total Claim Amount (KES)</label>
                                    <input type="number" class="form-control" name="claim_amount" 
                                           id="claimAmount" step="0.01" min="0" placeholder="0.00" required>
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label required">Treatment Description</label>
                                    <textarea class="form-control" name="treatment_description" rows="4" 
                                              placeholder="Provide detailed description of treatments, procedures, and services provided..." required></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Claim Items -->
                        <div class="form-section">
                            <div class="section-header">
                                <div class="section-icon">
                                    <i class="ri-file-list-3-line"></i>
                                </div>
                                <h5>Claim Items/Services</h5>
                                <button type="button" class="btn btn-primary btn-sm ms-auto" onclick="addClaimItem()">
                                    <i class="ri-add-line"></i> Add Item
                                </button>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="claim-items-table" id="claimItemsTable">
                                    <thead>
                                        <tr>
                                            <th style="width: 40%;">Service/Item Description</th>
                                            <th style="width: 15%;">Quantity</th>
                                            <th style="width: 20%;">Unit Price (KES)</th>
                                            <th style="width: 20%;">Total (KES)</th>
                                            <th style="width: 5%;"></th>
                                        </tr>
                                    </thead>
                                    <tbody id="claimItemsBody">
                                        <tr>
                                            <td colspan="5" class="text-center text-muted" style="padding: 2rem;">
                                                <i class="ri-inbox-line" style="font-size: 2rem; display: block; margin-bottom: 0.5rem; opacity: 0.5;"></i>
                                                No items added yet. Click "Add Item" to include services or items.
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Additional Notes -->
                        <div class="form-section">
                            <div class="section-header">
                                <div class="section-icon">
                                    <i class="ri-file-text-line"></i>
                                </div>
                                <h5>Additional Notes</h5>
                            </div>
                            
                            <div class="row">
                                <div class="col-12 mb-3">
                                    <label class="form-label">Internal Notes</label>
                                    <textarea class="form-control" name="notes" rows="3" 
                                              placeholder="Any additional information, remarks, or special instructions for the insurance provider..."></textarea>
                                    <small class="form-text">These notes will be included with the claim submission</small>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="form-section">
                            <div class="action-bar">
                                <button type="submit" class="btn btn-success">
                                    <i class="ri-send-plane-line"></i> Submit Claim
                                </button>
                                <button type="button" class="btn btn-secondary" onclick="resetForm()">
                                    <i class="ri-refresh-line"></i> Reset Form
                                </button>
                                <a href="insurance_claims.php" class="btn btn-outline-secondary">
                                    <i class="ri-arrow-left-line"></i> Back to Claims
                                </a>
                            </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="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    let itemCounter = 0;
    
    $(document).ready(function() {
        // Initialize Select2 for patient search
        $('#patientSelect').select2({
            placeholder: 'Search for patient...',
            ajax: {
                url: 'ajax/search_patients.php',
                dataType: 'json',
                delay: 250,
                method: 'POST',
                data: function(params) {
                    return { 
                        query: params.term
                    };
                },
                processResults: function(data) {
                    if (!data.success || !data.results) {
                        return { results: [] };
                    }
                    
                    return {
                        results: data.results.map(function(patient) {
                            return {
                                id: patient.id,
                                text: patient.full_name + ' (' + patient.patient_number + ')',
                                patient: patient
                            };
                        })
                    };
                },
                cache: true
            },
            minimumInputLength: 2,
            templateResult: formatPatientResult,
            templateSelection: formatPatientSelection
        });
        
        // Initialize Select2 for ICD-10 autocomplete
        $('#icd10Select').select2({
            placeholder: 'Search for diagnosis code...',
            allowClear: true,
            ajax: {
                url: 'ajax/search_icd10.php',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return { 
                        term: params.term
                    };
                },
                processResults: function(data) {
                    if (!data.success || !data.results) {
                        return { results: [] };
                    }
                    return {
                        results: data.results
                    };
                },
                cache: true
            },
            minimumInputLength: 2,
            templateResult: formatICD10Result,
            templateSelection: formatICD10Selection
        });
        
        // Format patient results with additional info
        function formatPatientResult(patient) {
            if (patient.loading) {
                return patient.text;
            }
            
            if (!patient.patient) {
                return patient.text;
            }
            
            var p = patient.patient;
            var $result = $(
                '<div class="select2-patient-result">' +
                    '<div class="patient-name">' + p.full_name + '</div>' +
                    '<div class="patient-details">' +
                        '<span class="badge bg-primary">' + p.patient_number + '</span> ' +
                        (p.phone ? '<span class="text-muted">' + p.phone + '</span>' : '') +
                    '</div>' +
                '</div>'
            );
            
            return $result;
        }
        
        function formatPatientSelection(patient) {
            return patient.text;
        }
        
        // Format ICD-10 code results
        function formatICD10Result(item) {
            if (item.loading) {
                return item.text;
            }
            
            var badges = '';
            if (item.is_ent_related) {
                badges += '<span class="badge bg-success badge-sm">ENT</span> ';
            }
            if (item.commonly_used) {
                badges += '<span class="badge bg-warning badge-sm">Common</span>';
            }
            
            var $result = $(
                '<div class="select2-icd10-result">' +
                    '<div class="d-flex justify-content-between align-items-start">' +
                        '<div>' +
                            '<span class="icd10-code">' + item.code + '</span>' +
                            '<span class="icd10-desc">' + item.short_description + '</span>' +
                        '</div>' +
                        '<div>' + badges + '</div>' +
                    '</div>' +
                    (item.category ? '<small class="category-text"><i class="ri-folder-line"></i> ' + item.category + '</small>' : '') +
                '</div>'
            );
            
            return $result;
        }
        
        function formatICD10Selection(item) {
            if (item.code && item.short_description) {
                return item.code + ' - ' + item.short_description;
            }
            return item.text;
        }
        
        // Handle patient selection
        $('#patientSelect').on('select2:select', function(e) {
            const patient = e.params.data.patient;
            if (patient) {
                displayPatientInfo(patient);
                loadPatientVisits(patient.id);
                
                // Auto-select provider if patient has insurance
                if (patient.insurance_provider_id && patient.insurance_provider_id > 0) {
                    $('#providerSelect').val(patient.insurance_provider_id).trigger('change');
                }
            }
        });
        
        // Form validation on submit
        $('#claimForm').on('submit', function(e) {
            const patientId = $('#patientSelect').val();
            const providerId = $('#providerSelect').val();
            const claimAmount = $('#claimAmount').val();
            const treatmentDesc = $('[name="treatment_description"]').val().trim();
            
            if (!patientId) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Patient Required',
                    text: 'Please select a patient before submitting the claim'
                });
                return false;
            }
            
            if (!providerId) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Provider Required',
                    text: 'Please select an insurance provider'
                });
                return false;
            }
            
            if (!claimAmount || claimAmount <= 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Amount',
                    text: 'Please enter a valid claim amount greater than 0'
                });
                return false;
            }
            
            if (!treatmentDesc) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Treatment Description Required',
                    text: 'Please provide a description of the treatment provided'
                });
                return false;
            }
            
            // Show loading indicator
            Swal.fire({
                title: 'Submitting Claim...',
                html: 'Please wait while we process your insurance claim',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            return true;
        });
    });
    
    function displayPatientInfo(patient) {
        $('#patientInfo').slideDown(300);
        $('#patientName').text(patient.full_name || '-');
        $('#patientNumber').text(patient.patient_number || '-');
        $('#insuranceNumber').text(patient.insurance_number || 'N/A');
        $('#insuranceProvider').text(patient.provider_name || 'None');
        $('#patientPhone').text(patient.phone_primary || patient.phone || '-');
        
        // Format registration type
        let regType = (patient.registration_type || 'WALK_IN').replace('_', ' ');
        $('#registrationType').html('<span class="badge bg-info">' + regType + '</span>');
    }
    
    function loadPatientVisits(patientId) {
        $.ajax({
            url: 'ajax/get_patient_visits.php',
            type: 'POST',
            data: { patient_id: patientId },
            dataType: 'json',
            success: function(response) {
                if (response.success && response.visits && response.visits.length > 0) {
                    $('#visitSelect').empty().append('<option value="">No visit selected</option>');
                    
                    response.visits.forEach(function(visit) {
                        const visitDate = visit.formatted_date || visit.registration_date;
                        const visitSource = visit.visit_source ? ' (' + visit.visit_source + ')' : '';
                        $('#visitSelect').append(
                            '<option value="' + visit.visit_id + '">' +
                                visit.visit_number + ' - ' + visit.visit_type + visitSource + ' [' + visitDate + ']' +
                            '</option>'
                        );
                    });
                } else {
                    $('#visitSelect').empty().append('<option value="">No visits found</option>');
                }
            },
            error: function() {
                $('#visitSelect').empty().append('<option value="">Error loading visits</option>');
            }
        });
    }
    
    function addClaimItem() {
        itemCounter++;
        const tbody = $('#claimItemsBody');
        
        // Remove "no items" message if present
        if (tbody.find('tr td[colspan]').length > 0) {
            tbody.empty();
        }
        
        const row = `
            <tr id="item_${itemCounter}" style="animation: slideIn 0.3s ease;">
                <td>
                    <input type="text" class="form-control form-control-sm" 
                           name="item_description[]" 
                           placeholder="e.g., ENT Consultation, Audiometry Test, Tympanoplasty" 
                           required>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm item-quantity" 
                           name="item_quantity[]" 
                           value="1" 
                           min="1" 
                           onchange="calculateItemTotal(${itemCounter})" 
                           required>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm item-price" 
                           name="item_price[]" 
                           step="0.01" 
                           min="0" 
                           placeholder="0.00"
                           onchange="calculateItemTotal(${itemCounter})" 
                           required>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm item-total" 
                           name="item_total[]" 
                           step="0.01" 
                           placeholder="0.00"
                           readonly 
                           style="background: #f9fafb;">
                </td>
                <td class="text-center">
                    <button type="button" class="btn-remove-item" onclick="removeClaimItem(${itemCounter})" title="Remove item">
                        <i class="ri-delete-bin-line"></i>
                    </button>
                </td>
            </tr>
        `;
        
        tbody.append(row);
        
        // Focus on the description field of the new row
        $(`#item_${itemCounter} input[name="item_description[]"]`).focus();
    }
    
    function calculateItemTotal(itemId) {
        const row = $(`#item_${itemId}`);
        const quantity = parseFloat(row.find('.item-quantity').val()) || 0;
        const price = parseFloat(row.find('.item-price').val()) || 0;
        const total = quantity * price;
        
        row.find('.item-total').val(total.toFixed(2));
        calculateClaimTotal();
    }
    
    function calculateClaimTotal() {
        let total = 0;
        $('.item-total').each(function() {
            const value = parseFloat($(this).val()) || 0;
            total += value;
        });
        
        if (total > 0) {
            $('#claimAmount').val(total.toFixed(2));
            
            // Highlight the total amount field briefly
            $('#claimAmount').addClass('border-success');
            setTimeout(() => {
                $('#claimAmount').removeClass('border-success');
            }, 1000);
        }
    }
    
    function removeClaimItem(itemId) {
        Swal.fire({
            title: 'Remove Item?',
            text: 'Are you sure you want to remove this item?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Yes, remove it',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                $(`#item_${itemId}`).fadeOut(300, function() {
                    $(this).remove();
                    
                    // Show "no items" message if no items left
                    if ($('#claimItemsBody tr').length === 0) {
                        $('#claimItemsBody').html(`
                            <tr>
                                <td colspan="5" class="text-center text-muted" style="padding: 2rem;">
                                    <i class="ri-inbox-line" style="font-size: 2rem; display: block; margin-bottom: 0.5rem; opacity: 0.5;"></i>
                                    No items added yet. Click "Add Item" to include services or items.
                                </td>
                            </tr>
                        `);
                    }
                    
                    calculateClaimTotal();
                });
            }
        });
    }
    
    function resetForm() {
        Swal.fire({
            title: 'Reset Form?',
            text: 'All entered data will be lost. Are you sure?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Yes, reset form',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Reset the form
                document.getElementById('claimForm').reset();
                
                // Clear Select2
                $('#patientSelect').val(null).trigger('change');
                $('#providerSelect').val('').trigger('change');
                $('#icd10Select').val(null).trigger('change');
                
                // Hide patient info
                $('#patientInfo').slideUp(300);
                
                // Reset claim items table
                $('#claimItemsBody').html(`
                    <tr>
                        <td colspan="5" class="text-center text-muted" style="padding: 2rem;">
                            <i class="ri-inbox-line" style="font-size: 2rem; display: block; margin-bottom: 0.5rem; opacity: 0.5;"></i>
                            No items added yet. Click "Add Item" to include services or items.
                        </td>
                    </tr>
                `);
                
                // Reset counter
                itemCounter = 0;
                
                Swal.fire({
                    icon: 'success',
                    title: 'Form Reset',
                    text: 'The form has been cleared',
                    timer: 1500,
                    showConfirmButton: false
                });
            }
        });
    }
    
    // Add keyboard shortcuts
    $(document).on('keydown', function(e) {
        // Ctrl/Cmd + S to submit form
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            $('#claimForm').submit();
        }
        
        // Ctrl/Cmd + I to add item
        if ((e.ctrlKey || e.metaKey) && e.key === 'i') {
            e.preventDefault();
            addClaimItem();
        }
    });
    
    // Show keyboard shortcuts hint on console
    console.log('%c💡 Keyboard Shortcuts:', 'font-weight: bold; font-size: 14px; color: #3b82f6;');
    console.log('Ctrl/Cmd + S: Submit claim');
    console.log('Ctrl/Cmd + I: Add claim item');
    </script>

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