@extends('layouts.app')

@section('title', 'Edit Bulk Invoice #' . $invoice->InvoiceNo)

@push('styles')
<style>
    /* Sulis Color Scheme */
    :root {
        --sulis-primary: #2c3e50;      /* Dark blue */
        --sulis-secondary: #3498db;    /* Blue */
        --sulis-accent: #e74c3c;       /* Red */
        --sulis-light: #ecf0f1;        /* Light gray */
        --sulis-dark: #2c3e50;         /* Dark blue */
        --sulis-success: #27ae60;      /* Green */
        --sulis-warning: #f39c12;      /* Orange */
        --sulis-danger: #e74c3c;       /* Red */
    }

    /* Card Styling */
    .card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        margin-bottom: 1.5rem;
        border-left: 4px solid var(--sulis-warning);
        border-top: 4px solid var(--sulis-secondary);
    }

    .card-header {
        background-color: var(--sulis-primary);
        color: white;
        border-bottom: none;
        font-weight: 600;
        padding: 1rem 1.5rem;
        border-bottom: 4px solid var(--sulis-secondary);
    }

    /* Form Controls */
    .form-control, .form-select {
        border: 1px solid #d1d5db;
        border-radius: 4px;
        padding: 0.5rem 0.75rem;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--sulis-secondary);
        box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
    }

    /* Buttons */
    .btn-primary {
        background-color: var(--sulis-primary);
        border-color: var(--sulis-primary);
    }

    .btn-primary:hover {
        background-color: #1a252f;
        border-color: #1a252f;
    }

    .btn-success {
        background-color: var(--sulis-success);
        border-color: var(--sulis-success);
    }

    .btn-danger {
        background-color: var(--sulis-danger);
        border-color: var(--sulis-danger);
    }

    /* Table Styling */
    .table {
        border-collapse: separate;
        border-spacing: 0;
        width: 100%;
    }

    .table th {
        background-color: var(--sulis-light);
        color: var(--sulis-dark);
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 0.5px;
    }

    .table td, .table th {
        padding: 0.75rem;
        vertical-align: middle;
        border: 1px solid #e2e8f0;
    }

    /* Section Headers */
    .section-header {
        color: var(--sulis-primary);
        font-weight: 600;
        margin-bottom: 1.5rem;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid var(--sulis-light);
    }

    /* Input Group */
    .input-group-text {
        background-color: var(--sulis-light);
        color: var(--sulis-dark);
        border: 1px solid #d1d5db;
    }

    /* Alert Styling */
    .alert {
        border-radius: 4px;
        border: none;
    }

    .alert-info {
        background-color: #e8f4fd;
        color: #0c63e4;
    }

    /* Badges */
    .badge {
        font-weight: 500;
        padding: 0.35em 0.65em;
    }

    .badge-success {
        background-color: var(--sulis-success);
    }

    .badge-danger {
        background-color: var(--sulis-danger);
    }

    /* Responsive Adjustments */
    @media (max-width: 768px) {
        .card-body {
            padding: 1rem;
        }
        
        .form-control, .form-select {
            font-size: 0.9rem;
        }
    }

    /* Invoice Items Table Font Size */
    #invoiceItemsSection .table {
        font-size: 0.85rem;
    }

    #invoiceItemsSection .table th {
        font-size: 0.75rem;
    }

    #invoiceItemsSection .table td {
        font-size: 0.75rem;
    }

    #invoiceItemsSection .form-control, 
    #invoiceItemsSection .form-select {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
    }
</style>
@endpush

