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

    // ======================================================
    // ELEMENT REFERENCES
    // ======================================================
    const form = document.getElementById("bookingForm");

    const serviceSelect = document.getElementById("service_id");
    const vehicleSelect = document.getElementById("vehicle_type");

    const zoneGroup = document.getElementById("zoneGroup");
    const zoneSelect = document.getElementById("zone_id");

    const hourGroup = document.getElementById("hourGroup");
    const hoursInput = document.getElementById("hours");

    const flightGroup = document.getElementById("flightGroup");
    const flightInput = document.querySelector("input[name='flight_number']");

    const pickupField = document.querySelector("input[name='pickup_address']");
    const dropoffField = document.querySelector("input[name='dropoff_address']");

    const totalPriceDisplay = document.getElementById("totalPrice");

    const adultInput = document.getElementById("adult_count");
    const childInput = document.getElementById("child_count");
    const largeInput = document.getElementById("large_luggage");
    const smallInput = document.getElementById("small_luggage");

    const capacityError = document.getElementById("capacityError");
    const recommendationBox = document.getElementById("vehicleRecommendation");

    // ======================================================
    // RESET UI
    // ======================================================
    function resetUI() {
        zoneGroup.classList.add("d-none");
        hourGroup.classList.add("d-none");
        flightGroup.classList.add("d-none");

        pickupField.removeAttribute("readonly");
        dropoffField.removeAttribute("readonly");
    }

    // ======================================================
    // SERVICE CHANGE (DB-DRIVEN)
    // ======================================================
    serviceSelect.addEventListener("change", function () {

        const option = serviceSelect.options[serviceSelect.selectedIndex];
        if (!option.value) {
            resetUI();
            calculatePrice();
            return;
        }

        const pricingType = option.dataset.pricing;
        const zoneRequired = parseInt(option.dataset.zone) || 0;
        const airportPickup = parseInt(option.dataset.airportPickup) || 0;
        const airportDropoff = parseInt(option.dataset.airportDropoff) || 0;
        const flightRequired = parseInt(option.dataset.flight) || 0;
        const minimumHours = parseInt(option.dataset.minhours) || 0;

        resetUI();

        if (zoneRequired === 1) {
            zoneGroup.classList.remove("d-none");
        }

        if (airportPickup === 1) {
            pickupField.value = "Changi Airport";
            pickupField.setAttribute("readonly", true);
        }

        if (airportDropoff === 1) {
            dropoffField.value = "Changi Airport";
            dropoffField.setAttribute("readonly", true);
        }

        if (flightRequired === 1) {
            flightGroup.classList.remove("d-none");
        }

        if (pricingType === "hourly") {
            hourGroup.classList.remove("d-none");
            if (hoursInput.value < minimumHours) {
                hoursInput.value = minimumHours;
            }
        }

        calculatePrice();
    });

    // ======================================================
    // PRICE CALCULATION
    // ======================================================
    function calculatePrice() {

        let price = 0;

        const option = serviceSelect.options[serviceSelect.selectedIndex];

        if (!option || !option.value) {
            totalPriceDisplay.innerText = "$0.00";
            return;
        }

        const pricingType = option.dataset.pricing;
        const basePrice = parseFloat(option.dataset.base) || 0;
        const hourlyRate = parseFloat(option.dataset.hourly) || 0;
        const minimumHours = parseInt(option.dataset.minhours) || 0;

        if (pricingType === "fixed") {
            price = basePrice;
        }

        else if (pricingType === "zone") {
            if (zoneSelect && zoneSelect.value) {
                const zoneOption = zoneSelect.options[zoneSelect.selectedIndex];
                price = parseFloat(zoneOption.dataset.price) || 0;
            }
        }

        else if (pricingType === "hourly") {
            let hours = parseInt(hoursInput.value) || minimumHours;
            if (hours < minimumHours) {
                hours = minimumHours;
                hoursInput.value = minimumHours;
            }
            price = hourlyRate * hours;
        }

        totalPriceDisplay.innerText = "$" + price.toFixed(2);
    }

    serviceSelect.addEventListener("change", calculatePrice);
    zoneSelect?.addEventListener("change", calculatePrice);
    hoursInput?.addEventListener("input", calculatePrice);
    vehicleSelect.addEventListener("change", calculatePrice);

    // ======================================================
    // CAPACITY VALIDATION
    // ======================================================
    function validateCapacity() {

        const vehicle = vehicleSelect.value;
        const adults = parseInt(adultInput.value) || 0;
        const children = parseInt(childInput.value) || 0;
        const large = parseInt(largeInput.value) || 0;
        const small = parseInt(smallInput.value) || 0;

        const totalPassengers = adults + children;

        capacityError.classList.add("d-none");
        recommendationBox.classList.add("d-none");
        capacityError.innerText = "";
        recommendationBox.innerHTML = "";

        if (!vehicle) return;

        if (vehicle === "sedan" && totalPassengers > 4) {
            recommendVehicle(totalPassengers);
        }

        if (vehicle === "suv" && totalPassengers > 5) {
            recommendVehicle(totalPassengers);
        }

        if (vehicle === "mpv" && totalPassengers > 7) {
            showError("Capacity exceeded. Please book 2 Vehicles.");
        }

        if (vehicle === "sedan" && (large > 2 || small > 4)) {
            recommendVehicle(totalPassengers);
        }

        if (vehicle === "suv" && (large > 2 || small > 4)) {
            recommendVehicle(totalPassengers);
        }

        if (vehicle === "mpv" && (large > 4 || small > 6)) {
            showError("Luggage exceeds MPV capacity.");
        }
    }

    function showError(message) {
        capacityError.innerText = message;
        capacityError.classList.remove("d-none");
    }

    function recommendVehicle(passengers) {

        let suggested = passengers <= 5 ? "suv" : "mpv";

        recommendationBox.innerHTML = `
            <strong>Vehicle Upgrade Recommended:</strong><br>
            We recommend upgrading to <strong>${suggested.toUpperCase()}</strong>.
            <br>
            <button type="button"
                    class="btn btn-gold btn-sm mt-2"
                    onclick="applyVehicleUpgrade('${suggested}')">
                Switch to ${suggested.toUpperCase()}
            </button>
        `;

        recommendationBox.classList.remove("d-none");
    }

    window.applyVehicleUpgrade = function (type) {
        vehicleSelect.value = type;
        recommendationBox.classList.add("d-none");
        validateCapacity();
        calculatePrice();
    };

    [adultInput, childInput, largeInput, smallInput, vehicleSelect]
        .forEach(el => el.addEventListener("input", validateCapacity));

    // ======================================================
    // INLINE ERROR SYSTEM
    // ======================================================
    function showInlineError(message) {

        let errorBox = document.getElementById("formError");

        if (!errorBox) {
            errorBox = document.createElement("div");
            errorBox.id = "formError";
            errorBox.className = "alert alert-danger mt-3";
            form.prepend(errorBox);
        }

        errorBox.innerText = message;
    }

    // ======================================================
    // FORM SUBMISSION
    // ======================================================
    form.addEventListener("submit", function (e) {

        e.preventDefault();

        const option = serviceSelect.options[serviceSelect.selectedIndex];
        if (!option.value) {
            showInlineError("Please select a service.");
            return;
        }

        const flightRequired = parseInt(option.dataset.flight) || 0;

        if (flightRequired === 1) {
            if (!flightInput.value.trim()) {
                flightInput.classList.add("is-invalid");
                showInlineError("Flight number is required for Airport Arrival.");
                return;
            } else {
                flightInput.classList.remove("is-invalid");
            }
        }

        if (!capacityError.classList.contains("d-none")) {
            showInlineError(capacityError.innerText);
            return;
        }

        const formData = new FormData(form);

        fetch("process_booking.php", {
            method: "POST",
            body: formData
        })
        .then(response => response.json())
        .then(data => {

            if (data.status === "error") {
                showInlineError(data.message);
                return;
            }

            if (data.redirect) {
                window.location.href = data.redirect;
            }

        })
        .catch(() => {
            showInlineError("Server error. Please try again.");
        });
    });

});
