$(document).ready(function () {

    const form = $('#bookingForm');
    const serviceSelect = $('#service_id');
    const zoneGroup = $('#zoneGroup');
    const hourGroup = $('#hourGroup');
    const totalDisplay = $('#totalPrice');
    const submitBtn = $('#submitBooking');

    let isSubmitting = false;

    /*
    |--------------------------------------------------------------------------
    | Service Change Logic
    |--------------------------------------------------------------------------
    */

    serviceSelect.on('change', function () {

        const selected = $(this).find(':selected');
        const pricingType = selected.data('pricing');

        zoneGroup.addClass('d-none');
        hourGroup.addClass('d-none');

        if (pricingType === 'zone') {
            zoneGroup.removeClass('d-none');
        }

        if (pricingType === 'hourly') {
            hourGroup.removeClass('d-none');
        }

        calculatePreview();
    });


    $('#zone_id, #hours, #vehicle_type').on('change input', function () {
        calculatePreview();
    });


    /*
    |--------------------------------------------------------------------------
    | Price Preview
    |--------------------------------------------------------------------------
    */

    function calculatePreview() {

        const serviceId = serviceSelect.val();
        if (!serviceId) return;

        $.ajax({
            url: 'ajax/price_estimator.php',
            method: 'POST',
            data: {
                service_id: serviceId,
                zone_id: $('#zone_id').val(),
                hours: $('#hours').val(),
                vehicle_type: $('#vehicle_type').val()
            },
            success: function (response) {

                if (response.status === 'success') {
                    totalDisplay.text('$' + response.data.total.toFixed(2));
                }
            }
        });
    }


    /*
    |--------------------------------------------------------------------------
    | Booking Submit
    |--------------------------------------------------------------------------
    */

    form.on('submit', function (e) {
        e.preventDefault();

        if (isSubmitting) return;

        isSubmitting = true;
        submitBtn.prop('disabled', true).text('Processing...');

        $.ajax({
            url: 'ajax/create_booking.php',
            method: 'POST',
            data: form.serialize(),
            dataType: 'json',

            success: function (response) {

                if (response.status === 'success') {

                    showSuccessModal(
                        response.booking_reference,
                        response.total_price
                    );

                    form.trigger('reset');
                    totalDisplay.text('$0.00');

                } else {
                    showError(response.message);
                }

            },

            error: function () {
                showError('Server error. Please try again.');
            },

            complete: function () {
                isSubmitting = false;
                submitBtn.prop('disabled', false).text('Confirm Booking');
            }
        });
    });


    /*
    |--------------------------------------------------------------------------
    | UI Helpers
    |--------------------------------------------------------------------------
    */

    function showSuccessModal(reference, total) {

        const html = `
            <div class="modal fade" id="bookingSuccessModal" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content bg-dark text-light">
                        <div class="modal-header border-0">
                            <h5 class="modal-title text-gold">Booking Confirmed</h5>
                            <button type="button" class="close text-light" data-dismiss="modal">&times;</button>
                        </div>
                        <div class="modal-body text-center">
                            <p>Reference:</p>
                            <h4 class="text-gold">${reference}</h4>
                            <p>Total Price:</p>
                            <h5>$${parseFloat(total).toFixed(2)}</h5>
                            <p class="mt-3">Our concierge team will contact you shortly.</p>
                        </div>
                    </div>
                </div>
            </div>
        `;

        $('body').append(html);
        $('#bookingSuccessModal').modal('show');

        $('#bookingSuccessModal').on('hidden.bs.modal', function () {
            $(this).remove();
        });
    }

    function showError(message) {

        const alertHtml = `
            <div class="alert alert-danger alert-dismissible fade show mt-3">
                ${message}
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        `;

        form.prepend(alertHtml);
    }

});
