<?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();
}

// Get invoice ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "Invalid invoice ID";
    header('Location: list_invoices.php');
    exit();
}

$invoice_id = intval($_GET['id']);
$page_title = "Edit Invoice";
$error_message = '';

// Get invoice details with patient and visit info
$invoice_query = "SELECT i.*, 
                  p.patient_number,
                  u.full_name as patient_name,
                  u.phone_primary,
                  pv.visit_number
                  FROM invoices i
                  INNER JOIN patients p ON i.patient_id = p.patient_id
                  INNER JOIN users u ON p.user_id = u.user_id
                  LEFT JOIN patient_visits pv ON i.visit_id = pv.visit_id
                  WHERE i.invoice_id = '$invoice_id'";
$invoice_result = mysqli_query($conn, $invoice_query);

if (!$invoice_result || mysqli_num_rows($invoice_result) == 0) {
    $_SESSION['error_message'] = "Invoice not found";
    header('Location: list_invoices.php');
    exit();
}

$invoice = mysqli_fetch_assoc($invoice_result);

// Check if invoice can be edited (only DRAFT and SENT invoices can be edited)
if (!in_array($invoice['status'], ['DRAFT', 'SENT', 'INSURANCE_PENDING'])) {
    $_SESSION['error_message'] = "Cannot edit invoice with status: " . $invoice['status'];
    header('Location: list_invoices.php');
    exit();
}

// Get invoice items
$items_query = "SELECT * FROM invoice_items WHERE invoice_id = '$invoice_id' ORDER BY item_id";
$items_result = mysqli_query($conn, $items_query);

// Get insurance providers
$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);

// Get patient visits for dropdown
$visits_query = "SELECT visit_id, visit_number, registration_date, visit_type, status
                 FROM patient_visits 
                 WHERE patient_id = '{$invoice['patient_id']}'
                 ORDER BY registration_date DESC
                 LIMIT 20";
