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

$page_title = "Create Invoice";
$success_message = '';
$error_message = '';

// Generate new invoice number
function generateInvoiceNumber($conn) {
    $prefix = "INV";
    $date = date('Ymd');
    
    $query = "SELECT COUNT(*) as count FROM invoices WHERE DATE(created_at) = CURDATE()";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);
    $sequence = str_pad($row['count'] + 1, 4, '0', STR_PAD_LEFT);
    
    return $prefix . $date . $sequence;
}

// Get insurance providers - USING EXACT SCHEMA COLUMNS
$insurance_query = "SELECT provider_id, provider_name, provider_code, co_payment_percentage 
                    FROM insurance_providers WHERE is_active = 1 ORDER BY provider_name";
$insurance_result = mysqli_query($conn, $insurance_query);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_invoice'])) {
    $patient_id = mysqli_real_escape_string($conn, $_POST['patient_id']);
    $visit_id = mysqli_real_escape_string($conn, $_POST['visit_id']);
    $bill_to = mysqli_real_escape_string($conn, $_POST['bill_to']);
    $insurance_provider_id = $bill_to == 'INSURANCE' ? mysqli_real_escape_string($conn, $_POST['insurance_provider_id']) : NULL;
    $invoice_date = date('Y-m-d');
    $due_date = mysqli_real_escape_string($conn, $_POST['due_date']);
    $payment_terms = mysqli_real_escape_string($conn, $_POST['payment_terms']);
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $discount_amount = isset($_POST['discount_amount']) ? floatval($_POST['discount_amount']) : 0;
    
    mysqli_begin_transaction($conn);
    
    try {
        $invoice_number = generateInvoiceNumber($conn);
        
        // Calculate totals from items
        $subtotal = 0;
        if (isset($_POST['items']) && is_array($_POST['items'])) {
            foreach ($_POST['items'] as $item) {
                $quantity = floatval($item['quantity']);
                $unit_price = floatval($item['unit_price']);
                $subtotal += $quantity * $unit_price;
            }
        }
        
        // Calculate insurance coverage
        $insurance_covered = 0;
        if ($bill_to == 'INSURANCE' && $insurance_provider_id) {
            $provider_query = "SELECT co_payment_percentage FROM insurance_providers WHERE provider_id = '$insurance_provider_id'";
            $provider_result = mysqli_query($conn, $provider_query);
            if ($provider_result && mysqli_num_rows($provider_result) > 0) {
                $provider = mysqli_fetch_assoc($provider_result);
                $insurance_covered = $subtotal * ((100 - $provider['co_payment_percentage']) / 100);
            }
        }
        
        $tax_amount = 0; // Medical services are VAT-exempt in Kenya
        $total_amount = $subtotal - $discount_amount + $tax_amount;
        $patient_portion = $total_amount - $insurance_covered;
        
        // Insert invoice - USING EXACT SCHEMA COLUMNS
        $invoice_query = "INSERT INTO invoices (
                         invoice_number, visit_id, patient_id, invoice_date, due_date, 
                         bill_to, insurance_provider_id, insurance_claim_number, subtotal, tax_amount, 
                         discount_amount, insurance_covered, total_amount, patient_portion, 
                         amount_paid, balance, payment_terms, status, 
                         etims_submitted, notes, created_by
                         ) VALUES (
                         '$invoice_number', '$visit_id', '$patient_id', '$invoice_date', '$due_date',
                         '$bill_to', " . ($insurance_provider_id ? "'$insurance_provider_id'" : "NULL") . ", 
                         NULL, '$subtotal', '$tax_amount', 
                         '$discount_amount', '$insurance_covered', '$total_amount', '$patient_portion', 
                         0.00, '$patient_portion', '$payment_terms', 'DRAFT', 
                         0, '$notes', {$_SESSION['user_id']})";
        
        if (!mysqli_query($conn, $invoice_query)) {
            throw new Exception("Error creating invoice: " . mysqli_error($conn));
        }
        
        $invoice_id = mysqli_insert_id($conn);
        
        // Insert invoice items - USING EXACT SCHEMA COLUMNS
        if (isset($_POST['items']) && is_array($_POST['items'])) {
            foreach ($_POST['items'] as $item) {
                $item_type = mysqli_real_escape_string($conn, $item['type']);
                $reference_id = !empty($item['reference_id']) ? mysqli_real_escape_string($conn, $item['reference_id']) : NULL;
                $description = mysqli_real_escape_string($conn, $item['description']);
                $quantity = intval($item['quantity']);
                $unit_price = floatval($item['unit_price']);
                $total_price = $quantity * $unit_price;
                
                $item_query = "INSERT INTO invoice_items (
                              invoice_id, item_type, reference_id, description, 
                              quantity, unit_price, total_price, provider_id, 
                              commission_rate, commission_amount, date_of_service
                              ) VALUES (
                              '$invoice_id', '$item_type', " . ($reference_id ? "'$reference_id'" : "NULL") . ",
                              '$description', '$quantity', '$unit_price', '$total_price', 
                              NULL, 0.00, 0.00, NULL)";
                
                if (!mysqli_query($conn, $item_query)) {
                    throw new Exception("Error adding invoice item: " . mysqli_error($conn));
                }
            }
        }
        
        mysqli_commit($conn);
        
        $_SESSION['success_message'] = "Invoice $invoice_number created successfully!";
        header("Location: list_invoices.php");
        exit();
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error_message = $e->getMessage();
    }
}

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?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" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .summary-card {
            position: sticky;
            top: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 12px;
            padding: 1.5rem;
            color: white;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .summary-row:last-child {
            border-bottom: none;
        }
        
        .select2-container--bootstrap-5 .select2-selection {
            min-height: 38px;
            border: 1px solid #ced4da;
        }
        
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
            padding-left: 12px;
        }
        
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
        
        .select2-patient-result {
            padding: 4px 0;
            line-height: 1.4;
        }
        
        .select2-patient-result .text-muted {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .select2-patient-result i {
            font-size: 0.875rem;
            opacity: 0.7;
            margin-right: 2px;
        }
        
        .select2-container--bootstrap-5 .select2-search--dropdown .select2-search__field {
            padding: 8px 12px;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
        }
        
        .select2-container--bootstrap-5 .select2-search--dropdown .select2-search__field:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
    </style>
</head>

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

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="financial_dashboard.php">Financial</a></li>
                                        <li class="breadcrumb-item"><a href="list_invoices.php">Invoices</a></li>
                                        <li class="breadcrumb-item active">Create</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-file-add-line me-2"></i>Create New Invoice</h4>
                                <p class="mb-0">Generate invoice for patient services</p>
                            </div>
                            <a href="list_invoices.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i> Back to Invoices
                            </a>
                        </div>
                    </div>

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

                    <form method="POST" id="invoiceForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <div class="chart-card">
                                    <h5 class="mb-3"><i class="ri-user-line me-2"></i>Patient & Billing Information</h5>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Patient <span class="text-danger">*</span></label>
                                            <select class="form-select select2-patient" name="patient_id" id="patient_id" required>
                                                <option value="">Type to search patients...</option>
                                            </select>
                                            <small class="text-muted">Search by name, patient number, or phone</small>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Visit <span class="text-danger">*</span></label>
                                            <select class="form-select" name="visit_id" id="visit_id" required>
                                                <option value="">Select Patient First</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Bill To <span class="text-danger">*</span></label>
                                            <select class="form-select" name="bill_to" id="bill_to" required>
                                                <option value="PATIENT">Patient (Self-Pay)</option>
                                                <option value="INSURANCE">Insurance Provider</option>
                                                <option value="CORPORATE">Corporate/Employer</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6" id="insurance_provider_div" style="display: none;">
                                            <label class="form-label">Insurance Provider</label>
                                            <select class="form-select select2" name="insurance_provider_id" id="insurance_provider_id">
                                                <option value="">Select Provider</option>
                                                <?php 
                                                mysqli_data_seek($insurance_result, 0);
                                                while ($provider = mysqli_fetch_assoc($insurance_result)): 
                                                ?>
                                                <option value="<?php echo $provider['provider_id']; ?>"
                                                        data-copay="<?php echo $provider['co_payment_percentage']; ?>">
                                                    <?php echo $provider['provider_name']; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Due Date <span class="text-danger">*</span></label>
                                            <input type="date" class="form-control" name="due_date" 
                                                   value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Payment Terms</label>
                                            <select class="form-select" name="payment_terms">
                                                <option value="Immediate">Immediate</option>
                                                <option value="Net 7">Net 7 Days</option>
                                                <option value="Net 15">Net 15 Days</option>
                                                <option value="Net 30" selected>Net 30 Days</option>
                                                <option value="Net 60">Net 60 Days</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Discount Amount (KES)</label>
                                            <input type="number" class="form-control" name="discount_amount" 
                                                   id="discount_amount" value="0" step="0.01" min="0">
                                        </div>
                                    </div>

                                    <div class="mb-0">
                                        <label class="form-label">Invoice Notes</label>
                                        <textarea class="form-control" name="notes" rows="2" 
                                                  placeholder="Additional notes or special instructions..."></textarea>
                                    </div>
                                </div>

                                <div class="chart-card">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h5 class="mb-0"><i class="ri-list-check me-2"></i>Invoice Items</h5>
                                        <button type="button" class="btn btn-sm btn-primary" id="addItemBtn">
                                            <i class="ri-add-line me-1"></i>Add Item
                                        </button>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="itemsTable">
                                            <thead class="table-light">
                                                <tr>
                                                    <th style="width: 18%">Type</th>
                                                    <th style="width: 35%">Description</th>
                                                    <th style="width: 12%">Quantity</th>
                                                    <th style="width: 15%">Unit Price</th>
                                                    <th style="width: 15%">Total</th>
                                                    <th style="width: 5%"></th>
                                                </tr>
                                            </thead>
                                            <tbody id="itemsBody">
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <div class="summary-card">
                                    <h5 class="mb-3 text-white"><i class="ri-calculator-line me-2"></i>Invoice Summary</h5>
                                    
                                    <div class="summary-row">
                                        <span>Subtotal:</span>
                                        <strong id="subtotal_display">KES 0.00</strong>
                                    </div>
                                    <div class="summary-row">
                                        <span>Discount:</span>
                                        <strong id="discount_display">- KES 0.00</strong>
                                    </div>
                                    <div class="summary-row">
                                        <span>Tax (VAT):</span>
                                        <strong id="tax_display">KES 0.00</strong>
                                        <small style="display:block; opacity:0.8;">Medical services VAT-exempt</small>
                                    </div>
                                    <div class="summary-row" style="font-size: 1.1rem; padding-top: 1rem;">
                                        <strong>Total Amount:</strong>
                                        <strong id="total_display">KES 0.00</strong>
                                    </div>
                                    <div class="summary-row" id="insurance_coverage_div" style="display: none;">
                                        <span>Insurance Covers:</span>
                                        <strong id="insurance_display">KES 0.00</strong>
                                    </div>
                                    <div class="summary-row" id="patient_portion_div" style="display: none;">
                                        <strong>Patient Pays:</strong>
                                        <strong id="patient_portion_display">KES 0.00</strong>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <button type="submit" name="create_invoice" class="btn btn-light btn-lg w-100 mb-2">
                                            <i class="ri-check-line me-2"></i>Create Invoice
                                        </button>
                                        <a href="list_invoices.php" class="btn btn-outline-light w-100">
                                            <i class="ri-close-line me-2"></i>Cancel
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    
                </div>
            </div>
        </div>

        <?php include 'layouts/footer.php'; ?>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize Select2 for Patient with AJAX search
        $('.select2-patient').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: 'Type to search patients (name, number, or phone)...',
            allowClear: true,
            minimumInputLength: 2,
            ajax: {
                url: 'ajax/search_patients.php',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        query: params.term,
                        page: params.page || 1
                    };
                },
                processResults: function(data, params) {
                    params.page = params.page || 1;
                    
                    if (!data.success || !data.results) {
                        return { results: [], pagination: { more: false } };
                    }
                    
                    const results = data.results.map(function(patient) {
                        return {
                            id: patient.id || patient.patient_id,
                            text: patient.patient_number + ' - ' + patient.full_name,
                            patient_id: patient.id || patient.patient_id,
                            patient_number: patient.patient_number,
                            full_name: patient.full_name,
                            phone_primary: patient.phone_primary || patient.phone || '',
                            age: patient.age || '',
                            gender: patient.gender || '',
                            registration_type: patient.registration_type || ''
                        };
                    });
                    
                    return {
                        results: results,
                        pagination: { more: data.total >= 20 }
                    };
                },
                cache: true
            },
            templateResult: formatPatientResult,
            templateSelection: formatPatientSelection,
            language: {
                inputTooShort: function() {
                    return "Type at least 2 characters to search patients";
                },
                searching: function() {
                    return "Searching patients...";
                },
                noResults: function() {
                    return "No patients found";
                },
                errorLoading: function() {
                    return "Error loading results";
                }
            }
        });
        
        function formatPatientResult(patient) {
            if (!patient.id) return patient.text;
            if (patient.loading) return patient.text;
            
            let displayHtml = '<div class="select2-patient-result">';
            displayHtml += '<div><strong>' + patient.patient_number + '</strong> - ' + patient.full_name + '</div>';
            
            let additionalInfo = [];
            if (patient.age) additionalInfo.push('<i class="ri-calendar-line"></i> ' + patient.age + ' yrs');
            if (patient.gender) {
                const genderIcon = patient.gender === 'MALE' ? 'ri-men-line' : 'ri-women-line';
                additionalInfo.push('<i class="' + genderIcon + '"></i> ' + patient.gender);
            }
            if (patient.phone_primary) additionalInfo.push('<i class="ri-phone-line"></i> ' + patient.phone_primary);
            
            if (additionalInfo.length > 0) {
                displayHtml += '<div class="text-muted small mt-1">' + additionalInfo.join(' | ') + '</div>';
            }
            displayHtml += '</div>';
            
            return $(displayHtml);
        }
        
        function formatPatientSelection(patient) {
            if (!patient.id) return patient.text;
            return patient.patient_number + ' - ' + patient.full_name;
        }
        
        $('#insurance_provider_id').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: 'Select insurance provider...',
            allowClear: true
        });

        let itemCounter = 0;

        $('#addItemBtn').on('click', function() {
            addInvoiceItem();
        });

        function addInvoiceItem() {
            const row = `
                <tr data-item="${itemCounter}">
                    <td>
                        <select class="form-select form-select-sm item-type" name="items[${itemCounter}][type]" required>
                            <option value="CONSULTATION">Consultation</option>
                            <option value="PROCEDURE">Procedure</option>
                            <option value="TEST">Test</option>
                            <option value="MEDICATION">Medication</option>
                            <option value="ACCOMMODATION">Accommodation</option>
                            <option value="OTHER">Other</option>
                        </select>
                    </td>
                    <td>
                        <input type="hidden" name="items[${itemCounter}][reference_id]" class="item-reference">
                        <input type="text" class="form-control form-control-sm item-description" 
                               name="items[${itemCounter}][description]" required placeholder="Item description">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm item-quantity" 
                               name="items[${itemCounter}][quantity]" value="1" min="1" step="1" required>
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm item-price" 
                               name="items[${itemCounter}][unit_price]" value="0" min="0" step="0.01" required>
                    </td>
                    <td class="text-end">
                        <strong class="item-total">0.00</strong>
                    </td>
                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-danger remove-item">
                            <i class="ri-delete-bin-line"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#itemsBody').append(row);
            itemCounter++;
            calculateTotals();
        }

        $(document).on('click', '.remove-item', function() {
            if ($('#itemsBody tr').length > 1) {
                $(this).closest('tr').remove();
                calculateTotals();
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'Cannot Remove',
                    text: 'Invoice must have at least one item'
                });
            }
        });

        $(document).on('input', '.item-quantity, .item-price', function() {
            const row = $(this).closest('tr');
            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').text(total.toFixed(2));
            calculateTotals();
        });

        $('#discount_amount, #insurance_provider_id').on('input change', function() {
            calculateTotals();
        });

        function calculateTotals() {
            let subtotal = 0;
            
            $('.item-total').each(function() {
                subtotal += parseFloat($(this).text()) || 0;
            });
            
            const discount = parseFloat($('#discount_amount').val()) || 0;
            const tax = 0;
            const total = subtotal - discount + tax;
            
            let insuranceCovered = 0;
            let patientPortion = total;
            
            if ($('#bill_to').val() === 'INSURANCE' && $('#insurance_provider_id').val()) {
                const copayPercentage = parseFloat($('#insurance_provider_id option:selected').data('copay')) || 0;
                insuranceCovered = total * ((100 - copayPercentage) / 100);
                patientPortion = total - insuranceCovered;
                
                $('#insurance_coverage_div').show();
                $('#patient_portion_div').show();
                $('#insurance_display').text('KES ' + insuranceCovered.toFixed(2));
                $('#patient_portion_display').text('KES ' + patientPortion.toFixed(2));
            } else {
                $('#insurance_coverage_div').hide();
                $('#patient_portion_div').hide();
            }
            
            $('#subtotal_display').text('KES ' + subtotal.toFixed(2));
            $('#discount_display').text('- KES ' + discount.toFixed(2));
            $('#tax_display').text('KES ' + tax.toFixed(2));
            $('#total_display').text('KES ' + total.toFixed(2));
        }

        $('#bill_to').on('change', function() {
            if ($(this).val() === 'INSURANCE') {
                $('#insurance_provider_div').show();
                $('#insurance_provider_id').prop('required', true);
            } else {
                $('#insurance_provider_div').hide();
                $('#insurance_provider_id').prop('required', false);
                $('#insurance_coverage_div').hide();
                $('#patient_portion_div').hide();
            }
            calculateTotals();
        });

        $('#patient_id').on('select2:select', function(e) {
            const patientId = $(this).val();
            
            if (patientId) {
                $('#visit_id').html('<option value="">Loading visits...</option>');
                
                $.ajax({
                    url: 'ajax/get_patient_visits.php',
                    method: 'POST',
                    dataType: 'json',
                    data: { patient_id: patientId },
                    success: function(response) {
                        if (response.success && response.visits && response.visits.length > 0) {
                            let options = '<option value="">Select a visit</option>';
                            
                            response.visits.forEach(function(visit) {
                                let visitType = visit.visit_type.replace(/_/g, ' ')
                                    .toLowerCase()
                                    .replace(/\b\w/g, l => l.toUpperCase());
                                
                                let statusBadge = '';
                                switch(visit.status) {
                                    case 'REGISTERED':
                                        statusBadge = '[Registered]';
                                        break;
                                    case 'WAITING':
                                        statusBadge = '[Waiting]';
                                        break;
                                    case 'IN_CONSULTATION':
                                        statusBadge = '[In Consultation]';
                                        break;
                                }
                                
                                let optionText = visit.visit_number + ' - ' + 
                                               visit.formatted_date + ' - ' + 
                                               visitType + ' ' + statusBadge;
                                
                                options += '<option value="' + visit.visit_id + '">' + 
                                          optionText + '</option>';
                            });
                            
                            $('#visit_id').html(options);
                        } else {
                            $('#visit_id').html('<option value="">No active visits found</option>');
                            
                            Swal.fire({
                                icon: 'info',
                                title: 'No Active Visits',
                                text: 'This patient has no active visits. You may need to register a new visit first.',
                                showCancelButton: true,
                                confirmButtonText: 'Register New Visit',
                                cancelButtonText: 'Continue Anyway'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    window.open('register_visit.php?patient_id=' + patientId, '_blank');
                                }
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX Error:', status, error);
                        $('#visit_id').html('<option value="">Error loading visits</option>');
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to load patient visits. Please try again.'
                        });
                    }
                });
            } else {
                $('#visit_id').html('<option value="">Select Patient First</option>');
            }
        });
        
        $('#patient_id').on('select2:clear', function() {
            $('#visit_id').html('<option value="">Select Patient First</option>');
        });

        $('#invoiceForm').on('submit', function(e) {
            if ($('#itemsBody tr').length === 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'No Items',
                    text: 'Please add at least one item to the invoice'
                });
                return false;
            }
        });

        addInvoiceItem();
    });
    </script>
</body>
</html>