@section('content')
<div class="container-fluid py-4" style="background-color: #f8fafc;">
    <div class="row justify-content-center">
        <div class="col-12">
            <form id="invoiceForm" method="POST" action="{{ route('invoices.bulk.update', $invoice->BulkInvoiceID) }}" class="needs-validation" novalidate enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <input type="hidden" name="CompanyID" id="CompanyID" value="{{ $invoice->CompanyID }}">
                <input type="hidden" name="BulkInvoiceID" value="{{ $invoice->BulkInvoiceID }}">
                
                <!-- Header Card -->
                <div class="card mb-4">
                    <div class="card-header bg-warning text-white">
                        <h2 class="h4 mb-0 text-center">EDIT BULK INVOICE #{{ $invoice->InvoiceNo }}</h2>
                    </div>
                    
                    <div class="card-body">
                    @if($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <!-- Basic Information Section -->
                    <div class="row mb-4">
                     @if(isset($userCompany) && $userCompany)
                        <input type="hidden" name="CompanyID" id="CompanyID" value="{{ $userCompany->CompanyID }}">
                        <input type="hidden" class="form-control" value="{{ $userCompany->CompanyName }}" readonly>
                    @endif
                        
                        <!-- Property -->
                        <div class="col-md-4 mb-3">
                            <label for="PropID" class="form-label">Property</label>
                            <select name="PropID" id="PropID" class="form-select" onchange="loadPreviousReadings(this.value)" required>
                                <option value="" disabled>Select Property</option>
                                @foreach($properties as $id => $name)
                                    <option value="{{ $id }}" 
                                        {{ $invoice->PropID == $id ? 'selected' : '' }}
                                        data-prev-reading1="{{ $invoice->PreviousReading1 }}"
                                        data-prev-reading2="{{ $invoice->PreviousReading2 }}"
                                        data-curr-reading1="{{ $invoice->CurrentReading1 }}"
                                        data-curr-reading2="{{ $invoice->CurrentReading2 }}"
                                        data-billing-period="{{ $invoice->BillingPeriod }}">
                                        {{ $name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Billing Period -->
                        <div class="col-md-4 mb-3">
                            <label for="BillingPeriod" class="form-label">Billing Period</label>
                            <input type="month" class="form-control bg-light" id="BillingPeriod" name="BillingPeriod" 
                                   value="{{ $invoice->BillingPeriod ? substr($invoice->BillingPeriod, 0, 4) . '-' . substr($invoice->BillingPeriod, 4, 2) : '' }}" 
                                   required readonly>
                        </div>

                        <!-- Consumption Type -->
                        <div class="col-md-4 mb-3">
                            <label for="consType" class="form-label">Consumption Type</label>
                            <select name="cons_type" id="consType" class="form-select @error('cons_type') is-invalid @enderror" required>
                                <option value="">Select Type</option>
                                @foreach($consumptionTypes as $type)
                                    <option value="{{ $type->tID }}" {{ old('cons_type', $invoice->ConsType) == $type->tID ? 'selected' : '' }}>
                                        {{ $type->ConsType }}
                                    </option>
                                @endforeach
                            </select>
                            @error('cons_type')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <!-- Invoice Details Section -->
                    <div class="row mb-4">
                        <!-- Invoice Number -->
                        <div class="col-md-4 mb-3">
                            <label for="invoiceNo" class="form-label">Invoice No. <span class="text-danger">*</span></label>
                            <input type="text" id="invoiceNo" name="InvoiceNo" 
                                class="form-control" required
                                pattern="[A-Za-z0-9-/]+"
                                title="Please enter a valid invoice number"
                                value="{{ old('InvoiceNo', $invoice->InvoiceNo) }}">
                            <div class="invalid-feedback">
                                Please provide a valid invoice number.
                            </div>
                        </div>

                        <!-- Invoice Date -->
                        <div class="col-md-4 mb-3">
                            <label for="invoiceDate" class="form-label">Invoice Date</label>
                            <input type="date" id="invoiceDate" name="InvoiceDate" 
                                class="form-control" 
                                value="{{ old('InvoiceDate', $invoice->InvoiceDate ? \Carbon\Carbon::parse($invoice->InvoiceDate)->format('Y-m-d') : '') }}" required>
                        </div>

                        <!-- Due Date -->
                        <div class="col-md-4 mb-3">
                            <label for="dueDate" class="form-label">Due Date</label>
                            <input type="date" id="dueDate" name="DueDate" 
                                class="form-control" 
                                value="{{ old('DueDate', $invoice->DueDate ? \Carbon\Carbon::parse($invoice->DueDate)->format('Y-m-d') : '') }}" required>
                        </div>
                    </div>

                    <!-- Meter Readings Section -->
                    <div class="mb-4">
                        <h3 class="h5 mb-3 pb-2 border-bottom">Meter Readings</h3>
                        <div class="row">
                            <!-- Previous Reading 1 -->
                            <div class="col-md-3 mb-3">
                                <label for="previousReading1" class="form-label">Previous Reading 1</label>
                                <input type="number" id="previousReading1" name="PreviousReading1" 
                                    class="form-control" 
                                    oninput="calculateConsumption()"
                                    value="{{ old('PreviousReading1', $invoice->PreviousReading1) }}">
                            </div>
                            
                            <!-- Current Reading 1 -->
                            <div class="col-md-3 mb-3">
                                <label for="currentReading1" class="form-label">Current Reading 1</label>
                                <input type="number" id="currentReading1" name="CurrentReading1" 
                                    class="form-control" 
                                    oninput="calculateConsumption()"
                                    value="{{ old('CurrentReading1', $invoice->CurrentReading1) }}">
                            </div>
                            
                            <!-- Previous Reading 2 -->
                            <div class="col-md-3 mb-3">
                                <label for="previousReading2" class="form-label">Previous Reading 2</label>
                                <input type="number" id="previousReading2" name="PreviousReading2" 
                                    class="form-control" 
                                    oninput="calculateConsumption()"
                                    value="{{ old('PreviousReading2', $invoice->PreviousReading2) }}">
                            </div>
                            
                            <!-- Current Reading 2 -->
                            <div class="col-md-3 mb-3">
                                <label for="currentReading2" class="form-label">Current Reading 2</label>
                                <input type="number" id="currentReading2" name="CurrentReading2" 
                                    class="form-control" 
                                    oninput="calculateConsumption()"
                                    value="{{ old('CurrentReading2', $invoice->CurrentReading2) }}">
                            </div>
                            
                        </div>
                    </div>

                <!-- Amounts Section -->
<div class="mb-4">
    <h3 class="h5 mb-3 pb-2 border-bottom">Amount Details</h3>
    <div class="row">
        <!-- Invoice Amount -->
        <div class="col-md-3 mb-3">
            <label for="invoiceAmount" class="form-label">Invoice Amount</label>
            <div class="input-group">
                <span class="input-group-text">KSh</span>
                <input type="number" id="invoiceAmount" name="InvoiceAmount" 
                    class="form-control bg-light" required
                    value="{{ old('InvoiceAmount', number_format($invoice->InvoiceAmount, 2, '.', '')) }}" readonly>
            </div>
        </div>

        <!-- Consumption -->
        <div class="col-md-3 mb-3">
            <label for="consumption" class="form-label">Consumption</label>
            <input type="number" id="consumption" name="Consumption" 
                class="form-control bg-light" 
                value="{{ old('Consumption', $invoice->Consumption) }}" step="1" min="0" readonly>
        </div>

        <!-- Consumption Amount -->
        <div class="col-md-3 mb-3">
            <label for="consAmount" class="form-label">Cons. Amount</label>
            <div class="input-group">
                <span class="input-group-text">KSh</span>
                <input type="number" id="consAmount" name="ConsAmount" 
                    class="form-control" 
                    value="{{ old('ConsAmount', number_format($invoice->ConsAmount, 2, '.', '')) }}" required
                    onchange="updateInvoiceAmount()">
            </div>
        </div>

        <!-- Fixed Amount -->
        <div class="col-md-3 mb-3">
            <label for="fixedAmount" class="form-label">Fixed Amount</label>
            <div class="input-group">
                <span class="input-group-text">KSh</span>
                <input type="number" id="fixedAmount" name="FixedAmount" 
                    class="form-control" 
                    value="{{ old('FixedAmount', number_format($invoice->FixedAmount, 2, '.', '')) }}" required
                    onchange="updateInvoiceAmount()">
            </div>
        </div>
    </div>
</div>

                 <!-- Invoice Items Section (initially hidden) -->
<div id="invoiceItemsSection" class="mb-4 d-none">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="d-inline-flex align-items-center px-3 py-1 bg-primary text-white rounded">
            <span class="fw-medium">Invoice Items</span>
        </div>
    </div>
    
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>Description</th>
                    <th>Unit Price</th>
                    <th>Amount</th>
                </tr>
            </thead>
            <tbody>
                @php
                    $totalAmount = 0;
                @endphp
                @foreach($invoice->bulkInvoiceLines as $index => $line)
                    <tr class="invoice-item">
                        <td>
                            <input type="hidden" name="items[{{ $index }}][BulkLineID]" value="{{ $line->BulkLineID }}">
                            {{ $line->BulkLineID }}
                        </td>
                        <input type="hidden" name="items[{{ $index }}][BulkCategID]" value="{{ $line->BulkCategID }}">
                        <td>
                            <input type="hidden" name="items[{{ $index }}][BulkLineDesc]" value="{{ $line->BulkLineDesc }}">
                            {{ $line->BulkLineDesc }}
                        </td>
                        <td>
                            <input type="number" class="form-control form-control-sm unit-price" 
                                   name="BulkLineUnitPrice[]" value="{{ number_format($line->BulkLineUnitPrice, 2, '.', '') }}" step="0.01" min="0" 
                                   onchange="calculateLineTotal(this)">
                        </td>
                        <td>
                            <input type="number" class="form-control form-control-sm line-total" 
                                   name="BulkLineAmount[]" value="{{ number_format($line->BulkLineAmount, 2, '.', '') }}" step="0.01" min="0"
                                   onchange="updateLineFromAmount(this)">
                        </td>
                    </tr>
                @endforeach
                <tr class="table-active fw-bold">
                    <td colspan="2" class="text-end">Total:</td>
                    <td colspan="2" class="text-end pe-3" id="invoiceTotal">KSh 0.00</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
                   <!-- Additional Invoice Items Section (initially hidden) -->
<div id="additionalChargesSection" class="mb-4 d-none">
    <!-- <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="d-inline-flex align-items-center px-3 py-1 bg-primary text-white rounded">
            <span class="fw-medium">Additional Charges</span>
        </div> -->
    </div>
    
  
</div>

                  <!-- Form Actions -->
<div class="d-flex justify-content-end gap-2 pt-3 mt-2 border-top">
    <a href="{{ route('invoices.bulk.show', $invoice->BulkInvoiceID) }}" 
       class="btn btn-danger">
        <i class="bi bi-x-circle me-1"></i> Cancel
    </a>
    <button type="button" class="btn btn-secondary" onclick="validateAndSubmit()">
        <i class="bi bi-save me-1"></i> Save Changes
    </button>
</div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

<!-- Hidden field to store the calculated total -->
<input type="hidden" id="calculatedTotal" name="calculated_total" value="{{ number_format($invoice->InvoiceAmount, 2, '.', '') }}">

@push('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Template for additional invoice items -->
<script type="text/template" id="additionalItemTemplate">
    <tr class="additional-item">
        <td>
            <input type="hidden" name="optionalItems[__INDEX__][BulkCategID]" value="ADD">
            <select name="optionalItems[__INDEX__][BulkLineDesc]" class="form-select form-select-sm item-description" required>
                <option value="">Select Item</option>
                <option value="Rent">Rent</option>
                <option value="Car Parking">Car Parking</option>
                <option value="Service Charge">Service Charge</option>
                <option value="Water Bill">Water Bill</option>
                <option value="Other">Other</option>
            </select>
        </td>
        <td>
            <input type="number" name="optionalItems[__INDEX__][BulkLineUnitPrice]" 
                   class="form-control form-control-sm unit-price" 
                   min="0" step="0.01" required 
                   onchange="calculateLineTotal(this)">
        </td>
        <td>
            <input type="number" name="optionalItems[__INDEX__][BulkLineAmount]" 
                   class="form-control form-control-sm line-total" readonly>
        </td>
        <td class="text-end">
            <button type="button" class="btn btn-sm btn-link text-danger remove-item">
                <i class="bi bi-trash"></i>
            </button>
        </td>
    </tr>
</script>
<script>
    // Function to toggle invoice sections based on form state
  function toggleInvoiceSections() {
    // Get company ID from the hidden input or from PHP variable
    const companyId = document.getElementById('CompanyID') ? document.getElementById('CompanyID').value : '{{ $userCompany->CompanyID ?? '' }}';
    const propertyId = $('#PropID').val();
    const isComplete = companyId && propertyId;
    
    console.log('Company ID:', companyId);  // Debug log
    console.log('Property ID:', propertyId); // Debug log
    
    if (isComplete) {
        $('#invoiceItemsSection, #additionalChargesSection').removeClass('d-none');
    } else {
        $('#invoiceItemsSection, #additionalChargesSection').addClass('d-none');
    }
}

// Call toggleInvoiceSections when the page loads and when property changes
$(document).ready(function() {
    toggleInvoiceSections(); // Initial check
    $('#PropID').on('change', toggleInvoiceSections);
});

    // Initialize event listeners
    $(document).ready(function() {
        // Toggle sections when page loads
        toggleInvoiceSections();
        
        // Toggle sections when company or property changes
        $('#CompanyID, #PropID').on('change', function() {
            toggleInvoiceSections();
        });
    });

    // Add additional invoice item
    $(document).on('click', '#addAdditionalItemBtn', function() {
        const template = $('#additionalItemTemplate').html();
        const index = $('.additional-item').length;
        const newRow = template.replace(/__INDEX__/g, index);
        $('#additionalItemsTableBody').append(newRow);
        updateInvoiceTotal();
    });

    // Remove item
    $(document).on('click', '.remove-item', function() {
        $(this).closest('tr').remove();
        updateInvoiceTotal();
        // Re-index the remaining items
        $('.additional-item').each(function(index) {
            $(this).find('input, select').each(function() {
                const name = $(this).attr('name');
                if (name) {
                    $(this).attr('name', name.replace(/\[\d+\]/, '[' + index + ']'));
                }
            });
        });
    });

    // Calculate line total for additional items
    function calculateLineTotal(input) {
        const row = $(input).closest('tr');
        const unitPrice = parseFloat(row.find('.unit-price').val()) || 0;
        const quantity = 1; // Default quantity is 1 for additional items
        const total = unitPrice * quantity;
        
        row.find('.line-total').val(total.toFixed(2));
        updateInvoiceTotal();
    }

    // Update the total invoice amount
    function updateInvoiceTotal() {
        let total = parseFloat($('#invoiceAmount').val()) || 0;
        
        // Add up all additional items
        $('.additional-item').each(function() {
            const amount = parseFloat($(this).find('.line-total').val()) || 0;
            total += amount;
        });
        
        // Update the total amount field
        $('#invoiceAmount').val(total.toFixed(2));
    }

    // Function to calculate consumption based on meter readings
    function calculateConsumption() {
        try {
            // Get input values
            const prev1 = Number(document.getElementById('previousReading1').value) || 0;
            const curr1 = Number(document.getElementById('currentReading1').value) || 0;
            const prev2 = Number(document.getElementById('previousReading2').value) || 0;
            const curr2 = Number(document.getElementById('currentReading2').value) || 0;
            
            // Calculate consumption for both meters (ensure no negative values and round down to whole number)
            const consumption1 = Math.max(0, Math.floor(curr1 - prev1));
            const consumption2 = Math.max(0, Math.floor(curr2 - prev2));
            
            // Total consumption is the sum of both meters as a whole number
            const totalConsumption = consumption1 + consumption2;
            
            // Update the consumption field
            const consumptionField = document.getElementById('consumption');
            if (consumptionField) {
                consumptionField.value = totalConsumption;
                
                // Trigger input event to update any dependent fields
                const event = new Event('input', { bubbles: true });
                consumptionField.dispatchEvent(event);
            }
            
            return totalConsumption;
        } catch (error) {
            console.error('Error in calculateConsumption:', error);
            return 0;
        }
    }
    
    // Function to update consumption amount based on consumption and rate
    function updateConsumptionAmount(consumption) {
        const rate = parseFloat(document.getElementById('rate')?.value) || 0;
        const amount = (consumption * rate).toFixed(2);
        const consAmountField = document.getElementById('consAmount');
        if (consAmountField) {
            consAmountField.value = amount;
            // Trigger input event to update any dependent fields
            const event = new Event('input', { bubbles: true });
            consAmountField.dispatchEvent(event);
        }
        
        // Also update the total invoice amount
        updateInvoiceAmount();
    }
    
    // Function to update total invoice amount
    function updateInvoiceAmount() {
        const consAmount = parseFloat(document.getElementById('consAmount')?.value) || 0;
        const fixedAmount = parseFloat(document.getElementById('fixedAmount')?.value) || 0;
        const total = (consAmount + fixedAmount).toFixed(2);
        
        const invoiceAmountField = document.getElementById('invoiceAmount');
        if (invoiceAmountField) {
            invoiceAmountField.value = total;
            
            // Update the display to show the new amount
            const displayField = document.getElementById('invoiceAmountDisplay');
            if (displayField) {
                displayField.textContent = 'KSh ' + total;
            }
        }
        
        // Update the invoice total (items table total)
        updateInvoiceTotal();
    }

    // Function to validate and submit the form
    function validateAndSubmit() {
        const invoiceAmount = parseFloat($('#invoiceAmount').val()) || 0;
        const calculatedTotal = parseFloat($('#calculatedTotal').val()) || 0;
        
        // Check if amounts match (with a small tolerance for floating point precision)
        if (Math.abs(invoiceAmount - calculatedTotal) > 0.01) {
            Swal.fire({
                icon: 'error',
                title: 'Amount Mismatch',
                html: `The total amount (KSh ${calculatedTotal.toFixed(2)}) does not match the invoice amount (KSh ${invoiceAmount.toFixed(2)}).<br><br>Please ensure the amounts match before saving.`,
                confirmButtonColor: '#d33',
                confirmButtonText: 'OK'
            });
            return false;
        }
        
        // If amounts match, submit the form
        document.getElementById('invoiceForm').submit();
    }

    // Function to calculate line total based on unit price and update invoice total
    function calculateLineTotal(input) {
        const row = $(input).closest('tr');
        const unitPrice = parseFloat($(input).val()) || 0;
        const quantity = 1; // Assuming quantity is always 1 for these items
        const lineTotal = unitPrice * quantity;
        
        // Update line total
        const lineTotalInput = row.find('.line-total');
        lineTotalInput.val(lineTotal.toFixed(2));
        
        // Update the corresponding amount field
        const amountInput = row.find('input[name^="BulkLineAmount"]');
        if (amountInput.length) {
            amountInput.val(lineTotal.toFixed(2));
        }
        
        // Update invoice total
        updateInvoiceTotal();
    }
    
    // Function to handle direct amount edits
    function updateLineFromAmount(input) {
        // Just update the total when amount is edited directly
        // Don't modify the unit price
        updateInvoiceTotal();
    }
    
    // Function to update the invoice total
    function updateInvoiceTotal() {
        let total = 0;
        $('.line-total').each(function() {
            const value = parseFloat($(this).val()) || 0;
            total += value;
            // Ensure the displayed value is always properly formatted
            $(this).val(value.toFixed(2));
        });
        
        // Update the total display in the items table
        const formattedTotal = total.toFixed(2);
        $('#invoiceTotal').text('KSh ' + formattedTotal);
        
        // Update the hidden calculated total field
        $('#calculatedTotal').val(formattedTotal);
        
        return parseFloat(formattedTotal);
    }
    
    // Function to calculate amount based on unit price and quantity
    function calculateAmount(input, index) {
        const unitPrice = parseFloat(input.value) || 0;
        // If you have a quantity field, include it in the calculation
        // const quantity = parseFloat($(`input[name='items[${index}][quantity]']`).val()) || 1;
        // const amount = unitPrice * quantity;
        
        // For now, just update the amount to match the unit price
        const amount = unitPrice;
        
        // Update the amount field
        $(`input[name='items[${index}][BulkLineAmount]']`).val(amount.toFixed(2));
    }
    
    // Function to update unit price when amount is changed
    function updateUnitPrice(input, index) {
        const amount = parseFloat(input.value) || 0;
        // If you have a quantity field, include it in the calculation
        // const quantity = parseFloat($(`input[name='items[${index}][quantity]']`).val()) || 1;
        // const unitPrice = amount / quantity;
        
        // For now, just update the unit price to match the amount
        const unitPrice = amount;
        
        // Update the unit price field
        $(`input[name='items[${index}][BulkLineUnitPrice]']`).val(unitPrice.toFixed(2));
    }

    // Function to initialize consumption calculation
    function initializeConsumptionCalculation() {
        try {
            // Add input event listeners to all meter reading fields
            const meterInputs = [
                'previousReading1', 'currentReading1',
                'previousReading2', 'currentReading2'
            ];
            
            meterInputs.forEach(id => {
                const input = document.getElementById(id);
                if (input) {
                    // Remove any existing listeners to prevent duplicates
                    const newInput = input.cloneNode(true);
                    input.parentNode.replaceChild(newInput, input);
                    
                    // Add new listener
                    newInput.addEventListener('input', calculateConsumption);
                }
            });
            
            // Initial calculation
            calculateConsumption();
        } catch (error) {
            console.error('Error initializing consumption calculation:', error);
        }
    }

    // Load previous readings when a property is selected
    function loadPreviousReadings(propId) {
        if (!propId) return;
        
        // Get the selected property option
        const selectedOption = $(`#PropID option[value="${propId}"]`);
        
        if (selectedOption.length) {
            // Update the billing period
            const billingPeriod = selectedOption.data('billing-period');
            if (billingPeriod) {
                const year = billingPeriod.substring(0, 4);
                const month = billingPeriod.substring(4, 6);
                $('#BillingPeriod').val(`${year}-${month}`);
            }
            
            // Update the meter readings if they exist
            if (selectedOption.data('prev-reading1') !== '') {
                $('#previousReading1').val(selectedOption.data('prev-reading1'));
            }
            if (selectedOption.data('prev-reading2') !== '') {
                $('#previousReading2').val(selectedOption.data('prev-reading2'));
            }
            if (selectedOption.data('curr-reading1') !== '') {
                $('#currentReading1').val(selectedOption.data('curr-reading1'));
            }
            if (selectedOption.data('curr-reading2') !== '') {
                $('#currentReading2').val(selectedOption.data('curr-reading2'));
            }
            
            // Recalculate consumption
            calculateConsumption();
        }
    }
    
    // Initialize the form
    $(document).ready(function() {
        // Format all numeric inputs on page load
        $('.line-amount').each(function() {
            const value = parseFloat($(this).val()) || 0;
            $(this).val(parseFloat(value).toFixed(2));
        });
        
        // Format the amount fields on page load
        $('#ConsAmount, #FixedAmount, #InvoiceAmount').each(function() {
            const value = parseFloat($(this).val()) || 0;
            $(this).val(parseFloat(value).toFixed(2));
        });
        
        // Calculate initial totals
        calculateConsumption();
        updateInvoiceAmount();
        calculateInvoiceTotal();
        
        // Set up form submission handler
        $('form').on('submit', function(e) {
            e.preventDefault();
            
            // Ensure all amounts are properly formatted before submission
            $('.line-amount, #ConsAmount, #FixedAmount').each(function() {
                const value = parseFloat($(this).val()) || 0;
                $(this).val(parseFloat(value).toFixed(2));
            });
            
            // Get the invoice amount and line items total
            const invoiceAmount = parseFloat($('#InvoiceAmount').val()) || 0;
            const lineItemsTotal = parseFloat(calculateInvoiceTotal()) || 0;
            
            // Validate that the invoice amount is greater than 0
            if (invoiceAmount <= 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Amount',
                    text: 'Invoice amount must be greater than 0.',
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'OK'
                });
                return false;
            }
            
            // Validate that invoice amount matches line items total
            if (Math.abs(invoiceAmount - lineItemsTotal) > 0.01) {
                Swal.fire({
                    icon: 'error',
                    title: 'Amount Mismatch',
                    html: `The total amount (KSh ${lineItemsTotal.toFixed(2)}) does not match the invoice amount (KSh ${invoiceAmount.toFixed(2)}).<br><br>Please ensure the amounts match before saving.`,
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'OK'
                });
                return false;
            }
            
            // If validation passes, submit the form via AJAX
            const form = this;
            const formData = new FormData(form);
            
            // Format dates properly
            const billingPeriod = document.getElementById('BillingPeriod').value.replace(/-/g, '');
            const invoiceDate = document.getElementById('InvoiceDate').value || new Date().toISOString().split('T')[0];
            const dueDate = document.getElementById('DueDate').value || new Date().toISOString().split('T')[0];
            
            // Get all form data
            const formDataObj = {};
            formData.forEach((value, key) => {
                // Handle array fields (like items[])
                if (key.endsWith('[]')) {
                    const baseKey = key.replace('[]', '');
                    if (!formDataObj[baseKey]) {
                        formDataObj[baseKey] = [];
                    }
                    formDataObj[baseKey].push(value);
                } else {
                    formDataObj[key] = value;
                }
            });
            
            // Ensure required fields are set
            formDataObj['BillingPeriod'] = billingPeriod;
            formDataObj['InvoiceDate'] = invoiceDate;
            formDataObj['DueDate'] = dueDate;
            
            // Convert to URL-encoded string
            const urlEncodedData = Object.entries(formDataObj)
                .map(([key, value]) => {
                    if (Array.isArray(value)) {
                        return value.map(v => `${encodeURIComponent(key)}[]=${encodeURIComponent(v)}`).join('&');
                    }
                    return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
                })
                .join('&');
            
            // Show loading state
            const submitButton = $(form).find('button[type="submit"]');
            const originalButtonText = submitButton.html();
            submitButton.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');
            
            // Submit the form via AJAX
            fetch(form.action, {
                method: 'POST',
                body: urlEncodedData,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                    'X-HTTP-Method-Override': 'PUT' // For Laravel to recognize PUT method
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || 'An error occurred while saving the invoice');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message || 'Invoice updated successfully!',
                        confirmButtonColor: '#3085d6',
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed && data.redirect) {
                            window.location.href = data.redirect;
                        }
                    });
                } else {
                    throw new Error(data.message || 'Failed to update invoice');
                }
            })
            .catch(error => {
                console.error('Error updating invoice:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: error.message || 'An error occurred while updating the invoice.',
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'OK'
                });
                
                // Reset button state
                submitButton.prop('disabled', false).html(originalButtonText);
            });
        });
    });