$visits_result = mysqli_query($conn, $visits_query);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_invoice'])) {
    $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;
    $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;
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    mysqli_begin_transaction($conn);
    
    try {
        // 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;
        $total_amount = $subtotal - $discount_amount + $tax_amount;
        $patient_portion = $total_amount - $insurance_covered;
        
        // Calculate new balance (total - amount already paid)
        $new_balance = $patient_portion - floatval($invoice['amount_paid']);
        
        // Update invoice
        $update_query = "UPDATE invoices SET
                        visit_id = '$visit_id',
                        due_date = '$due_date',
                        bill_to = '$bill_to',
                        insurance_provider_id = " . ($insurance_provider_id ? "'$insurance_provider_id'" : "NULL") . ",
                        subtotal = '$subtotal',
                        tax_amount = '$tax_amount',
                        discount_amount = '$discount_amount',
                        insurance_covered = '$insurance_covered',
                        total_amount = '$total_amount',
                        patient_portion = '$patient_portion',
                        balance = '$new_balance',
                        payment_terms = '$payment_terms',
                        status = '$status',
                        notes = '$notes',
                        updated_at = NOW()
                        WHERE invoice_id = '$invoice_id'";
        
        if (!mysqli_query($conn, $update_query)) {
            throw new Exception("Error updating invoice: " . mysqli_error($conn));
        }
        
        // Delete existing invoice items
        $delete_items = "DELETE FROM invoice_items WHERE invoice_id = '$invoice_id'";
        if (!mysqli_query($conn, $delete_items)) {
            throw new Exception("Error deleting old invoice items: " . mysqli_error($conn));
        }
        
        // Insert updated invoice items
        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['invoice_number']} updated 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;
        }
        
        .info-card {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border-radius: 0.375rem;
        }
        
        .badge-status {
            font-size: 0.875rem;
            padding: 0.5rem 1rem;
        }
    </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">Edit</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-edit-line me-2"></i>Edit Invoice: <?php echo $invoice['invoice_number']; ?></h4>
                                <p class="mb-0">
                                    Patient: <?php echo $invoice['patient_name']; ?> (<?php echo $invoice['patient_number']; ?>)
                                    <span class="badge badge-status bg-<?php 
                                        echo $invoice['status'] == 'DRAFT' ? 'secondary' : 
                                            ($invoice['status'] == 'SENT' ? 'info' : 'warning'); 
                                    ?> ms-2"><?php echo $invoice['status']; ?></span>
                                </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; ?>

                    <div class="info-card">
                        <div class="row">
                            <div class="col-md-3">
                                <small class="text-muted">Invoice Date</small>
                                <div><strong><?php echo date('M d, Y', strtotime($invoice['invoice_date'])); ?></strong></div>
                            </div>
                            <div class="col-md-3">
                                <small class="text-muted">Amount Paid</small>
                                <div><strong>KES <?php echo number_format($invoice['amount_paid'], 2); ?></strong></div>
                            </div>
                            <div class="col-md-3">
                                <small class="text-muted">Balance</small>
                                <div><strong>KES <?php echo number_format($invoice['balance'], 2); ?></strong></div>
                            </div>
                            <div class="col-md-3">
                                <small class="text-muted">Created By</small>
                                <div><strong>User ID: <?php echo $invoice['created_by']; ?></strong></div>
                            </div>
                        </div>
                    </div>

                    <form method="POST" id="invoiceForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <div class="chart-card">
                                    <h5 class="mb-3"><i class="ri-file-info-line me-2"></i>Invoice Details</h5>
                                    
                                    <div class="row mb-3">
                                        <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>
                                                <?php 
                                                mysqli_data_seek($visits_result, 0);
                                                while ($visit = mysqli_fetch_assoc($visits_result)): 
                                                    $selected = $visit['visit_id'] == $invoice['visit_id'] ? 'selected' : '';
                                                    $visit_type = ucfirst(str_replace('_', ' ', strtolower($visit['visit_type'])));
                                                    $visit_date = date('M d, Y', strtotime($visit['registration_date']));
                                                ?>
                                                <option value="<?php echo $visit['visit_id']; ?>" <?php echo $selected; ?>>
                                                    <?php echo $visit['visit_number'] . ' - ' . $visit_date . ' - ' . $visit_type; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <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" <?php echo $invoice['bill_to'] == 'PATIENT' ? 'selected' : ''; ?>>Patient (Self-Pay)</option>
                                                <option value="INSURANCE" <?php echo $invoice['bill_to'] == 'INSURANCE' ? 'selected' : ''; ?>>Insurance Provider</option>
                                                <option value="CORPORATE" <?php echo $invoice['bill_to'] == 'CORPORATE' ? 'selected' : ''; ?>>Corporate/Employer</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6" id="insurance_provider_div" style="display: <?php echo $invoice['bill_to'] == 'INSURANCE' ? 'block' : '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)): 
                                                    $selected = $provider['provider_id'] == $invoice['insurance_provider_id'] ? 'selected' : '';
                                                ?>
                                                <option value="<?php echo $provider['provider_id']; ?>"
                                                        data-copay="<?php echo $provider['co_payment_percentage']; ?>"
                                                        <?php echo $selected; ?>>
                                                    <?php echo $provider['provider_name']; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status" id="status">
                                                <option value="DRAFT" <?php echo $invoice['status'] == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                                <option value="SENT" <?php echo $invoice['status'] == 'SENT' ? 'selected' : ''; ?>>Sent</option>
                                                <option value="INSURANCE_PENDING" <?php echo $invoice['status'] == 'INSURANCE_PENDING' ? 'selected' : ''; ?>>Insurance Pending</option>
                                            </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 $invoice['due_date']; ?>" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Payment Terms</label>
                                            <select class="form-select" name="payment_terms">
                                                <option value="Immediate" <?php echo $invoice['payment_terms'] == 'Immediate' ? 'selected' : ''; ?>>Immediate</option>
                                                <option value="Net 7" <?php echo $invoice['payment_terms'] == 'Net 7' ? 'selected' : ''; ?>>Net 7 Days</option>
                                                <option value="Net 15" <?php echo $invoice['payment_terms'] == 'Net 15' ? 'selected' : ''; ?>>Net 15 Days</option>
                                                <option value="Net 30" <?php echo $invoice['payment_terms'] == 'Net 30' ? 'selected' : ''; ?>>Net 30 Days</option>
                                                <option value="Net 60" <?php echo $invoice['payment_terms'] == 'Net 60' ? 'selected' : ''; ?>>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="<?php echo $invoice['discount_amount']; ?>" 
                                                   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..."><?php echo htmlspecialchars($invoice['notes']); ?></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>
                                    
                                    <hr style="border-color: rgba(255,255,255,0.3);">
                                    
                                    <div class="summary-row">
                                        <span>Amount Paid:</span>
                                        <strong>KES <?php echo number_format($invoice['amount_paid'], 2); ?></strong>
                                    </div>
                                    <div class="summary-row" style="font-size: 1.1rem;">
                                        <strong>New Balance:</strong>
                                        <strong id="balance_display">KES 0.00</strong>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <button type="submit" name="update_invoice" class="btn btn-light btn-lg w-100 mb-2">
                                            <i class="ri-save-line me-2"></i>Update 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() {
        const amountPaid = <?php echo $invoice['amount_paid']; ?>;
        
        $('#insurance_provider_id').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: 'Select insurance provider...',
            allowClear: true
        });

        let itemCounter = 0;
        
        // Load existing items
        <?php 
        mysqli_data_seek($items_result, 0);
        while ($item = mysqli_fetch_assoc($items_result)): 
        ?>
        addInvoiceItem(
            '<?php echo $item['item_type']; ?>',
            '<?php echo addslashes($item['description']); ?>',
            <?php echo $item['quantity']; ?>,
            <?php echo $item['unit_price']; ?>
        );
        <?php endwhile; ?>

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

        function addInvoiceItem(type = 'CONSULTATION', description = '', quantity = 1, price = 0) {
            const row = `
                <tr data-item="${itemCounter}">
                    <td>
                        <select class="form-select form-select-sm item-type" name="items[${itemCounter}][type]" required>
                            <option value="CONSULTATION" ${type == 'CONSULTATION' ? 'selected' : ''}>Consultation</option>
                            <option value="PROCEDURE" ${type == 'PROCEDURE' ? 'selected' : ''}>Procedure</option>
                            <option value="TEST" ${type == 'TEST' ? 'selected' : ''}>Test</option>
                            <option value="MEDICATION" ${type == 'MEDICATION' ? 'selected' : ''}>Medication</option>
                            <option value="ACCOMMODATION" ${type == 'ACCOMMODATION' ? 'selected' : ''}>Accommodation</option>
                            <option value="OTHER" ${type == 'OTHER' ? 'selected' : ''}>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"
                               value="${description}">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm item-quantity" 
                               name="items[${itemCounter}][quantity]" value="${quantity}" min="1" step="1" required>
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm item-price" 
                               name="items[${itemCounter}][unit_price]" value="${price}" min="0" step="0.01" required>
                    </td>
                    <td class="text-end">
                        <strong class="item-total">${(quantity * price).toFixed(2)}</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();
            }
            
            const newBalance = patientPortion - amountPaid;
            
            $('#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));
            $('#balance_display').text('KES ' + newBalance.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();
        });

        $('#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;
            }
        });

        // Initial calculation
        calculateTotals();
    });
    </script>
</body>
</html>