@extends('layouts.app')

@section('title', 'Create New Invoice')

@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.store') }}" class="needs-validation" novalidate enctype="multipart/form-data">
                @csrf
                
                <!-- Header Card -->
                <div class="card mb-4">
                    <div class="card-header bg-warning text-white">
                        <h2 class="h4 mb-0 text-center">NEW BULK INVOICE</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" onchange="toggleInvoiceSections(); loadPreviousReadings(this.value);" class="form-select" required>
                                <option value="" selected disabled>Select Property</option>
                                @if(isset($properties) && count($properties) > 0)
                                    @foreach($properties as $id => $name)
                                        @php
                                            $previousReading = $previousReadings[$id] ?? null;
                                            $prevReading1 = $previousReading ? $previousReading->PreviousReading1 : '';
                                            $prevReading2 = $previousReading ? $previousReading->PreviousReading2 : '';
                                            $currentReading1 = $previousReading ? $previousReading->CurrentReading1 : '';
                                            $currentReading2 = $previousReading ? $previousReading->CurrentReading2 : '';
                                        @endphp
                                        <option value="{{ $id }}" 
                                            data-prev-reading1="{{ $prevReading1 }}"
                                            data-prev-reading2="{{ $prevReading2 }}"
                                            data-curr-reading1="{{ $currentReading1 }}"
                                            data-curr-reading2="{{ $currentReading2 }}"
                                            data-billing-period="{{ $previousReading ? $previousReading->BillingPeriod : '' }}">
                                            {{ $name }}
                                        </option>
                                    @endforeach
                                @else
                                    <option value="" disabled>No properties found</option>
                                @endif
                            </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="{{ $latestBillingPeriod ? substr($latestBillingPeriod, 0, 4) . '-' . substr($latestBillingPeriod, 4, 2) : '' }}"
                                   onchange="loadAvailableProperties()" 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" onchange="loadAvailableProperties()" required>
                                <option value="">Select Type</option>
                                @foreach($consumptionTypes as $type)
                                    <option value="{{ $type->tID }}" {{ old('cons_type', '') == $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">
                            <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="{{ date('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="{{ date('Y-m-d', strtotime('+30 days')) }}" 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()">
                            </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()">
                            </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()">
                            </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()">
                            </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" required>
            </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="0" 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="0" required>
            </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="0" required>
            </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>
    
    @if(isset($bulkInvoiceLines) && $bulkInvoiceLines->count() > 0)
        <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($bulkInvoiceLines as $index => $item)
                        <tr class="invoice-item">
                            <td>
                                <input type="hidden" name="items[{{ $index }}][BulkLineID]" value="{{ $item->BulkLineID }}">
                                {{ $item->BulkLineID }}
                            </td>
                            <input type="hidden" name="items[{{ $index }}][BulkCategID]" value="{{ $item->BulkCategID }}">
                            <td>
                                <input type="hidden" name="items[{{ $index }}][BulkLineDesc]" value="{{ $item->BulkLineDesc }}">
                                {{ $item->BulkLineDesc }}
                            </td>
                            <td>
                                <input type="number" class="form-control form-control-sm unit-price" 
                                       name="BulkLineUnitPrice[]" value="1" step="0.01" min="0" 
                                       onchange="calculateLineTotal(this)">
                            </td>
                            <td>
                                <input type="number" class="form-control form-control-sm line-total" 
                                       name="BulkLineAmount[]" value="0" 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>
    @else
        <div class="alert alert-warning">
            <div class="d-flex">
                <div class="me-3">
                    <i class="bi bi-exclamation-triangle-fill"></i>
                </div>
                <div>
                    No invoice items found for the latest bulk invoice.
                </div>
            </div>
        </div>
    @endif
</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.index') }}" 
       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 Invoice
    </button>
</div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

<!-- 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 available properties based on billing period
    function loadAvailableProperties() {
        const billingPeriod = document.getElementById('BillingPeriod').value;
        const consType = document.getElementById('consType').value;
        if (!billingPeriod || !consType) return;
        
        const routeUrl = "{{ route('invoices.bulk.available-properties') }}";
        const url = `${routeUrl}?billing_period=${billingPeriod}&cons_type=${consType}`;
        
        // Show loading state
        const propertySelect = document.getElementById('PropID');
        const currentValue = propertySelect.value;
        propertySelect.disabled = true;
        propertySelect.innerHTML = '<option value="" disabled>Loading properties...</option>';
        
        console.log('Loading properties for billing period:', billingPeriod, 'and cons type:', consType);
        console.log('Request URL:', url);
        
        fetch(url, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        })
        .then(response => {
            console.log('Response status:', response.status);
            console.log('Response ok:', response.ok);
            
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.error || `HTTP error! status: ${response.status}`);
                });
            }
            return response.json();
        })
        .then(data => {
            console.log('Received data:', data);
            
            if (data.error) {
                console.error('Server error:', data.error);
                propertySelect.innerHTML = `<option value="" disabled>Error: ${data.error}</option>`;
                return;
            }
            
            // Clear existing options
            propertySelect.innerHTML = '<option value="" selected disabled>Select Property</option>';
            
            if (data.length === 0) {
                propertySelect.innerHTML += '<option value="" disabled>No available properties for this billing period</option>';
            } else {
                // Add properties to dropdown
                data.forEach(property => {
                    const option = document.createElement('option');
                    option.value = property.PropID;
                    option.textContent = property.PropName;
                    option.setAttribute('data-prev-reading1', property.PreviousReading1 || '');
                    option.setAttribute('data-prev-reading2', property.PreviousReading2 || '');
                    option.setAttribute('data-curr-reading1', property.CurrentReading1 || '');
                    option.setAttribute('data-curr-reading2', property.CurrentReading2 || '');
                    option.setAttribute('data-billing-period', property.LastBillingPeriod || '');
                    propertySelect.appendChild(option);
                });
                
                // Restore previous selection if it's still available
                if (currentValue) {
                    const existingOption = Array.from(propertySelect.options).find(opt => opt.value === currentValue);
                    if (existingOption) {
                        propertySelect.value = currentValue;
                    }
                }
            }
            
            propertySelect.disabled = false;
            
            // Trigger change event to update form sections
            const event = new Event('change', { bubbles: true });
            propertySelect.dispatchEvent(event);
        })
        .catch(error => {
            console.error('Error loading properties:', error);
            console.error('Error details:', error.message);
            console.error('Error stack:', error.stack);
            
            let errorMessage = 'Error loading properties';
            if (error.message) {
                errorMessage += ': ' + error.message;
            }
            
            propertySelect.innerHTML = `<option value="" disabled>${errorMessage}</option>`;
            propertySelect.disabled = false;
        });
    }

    // Load previous readings when a property is selected
    function loadPreviousReadings(propertyId) {
        if (!propertyId) return;
        
        const propertySelect = document.querySelector(`#PropID option[value="${propertyId}"]`);
        if (!propertySelect) return;
        
        const prevReading1 = propertySelect.getAttribute('data-prev-reading1');
        const prevReading2 = propertySelect.getAttribute('data-prev-reading2');
        const currReading1 = propertySelect.getAttribute('data-curr-reading1');
        const currReading2 = propertySelect.getAttribute('data-curr-reading2');
        const billingPeriod = propertySelect.getAttribute('data-billing-period');
        
        // Format billing period for display (if needed)
        // Removed setting the billing period when property changes
        // The billing period should remain fixed based on the latest billing period
        
        // Set previous readings in the form
        const prev1Field = document.getElementById('previousReading1');
        const prev2Field = document.getElementById('previousReading2');
        const curr1Field = document.getElementById('currentReading1');
        const curr2Field = document.getElementById('currentReading2');
        
        // Only set previous readings if they're not already set
        if (prevReading1 && (!prev1Field.value || prev1Field.value === '0')) {
            prev1Field.value = prevReading1;
            prev1Field.readOnly = true;
            prev1Field.classList.add('bg-light');
        }
        
        if (prevReading2 && (!prev2Field.value || prev2Field.value === '0')) {
            prev2Field.value = prevReading2;
            prev2Field.readOnly = true;
            prev2Field.classList.add('bg-light');
        }
        
        // Set current readings as well (but leave them editable)
        if (currReading1 && (!curr1Field.value || curr1Field.value === '0')) {
            curr1Field.value = currReading1;
        }
        
        if (currReading2 && (!curr2Field.value || curr2Field.value === '0')) {
            curr2Field.value = currReading2;
        }
        
        // Update billing period if needed
        if (formattedBillingPeriod && document.getElementById('billingMonth')) {
            document.getElementById('billingMonth').value = formattedBillingPeriod;
        }
        
        // Recalculate consumption
        calculateConsumption();
    }

    // Initialize when DOM is loaded
    // Generate a default invoice number
    function generateInvoiceNumber() {
        const now = new Date();
        const year = now.getFullYear().toString().substr(-2);
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const random = Math.floor(1000 + Math.random() * 9000);
        return `INV-${year}${month}-${random}`;
    }

    // Handle form submission
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize consumption calculation
        initializeConsumptionCalculation();
        
        // Load available properties for current billing period
        loadAvailableProperties();
        
        // Set default invoice number if empty
        const invoiceNoField = document.getElementById('invoiceNo');
        if (invoiceNoField && !invoiceNoField.value) {
            invoiceNoField.value = generateInvoiceNumber();
        }
        
        // Handle form submission
        const form = document.getElementById('invoiceForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Validate form
                if (!form.checkValidity()) {
                    e.stopPropagation();
                    form.classList.add('was-validated');
                    return false;
                }
                
                // Show loading state
                const submitButton = form.querySelector('button[type="submit"]');
                const originalButtonText = submitButton.innerHTML;
                submitButton.disabled = true;
                submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...';
                
                // Submit the form using Fetch API
                fetch(form.action, {
                    method: 'POST',
                    body: new FormData(form),
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Invoice created successfully!',
                            confirmButtonColor: '#3085d6',
                            confirmButtonText: 'OK'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                // Redirect to the invoice details page
                                window.location.href = data.redirect || '{{ route("invoices.bulk.index") }}';
                            }
                        });
                    } else {
                        // Show error message
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: data.message || 'An error occurred while creating the invoice.',
                            confirmButtonColor: '#d33',
                            confirmButtonText: 'OK'
                        });
                        submitButton.disabled = false;
                        submitButton.innerHTML = originalButtonText;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while creating the invoice. Please try again.',
                        confirmButtonColor: '#d33',
                        confirmButtonText: 'OK'
                    });
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalButtonText;
                });
            });
        }
        
        // Initialize form with default values
        const propSelect = document.querySelector('select[name="PropID"]');
        if (propSelect) {
            propSelect.addEventListener('change', fetchBulkInvoiceLines);
        }

        function fetchBulkInvoiceLines() {
            // Implementation for fetching invoice lines
            // This will be called when property changes
            const propertyId = $('#PropID').val();
            if (propertyId) {
                // Example AJAX call - update with your actual endpoint
                /*
                $.get(`/api/properties/${propertyId}/invoice-lines`, function(data) {
                    const tbody = $('#bulkInvoiceTableBody');
                    tbody.empty();
                    
                    data.forEach(item => {
                        tbody.append(`
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.description}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.unit_price}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.amount}</td>
                            </tr>
                        `);
                    });
                });
                */
            }
        }

        // Show success/error messages
        @if(session('success'))
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: '{{ session('success') }}',
                confirmButtonColor: '#3085d6',
                confirmButtonText: 'OK'
            });
        @endif

        @if(session('error'))
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '{{ session('error') }}',
                confirmButtonColor: '#d33',
                confirmButtonText: 'OK'
            });
        @endif
    });

    function calculateConsumption() {
        let prev1 = parseFloat($("#previousReading1").val()) || 0;
        let curr1 = parseFloat($("#currentReading1").val()) || 0;
        let prev2 = parseFloat($("#previousReading2").val()) || 0;
        let curr2 = parseFloat($("#currentReading2").val()) || 0;

        let consumption = (curr1 - prev1) + (curr2 - prev2);
        $("#consumption").val(consumption.toFixed(2));
    }
</script>
@endpush
@endsection
