document.addEventListener('DOMContentLoaded', function () {

    // --- Toggle for Layover Section ---
    const layoverToggle = document.getElementById('layoverToggle');
    const layoverDetails = document.getElementById('layoverDetails');

    if (layoverToggle) {
        layoverToggle.addEventListener('change', function () {
            layoverDetails.style.display = this.checked ? 'block' : 'none';
        });
    }

    // --- Auto-calculation for Fares ---
    const passengersInput = document.getElementById('passengers');
    const fareInput = document.getElementById('fare');
    const totalFareInput = document.getElementById('totalFare');
    
    const infantsInput = document.getElementById('infants');
    const infantFareInput = document.getElementById('infantFare');
    const totalInfantFareInput = document.getElementById('totalInfantFare');

    const extraChargePriceInput = document.getElementById('extraChargePrice');
    const grandTotalInput = document.getElementById('grandTotal');

    const calculationFields = [passengersInput, fareInput, infantsInput, infantFareInput, extraChargePriceInput];

    function calculateTotals() {
        const passengers = parseFloat(passengersInput.value) || 0;
        const fare = parseFloat(fareInput.value) || 0;
        const infants = parseFloat(infantsInput.value) || 0;
        const infantFare = parseFloat(infantFareInput.value) || 0;
        const extraCharges = parseFloat(extraChargePriceInput.value) || 0;

        const totalFare = passengers * fare;
        const totalInfantFare = infants * infantFare;
        const grandTotal = totalFare + totalInfantFare + extraCharges;

        totalFareInput.value = totalFare.toFixed(3);
        totalInfantFareInput.value = totalInfantFare.toFixed(3);
        grandTotalInput.value = grandTotal.toFixed(3) + ' OMR';
    }

    calculationFields.forEach(field => {
        if (field) {
            field.addEventListener('input', calculateTotals);
        }
    });

    // Initial calculation on page load
    calculateTotals();

    // --- Preview Modal Logic ---
    const previewButton = document.getElementById('previewButton');
    const previewModal = new bootstrap.Modal(document.getElementById('previewModal'));
    const previewContent = document.getElementById('previewContent');

    if (previewButton) {
        previewButton.addEventListener('click', function () {
            // Helper to get form values
            const getValue = (id) => document.getElementById(id).value || 'N/A';

            // Collect data from form fields
            const customerName = getValue('customerName');
            const phoneNumber = getValue('phoneNumber');
            const email = getValue('email');
            const passengers = getValue('passengers');

            const departureAirport = getValue('departureAirport');
            const arrivalAirport = getValue('arrivalAirport');
            const departureDate = getValue('departureDate');
            const returnDate = getValue('returnDate');
            const airline = getValue('airline');
            const cabinClass = getValue('cabinClass');

            let layoverInfo = '';
            if (layoverToggle.checked) {
                const layoverAirport = getValue('layoverAirport');
                const layoverDuration = getValue('layoverDuration');
                layoverInfo = `
                    <h5><i class="bi bi-clock"></i> Layover Details</h5>
                    <p><strong>Layover Airport:</strong> ${layoverAirport}</p>
                    <p><strong>Duration:</strong> ${layoverDuration}</p>
                `;
            }
            
            const fare = parseFloat(getValue('fare')).toFixed(3) || '0.000';
            const totalFare = getValue('totalFare');

            const infants = getValue('infants');
            const infantFare = parseFloat(getValue('infantFare')).toFixed(3) || '0.000';
            const totalInfantFare = getValue('totalInfantFare');
            const infantBaggage = getValue('infantBaggage');

            const checkedBaggage = getValue('checkedBaggage');
            const weightPerPiece = getValue('weightPerPiece');
            const handBaggage = getValue('handBaggage');
            const baggageNotes = getValue('baggageNotes');

            const extraChargeDescription = getValue('extraChargeDescription');
            const extraChargePrice = parseFloat(getValue('extraChargePrice')).toFixed(3) || '0.000';

            const grandTotal = getValue('grandTotal');
            const otherRequests = getValue('otherRequests');

            // Construct HTML for preview
            previewContent.innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <h5><i class="bi bi-person-circle"></i> Customer Details</h5>
                        <p><strong>Name:</strong> ${customerName}</p>
                        <p><strong>Phone:</strong> ${phoneNumber}</p>
                        <p><strong>Email:</strong> ${email}</p>
                    </div>
                    <div class="col-md-6">
                        <h5><i class="bi bi-airplane-fill"></i> Flight Information</h5>
                        <p><strong>From:</strong> ${departureAirport}</p>
                        <p><strong>To:</strong> ${arrivalAirport}</p>
                        <p><strong>Departure:</strong> ${departureDate}</p>
                        <p><strong>Return:</strong> ${returnDate || 'One-way'}</p>
                        <p><strong>Airline:</strong> ${airline}</p>
                        <p><strong>Class:</strong> ${cabinClass}</p>
                    </div>
                </div>

                ${layoverInfo}

                <hr>

                <div class="row">
                     <div class="col-md-6">
                        <h5><i class="bi bi-person-arms-up"></i> Passenger & Infant Details</h5>
                        <p><strong>No. of Passengers:</strong> ${passengers}</p>
                        <p><strong>No. of Infants:</strong> ${infants}</p>
                        <p><strong>Infant Baggage:</strong> ${infantBaggage}</p>
                    </div>
                    <div class="col-md-6">
                        <h5><i class="bi bi-briefcase-fill"></i> Adult Baggage Details</h5>
                        <p><strong>Checked Pieces:</strong> ${checkedBaggage}</p>
                        <p><strong>Weight per Piece:</strong> ${weightPerPiece} kg</p>
                        <p><strong>Hand Baggage:</strong> ${handBaggage} kg</p>
                        <p><strong>Notes:</strong> ${baggageNotes}</p>
                    </div>
                </div>

                <hr>

                <h5><i class="bi bi-cash-coin"></i> Fare Summary (OMR)</h5>
                <table class="table table-sm">
                    <tbody>
                        <tr>
                            <td>Fare per Passenger</td>
                            <td class="text-end">${fare}</td>
                        </tr>
                        <tr>
                            <td><strong>Total Passenger Fare</strong></td>
                            <td class="text-end"><strong>${totalFare}</strong></td>
                        </tr>
                        <tr>
                            <td>Infant Fare</td>
                            <td class="text-end">${infantFare}</td>
                        </tr>
                         <tr>
                            <td><strong>Total Infant Fare</strong></td>
                            <td class="text-end"><strong>${totalInfantFare}</strong></td>
                        </tr>
                        <tr>
                            <td>${extraChargeDescription || 'Extra Charges'}</td>
                            <td class="text-end">${extraChargePrice}</td>
                        </tr>
                        <tr class="table-active">
                            <td class="fw-bold">Grand Total</td>
                            <td class="text-end fw-bold">${grandTotal}</td>
                        </tr>
                    </tbody>
                </table>

                <h5><i class="bi bi-chat-left-text-fill"></i> Additional Comments</h5>
                <p>${otherRequests}</p>
            `;

            // Show the modal
            previewModal.show();
        });
    }

    // --- Reset Form Logic ---
    const resetButton = document.getElementById('resetButton');
    const airfareForm = document.getElementById('airfareForm');

    if (resetButton) {
        resetButton.addEventListener('click', function() {
            airfareForm.reset();
            // Manually hide the layover section if it was open
            if (layoverToggle.checked) {
                layoverDetails.style.display = 'none';
            }
            // Recalculate totals to reset them to 0
            calculateTotals();
        });
    }
});