</script>
@endpush

@if(session('success'))
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '{{ session('success') }}',
                confirmButtonColor: '#3085d6',
                confirmButtonText: 'OK'
            }).then((result) => {
                // Redirect to show page after success
                if (result.isConfirmed) {
                    window.location.href = "{{ route('invoices.bulk.show', $invoice->BulkInvoiceID) }}";
                }
            });
        });
    </script>
@endif

@endsection

@push('styles')
<style>
    .invoice-line td {
        vertical-align: middle;
    }
    .remove-line {
        padding: 0.25rem 0.5rem;
        line-height: 1;
    }
    .form-control-sm {
        min-height: calc(1.5em + 0.5rem + 2px);
    }
    /* Add Sulis colors and professional UI styles here */
    body {
        font-family: Arial, sans-serif;
        background-color: #f0f0f0;
    }
    .card {
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    .card-header {
        background-color: #337ab7;
        color: #fff;
        padding: 10px;
        border-bottom: 1px solid #ddd;
    }
    .card-body {
        padding: 20px;
    }
    .form-section {
        background-color: #f9f9f9;
        padding: 20px;
        border: 1px solid #ddd;
        border-radius: 10px;
        margin-bottom: 20px;
    }
    .section-title {
        font-weight: bold;
        font-size: 18px;
        margin-bottom: 10px;
    }
    .table-responsive {
        overflow-x: auto;
    }
    .table {
        border-collapse: collapse;
        width: 100%;
    }
    .table th, .table td {
        border: 1px solid #ddd;
        padding: 10px;
        text-align: left;
    }
    .table th {
        background-color: #f0f0f0;
    }
    .table td {
        background-color: #fff;
    }
    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }
    .btn-primary {
        background-color: #337ab7;
        color: #fff;
    }
    .btn-secondary {
        background-color: #666;
        color: #fff;
    }
