console.log("✅ requestAppointment.js loaded");

document.addEventListener("DOMContentLoaded", function () {
    const form = document.getElementById("apptmntForm");

    // --- Input Validation ---
    const nameField = document.getElementById("customerName");
    const phoneField = document.getElementById("phone");
    const yearField = document.getElementById("vehicleYear");

    // Validation messages
    const customerInfoMssg = document.getElementById("customerInfoMssg") || document.createElement("small");
    const vehicleYearMssg = document.getElementById("vehicleYearMssg") || document.createElement("small");

    // Name validation
    nameField.addEventListener("input", function () {
        if (/[^a-zA-Z\s]/.test(this.value)) {
            customerInfoMssg.textContent = "Please enter only alphabets and spaces for name";
            this.value = this.value.replace(/[^a-zA-Z\s]/g, "");
        } else {
            customerInfoMssg.textContent = "";
        }
    });

    // Phone validation
    phoneField.addEventListener("input", function () {
        if (/[^0-9-]/.test(this.value)) {
            customerInfoMssg.textContent = "Please enter only numbers or hyphen for phone number";
            this.value = this.value.replace(/[^0-9-]/g, "");
        } else {
            customerInfoMssg.textContent = "";
        }
    });

    // Vehicle year validation
    yearField.addEventListener("input", function () {
        if (/[^0-9]/.test(this.value)) {
            vehicleYearMssg.textContent = "Please enter only numeric values for vehicle year";
            this.value = this.value.replace(/[^0-9]/g, "");
        } else {
            vehicleYearMssg.textContent = "";
        }
    });

    // --- Handle form submission ---
    form.addEventListener("submit", function (e) {
        e.preventDefault();

        console.log("⏳ Submitting form...");

        fetch("sendAppointment.php", {
            method: "POST",
            body: new FormData(form),
        })
        .then(response => response.json())
        .then(data => {
            console.log("Server says:", data);

            if (data.ok) {
                // ✅ Redirect to thank you page
                window.location.href = "thankyou.html";
            } else {
                alert("❌ " + data.message);
            }
        })
        .catch(error => {
            console.error("Fetch error:", error);
            alert("❌ Network error. Please try again later.");
        });
    });
});