</style>
@endpush

<!-- Hidden field to store the calculated total -->
<input type="hidden" id="calculatedTotal" name="calculated_total" value="0">

@push('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Template for additional invoice items -->
<script type="text/template" id="additionalItemTemplate">
    <tr class="additional-item">
        <td>
            <input type="hidden" name="optionalItems[__INDEX__][BulkCategID]" value="ADD">
            <select name="optionalItems[__INDEX__][BulkLineDesc]" class="form-select form-select-sm item-description" required>
                <option value="">Select Item</option>
                <option value="Rent">Rent</option>
                <option value="Car Parking">Car Parking</option>
                <option value="Service Charge">Service Charge</option>
                <option value="Water Bill">Water Bill</option>
                <option value="Other">Other</option>
            </select>
        </td>
        <td>
            <input type="number" name="optionalItems[__INDEX__][BulkLineUnitPrice]" 
                   class="form-control form-control-sm unit-price" 
                   min="0" step="0.01" required 
                   onchange="calculateLineTotal(this)">
        </td>
        <td>
            <input type="number" name="optionalItems[__INDEX__][BulkLineAmount]" 
                   class="form-control form-control-sm line-total" readonly>
        </td>
        <td class="text-end">
            <button type="button" class="btn btn-sm btn-link text-danger remove-item">
                <i class="bi bi-trash"></i>
            </button>
        </td>
    </tr>
</script>
<script>
    // Function to toggle invoice sections based on form state
  function toggleInvoiceSections() {
    // Get company ID from the hidden input or from PHP variable
    const companyId = document.getElementById('CompanyID') ? document.getElementById('CompanyID').value : '{{ $userCompany->CompanyID ?? '' }}';
    const propertyId = $('#PropID').val();
    const isComplete = companyId && propertyId;
    
    console.log('Company ID:', companyId);  // Debug log
    console.log('Property ID:', propertyId); // Debug log
    
    if (isComplete) {
        $('#invoiceItemsSection, #additionalChargesSection').removeClass('d-none');
    } else {
        $('#invoiceItemsSection, #additionalChargesSection').addClass('d-none');
    }
}

// Call toggleInvoiceSections when the page loads and when property changes
$(document).ready(function() {
    toggleInvoiceSections(); // Initial check
    $('#PropID').on('change', toggleInvoiceSections);
});

    // Initialize event listeners
    $(document).ready(function() {
        // Toggle sections when page loads
        toggleInvoiceSections();
        
        // Toggle sections when company or property changes
        $('#CompanyID, #PropID').on('change', function() {
            toggleInvoiceSections();
        });
    });

    // Add additional invoice item
    $(document).on('click', '#addAdditionalItemBtn', function() {
        const template = $('#additionalItemTemplate').html();
        const index = $('.additional-item').length;
        const newRow = template.replace(/__INDEX__/g, index);
        $('#additionalItemsTableBody').append(newRow);
        updateInvoiceTotal();
    });

    // Remove item
    $(document).on('click', '.remove-item', function() {
        $(this).closest('tr').remove();
        updateInvoiceTotal();
        // Re-index the remaining items
        $('.additional-item').each(function(index) {
            $(this).find('input, select').each(function() {
                const name = $(this).attr('name');
                if (name) {
                    $(this).attr('name', name.replace(/\[\d+\]/, '[' + index + ']'));
                }
            });
        });
    });

    // Calculate line total for additional items
    function calculateLineTotal(input) {
        const row = $(input).closest('tr');
        const unitPrice = parseFloat(row.find('.unit-price').val()) || 0;
        const quantity = 1; // Default quantity is 1 for additional items
        const total = unitPrice * quantity;
        
        row.find('.line-total').val(total.toFixed(2));
        updateInvoiceTotal();
    }

    // Update the total invoice amount
    function updateInvoiceTotal() {
        let total = parseFloat($('#invoiceAmount').val()) || 0;
        
        // Add up all additional items
        $('.additional-item').each(function() {
            const amount = parseFloat($(this).find('.line-total').val()) || 0;
            total += amount;
        });
        
        // Update the total amount field
        $('#invoiceAmount').val(total.toFixed(2));
    }

    // Function to calculate consumption based on meter readings
    function calculateConsumption() {
        try {
            // Get input values
            const prev1 = Number(document.getElementById('previousReading1').value) || 0;
            const curr1 = Number(document.getElementById('currentReading1').value) || 0;
            const prev2 = Number(document.getElementById('previousReading2').value) || 0;
            const curr2 = Number(document.getElementById('currentReading2').value) || 0;
            
            // Calculate consumption for both meters (ensure no negative values and round down to whole number)
            const consumption1 = Math.max(0, Math.floor(curr1 - prev1));
            const consumption2 = Math.max(0, Math.floor(curr2 - prev2));
            
            // Total consumption is the sum of both meters as a whole number
            const totalConsumption = consumption1 + consumption2;
            
            // Update the consumption field
            const consumptionField = document.getElementById('consumption');
            if (consumptionField) {
                consumptionField.value = totalConsumption;
                
                // Trigger input event to update any dependent fields
                const event = new Event('input', { bubbles: true });
                consumptionField.dispatchEvent(event);
            }
            
            return totalConsumption;
        } catch (error) {
            console.error('Error in calculateConsumption:', error);
            return 0;
        }
    }
    
    // Function to update consumption amount based on consumption and rate
    function updateConsumptionAmount(consumption) {
        const rate = parseFloat(document.getElementById('rate')?.value) || 0;
        const amount = (consumption * rate).toFixed(2);
        const consAmountField = document.getElementById('consAmount');
        if (consAmountField) {
            consAmountField.value = amount;
            // Trigger input event to update any dependent fields
            const event = new Event('input', { bubbles: true });
            consAmountField.dispatchEvent(event);
        }
        
        // Also update the total invoice amount
        updateInvoiceAmount();
    }
    
    // Function to update total invoice amount
    function updateInvoiceAmount() {
        const consAmount = parseFloat(document.getElementById('consAmount')?.value) || 0;
        const fixedAmount = parseFloat(document.getElementById('fixedAmount')?.value) || 0;
        const total = (consAmount + fixedAmount).toFixed(2);
        
        const invoiceAmountField = document.getElementById('invoiceAmount');
        if (invoiceAmountField) {
            invoiceAmountField.value = total;
            
            // Update the display to show the new amount
            const displayField = document.getElementById('invoiceAmountDisplay');
            if (displayField) {
                displayField.textContent = 'KSh ' + total;
            }
        }
        
        // Update the invoice total (items table total)
        updateInvoiceTotal();
    }

    // Function to validate and submit the form
    function validateAndSubmit() {
        const invoiceAmount = parseFloat($('#invoiceAmount').val()) || 0;
        const calculatedTotal = parseFloat($('#calculatedTotal').val()) || 0;
        
        // Check if amounts match (with a small tolerance for floating point precision)
        if (Math.abs(invoiceAmount - calculatedTotal) > 0.01) {
            Swal.fire({
                icon: 'error',
                title: 'Amount Mismatch',
                html: `The total amount (KSh ${calculatedTotal.toFixed(2)}) does not match the invoice amount (KSh ${invoiceAmount.toFixed(2)}).<br><br>Please ensure the amounts match before saving.`,
                confirmButtonColor: '#d33',
                confirmButtonText: 'OK'
            });
            return false;
        }
        
        // If amounts match, submit the form
        document.getElementById('invoiceForm').submit();
    }

    // Function to calculate line total based on unit price and update invoice total
    function calculateLineTotal(input) {
        const row = $(input).closest('tr');
        const unitPrice = parseFloat($(input).val()) || 0;
        const quantity = 1; // Assuming quantity is always 1 for these items
        const lineTotal = unitPrice * quantity;
        
        // Update line total
        const lineTotalInput = row.find('.line-total');
        lineTotalInput.val(lineTotal.toFixed(2));
        
        // Update the corresponding amount field
        const amountInput = row.find('input[name^="BulkLineAmount"]');
        if (amountInput.length) {
            amountInput.val(lineTotal.toFixed(2));
        }
        
        // Update invoice total
        updateInvoiceTotal();
    }
    
    // Function to handle direct amount edits
    function updateLineFromAmount(input) {
        // Just update the total when amount is edited directly
        // Don't modify the unit price
        updateInvoiceTotal();
    }
    
    // Function to update the invoice total
    function updateInvoiceTotal() {
        let total = 0;
        $('.line-total').each(function() {
            const value = parseFloat($(this).val()) || 0;
            total += value;
            // Ensure the displayed value is always properly formatted
            $(this).val(value.toFixed(2));
        });
        
        // Update the total display in the items table
        const formattedTotal = total.toFixed(2);
        $('#invoiceTotal').text('KSh ' + formattedTotal);
        
        // Update the hidden calculated total field
        $('#calculatedTotal').val(formattedTotal);
        
        return parseFloat(formattedTotal);
    }
    
    // Function to calculate amount based on unit price and quantity
    function calculateAmount(input, index) {
        const unitPrice = parseFloat(input.value) || 0;
        // If you have a quantity field, include it in the calculation
        // const quantity = parseFloat($(`input[name='items[${index}][quantity]']`).val()) || 1;
        // const amount = unitPrice * quantity;
        
        // For now, just update the amount to match the unit price
        const amount = unitPrice;
        
        // Update the amount field
        $(`input[name='items[${index}][BulkLineAmount]']`).val(amount.toFixed(2));
    }
    
    // Function to update unit price when amount is changed
    function updateUnitPrice(input, index) {
        const amount = parseFloat(input.value) || 0;
        // If you have a quantity field, include it in the calculation
        // const quantity = parseFloat($(`input[name='items[${index}][quantity]']`).val()) || 1;
        // const unitPrice = amount / quantity;
        
        // For now, just update the unit price to match the amount
        const unitPrice = amount;
        
        // Update the unit price field
        $(`input[name='items[${index}][BulkLineUnitPrice]']`).val(unitPrice.toFixed(2));
    }

    // Function to initialize consumption calculation
    function initializeConsumptionCalculation() {
        try {
            // Add input event listeners to all meter reading fields
            const meterInputs = [
                'previousReading1', 'currentReading1',
                'previousReading2', 'currentReading2'
            ];
            
            meterInputs.forEach(id => {
                const input = document.getElementById(id);
                if (input) {
                    // Remove any existing listeners to prevent duplicates
                    const newInput = input.cloneNode(true);
                    input.parentNode.replaceChild(newInput, input);
                    
                    // Add new listener
                    newInput.addEventListener('input', calculateConsumption);
                }
            });
            
            // Initial calculation
            calculateConsumption();
        } catch (error) {
            console.error('Error initializing consumption calculation:', error);
        }
    }

    // Load previous readings when a property is selected
    function loadPreviousReadings(propId) {
        if (!propId) return;
        
        // Get the selected property option
        const selectedOption = $(`#PropID option[value="${propId}"]`);
        
        if (selectedOption.length) {
            // Update the billing period
            const billingPeriod = selectedOption.data('billing-period');
            if (billingPeriod) {
                const year = billingPeriod.substring(0, 4);
                const month = billingPeriod.substring(4, 6);
                $('#BillingPeriod').val(`${year}-${month}`);
            }
            
            // Update the meter readings if they exist
            if (selectedOption.data('prev-reading1') !== '') {
                $('#previousReading1').val(selectedOption.data('prev-reading1'));
            }
            if (selectedOption.data('prev-reading2') !== '') {
                $('#previousReading2').val(selectedOption.data('prev-reading2'));
            }
            if (selectedOption.data('curr-reading1') !== '') {
                $('#currentReading1').val(selectedOption.data('curr-reading1'));
            }
            if (selectedOption.data('curr-reading2') !== '') {
                $('#currentReading2').val(selectedOption.data('curr-reading2'));
            }
            
            // Recalculate consumption
            calculateConsumption();
        }
    }
    
    // Initialize the form
    $(document).ready(function() {
        // Format all numeric inputs on page load
        $('.line-amount').each(function() {
            const value = parseFloat($(this).val()) || 0;
            $(this).val(parseFloat(value).toFixed(2));
        });
        
        // Format the amount fields on page load
        $('#ConsAmount, #FixedAmount, #InvoiceAmount').each(function() {
            const value = parseFloat($(this).val()) || 0;
            $(this).val(parseFloat(value).toFixed(2));
        });
        
        // Calculate initial totals
        calculateConsumption();
        updateInvoiceAmount();
        calculateInvoiceTotal();
        
        // Set up form submission handler
        $('form').on('submit', function(e) {
            e.preventDefault();
            
            // Ensure all amounts are properly formatted before submission
            $('.line-amount, #ConsAmount, #FixedAmount').each(function() {
                const value = parseFloat($(this).val()) || 0;
                $(this).val(parseFloat(value).toFixed(2));
            });
            
            // Get the invoice amount and line items total
            const invoiceAmount = parseFloat($('#InvoiceAmount').val()) || 0;
            const lineItemsTotal = parseFloat(calculateInvoiceTotal()) || 0;
            
            // Validate that the invoice amount is greater than 0
            if (invoiceAmount <= 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Amount',
                    text: 'Invoice amount must be greater than 0.',
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'OK'
                });
                return false;
            }
            
            // Validate that invoice amount matches line items total
            if (Math.abs(invoiceAmount - lineItemsTotal) > 0.01) {
                Swal.fire({
                    icon: 'error',
                    title: 'Amount Mismatch',
                    html: `The total amount (KSh ${lineItemsTotal.toFixed(2)}) does not match the invoice amount (KSh ${invoiceAmount.toFixed(2)}).<br><br>Please ensure the amounts match before saving.`,
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'OK'
                });
                return false;
            }
            
            // If validation passes, submit the form via AJAX
            const form = this;
            const formData = new FormData(form);
            
            // Format dates properly
            const billingPeriod = document.getElementById('BillingPeriod').value.replace(/-/g, '');
            const invoiceDate = document.getElementById('InvoiceDate').value || new Date().toISOString().split('T')[0];
            const dueDate = document.getElementById('DueDate').value || new Date().toISOString().split('T')[0];
            
            // Get all form data
            const formDataObj = {};
            formData.forEach((value, key) => {
                // Handle array fields (like items[])
                if (key.endsWith('[]')) {
                    const baseKey = key.replace('[]', '');
                    if (!formDataObj[baseKey]) {
                        formDataObj[baseKey] = [];
                    }
                    formDataObj[baseKey].push(value);
                } else {
                    formDataObj[key] = value;
                }
            });
            
            // Ensure required fields are set
            formDataObj['BillingPeriod'] = billingPeriod;
            formDataObj['InvoiceDate'] = invoiceDate;
            formDataObj['DueDate'] = dueDate;
            
            // Convert to URL-encoded string
            const urlEncodedData = Object.entries(formDataObj)
                .map(([key, value]) => {
                    if (Array.isArray(value)) {
                        return value.map(v => `${encodeURIComponent(key)}[]=${encodeURIComponent(v)}`).join('&');
                    }
                    return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
                })
                .join('&');
            
            // Show loading state
            const submitButton = $(form).find('button[type="submit"]');
            const originalButtonText = submitButton.html();
            submitButton.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');
            
            // Submit the form via AJAX
            fetch(form.action, {
                method: 'POST',
                body: urlEncodedData,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                    'X-HTTP-Method-Override': 'PUT' // For Laravel to recognize PUT method
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || 'An error occurred while saving the invoice');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message || 'Invoice updated successfully!',
                        confirmButtonColor: '#3085d6',

                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed && data.redirect) {
                            window.location.href = data.redirect;
                        }
                    });
                } else {
                    throw new Error(data.message || 'Failed to update invoice');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                submitButton.prop('disabled', false).html(originalButtonText);
                
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message || 'An error occurred while saving the invoice. Please try again.',
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'OK'
                });
            });
        });
        
        // Set up input event listeners for meter readings
        $('#previousReading1, #currentReading1, #previousReading2, #currentReading2').on('input', calculateConsumption);
        
        // Set up event listeners for amount fields
        $('#ConsAmount, #FixedAmount').on('input', updateInvoiceAmount);
        
        // Initialize the VAT amount on page load
        updateInvoiceAmount();
        
        // Set up input event listeners for line amounts
        $('.line-amount').on('input', function() {
            updateLineFromAmount(this);
        });
    });
</script>
@endpush
