// header
window.addEventListener("scroll", function () {
    const header = document.querySelector("header");
    const logo = document.querySelector(".logo");
    if (window.scrollY > 10) {
        header.classList.add("active");
        logo.src = "./asset/images/logo-022352.png";
    } else {
        header.classList.remove("active");
        logo.src = "./asset/images/logo-022352.png";
    }
});

// for header navbar active 
// document.addEventListener("DOMContentLoaded", function () {
//     const currentPage = window.location.pathname.split("/").pop();

//     document.querySelectorAll(".nav-link").forEach(link => {
//         let linkPage = link.getAttribute("href");

//         if (currentPage === linkPage) {
//             link.classList.add("active-menu");
//         }
//     });
// });


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

    // get current page name
    let currentPage = window.location.pathname.split("/").pop();

    // remove .php if exists
    currentPage = currentPage.replace(".php", "");

    // if home page is empty
    if (currentPage === "") {
        currentPage = "index";
    }

    document.querySelectorAll(".nav-link").forEach(link => {
        let linkPage = link.getAttribute("href");

        if (currentPage === linkPage) {
            link.classList.add("active-menu");
        }
    });

})

// ========== home page ======


// check (in /out)date  for home login form  

let fp0;
document.addEventListener('DOMContentLoaded', function () {
    const pickerInput = document.getElementById('date-range-picker0');

    // Initialize flatpickr on that element
    fp0 = flatpickr(pickerInput, {
        mode: "range",
        minDate: "today",
        dateFormat: "d-M-y  ",
        altInput: true,
        altFormat: "d-M-y",
        locale: {
            rangeSeparator: "  - "   // Change 'to' into '-'
        }
    });

});
function cleardatepicker0() {
    if (fp0) {
        fp0.clear();
    }
}

// (prin only text in  name input)  homepage  form   

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById("num2").addEventListener("input", function () {
        this.value = this.value.replace(/[^A-Za-z\s]/g, "");
    });
});




//==== home page ========

// facilities section

$(document).ready(function () {

    var owl = $('#facilitiescarousel');
    owl.owlCarousel({
        loop: true,
        dots: false,
        margin: 10,
        nav: false,   // hide default nav buttons
        center: true,
        autoplay: true,
        autoplayTimeout: 3000,
        responsive: {
            0: { items: 1, center: true },
            768: { items: 2, center: true },
            1000: { items: 3, center: true }
        }
    });
});


// what our guests say
$(document).ready(function () {

    var owl = $('#guestcarousel');
    owl.owlCarousel({
        loop: true,
        margin: 10,
        nav: false,   // hide default nav buttons
        dots: true,
        center: true,
        autoplay: true,
        autoplayTimeout: 3000,
        responsive: {
            0: { items: 1, center: true },
            768: { items: 2, center: true },
            1000: { items: 3, center: true }
        }
    });
});



//          ================         about page

$(document).ready(function () {

    var owl = $('#aboutguestcarousel');
    owl.owlCarousel({
        loop: true,
        margin: 10,
        nav: false,   // hide default nav buttons
        dots: true,
        center: true,
        autoplay: true,
        autoplayTimeout: 3000,
        responsive: {
            0: { items: 1, center: true },
            768: { items: 2, center: true },
            1000: { items: 3, center: true }
        }
    });
});






// villa page form validation
var validateRegex;
document.addEventListener('DOMContentLoaded', function () {
    function validateRegexFn(inputId, msgId, pattern, customMessage) {
        const value = document.getElementById(inputId).value;

        if (!pattern.test(value)) {
            document.getElementById(msgId).innerText = customMessage;
            return false;
        }
        document.getElementById(msgId).innerText = "";
        return true;
    }
    validateRegex = validateRegexFn; // <-- Correct way
});

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

    // adults input validation 1
    document.getElementById("adultsForm1").addEventListener("input", () => {
        validateRegex(
            "adultsForm1",
            "adultsForm1Msg",
            /^(?:[1-9]|1[0-9]|20)$/,
            "Please enter a valid number of adults (1-20)."
        );
    });
    //child input validation 1
    document.getElementById("childForm1").addEventListener("input", () => {

        validateRegex(
            "childForm1",
            "childForm1Msg",
            /^(?:[1-9]|1[0-9]|15)$/,
            "Please enter a valid number of childs (1-15)."
        );
    });

    //rooms input validation 1
    document.getElementById("roomsForm1").addEventListener("input", () => {

        validateRegex(
            "roomsForm1",
            "roomsForm1Msg",
            /^(?:[1-9]|1[0-9]|10)$/,
            "Please enter a valid number of rooms (1-10)."
        );
    });


    // adults input validation 2
    document.getElementById("adultsForm2").addEventListener("input", () => {
        validateRegex(
            "adultsForm2",
            "adultsForm2Msg",
            /^(?:[1-9]|1[0-9]|20)$/,
            "Please enter a valid number of adults (1-20)."
        );
    });
    //child input validation   2
    document.getElementById("childForm2").addEventListener("input", () => {

        validateRegex(
            "childForm2",
            "childForm2Msg",
            /^(?:[1-9]|1[0-9]|15)$/,
            "Please enter a valid number of childs (1-15)."
        );
    });

    //rooms input validation  2
    document.getElementById("roomsForm2").addEventListener("input", () => {

        validateRegex(
            "roomsForm2",
            "roomsForm2Msg",
            /^(?:[1-9]|1[0-9]|10)$/,
            "Please enter a valid number of rooms (1-10)."
        );
    });

});



// villa page form 1 input for guest name
document.addEventListener('DOMContentLoaded', function () {

    document.getElementById("num3").addEventListener("input", function () {

        this.value = this.value.replace(/[^A-Za-z\s]/g, "");
    });
});

// // villa page form 2 input for guest name 
document.addEventListener('DOMContentLoaded', function () {

    document.getElementById("num4").addEventListener("input", function () {

        this.value = this.value.replace(/[^A-Za-z\s]/g, "");
    });
});



// double date
let fp1;
document.addEventListener('DOMContentLoaded', function () {
    const pickerInput = document.getElementById('date-range-picker1');

    // Initialize flatpickr on that element
    fp1 = flatpickr(pickerInput, {
        mode: "range",
        minDate: "today",
        dateFormat: "d-M-y  ",
        altInput: true,
        altFormat: "  d-M-y",
        locale: {
            rangeSeparator: "   - "   // Change 'to' into '-'
        }

    });
});


function cleardatepicker1() {
    if (fp1) {
        fp1.clear();
    }
}

let fp2;
document.addEventListener('DOMContentLoaded', function () {
    const pickerInput = document.getElementById('date-range-picker2');

    // Initialize flatpickr on that element
    fp2 = flatpickr(pickerInput, {
        mode: "range",
        minDate: "today",
        dateFormat: "d-M-y  ",
        altInput: true,
        altFormat: "d-M-y",
        locale: {
            rangeSeparator: "   - "   // Change 'to' into '-'
        }
    });

});
function cleardatepicker2() {
    if (fp2) {
        fp2.clear();
    }
}




// done btn( 1 and 2)

document.addEventListener('DOMContentLoaded', function () {
    const doneBtn1 = document.getElementById('doneBtn1');
    const doneBtn2 = document.getElementById('doneBtn2');

    if (doneBtn1) {
        doneBtn1.addEventListener('click', function () {
            const parent = this.closest('.dropdown-menu');
            const adults = parent.querySelector('input[name="adults"]').value;
            const children = parent.querySelector('input[name="children"]').value;
            const rooms = parent.querySelector('input[name="rooms"]').value;

            const guestText = document.getElementById('guestText1');
            guestText.innerHTML = `<i class="bi bi-person-circle me-2"></i>${adults} Adults - ${children} Children - ${rooms} Rooms`;
            parent.classList.remove('show'); // close dropdown
        });
    }

    if (doneBtn2) {
        doneBtn2.addEventListener('click', function () {
            const parent = this.closest('.dropdown-menu');
            const adults = parent.querySelector('input[name="adults"]').value;
            const children = parent.querySelector('input[name="children"]').value;
            const rooms = parent.querySelector('input[name="rooms"]').value;

            const guestText = document.getElementById('guestText2');
            guestText.innerHTML = `<i class="bi bi-person-circle me-2"></i>${adults} Adults - ${children} Children - ${rooms} Rooms`;
            parent.classList.remove('show'); // close dropdown
        });
    }
});



//   ====== gallery page======

$(document).ready(function () {

    var owl = $('#gallerycarousel');
    owl.owlCarousel({
        loop: true,
        margin: 10,
        nav: false,   // hide default nav buttons
        dots: false,
        center: true,
        autoplay: true,
        autoplayHoverPause: true,
        autoplayTimeout: 3000,
        responsive: {
            0: { items: 1, },
            768: { items: 2, },
            1000: { items: 3 }
        }
    });
});


// whatsapp

function openWhatsApp() {
    var phone = "918939582777";
    var message = "Hi 👋, I want to book a room 🏨";

    var url = "https://wa.me/" + phone + "?text=" + encodeURIComponent(message);
    window.open(url, "_blank");  // opens in new tab
}

$(document).ready(function () {

    // Trigger function when modal fully closes
    $(' #booknow2').on('hidden.bs.modal', function () {
        fp2.clear();
        nameMsg = document.getElementById('nameMsg');
        dateMsg = document.getElementById('dateMsg');
        guestMsg = document.getElementById('guestMsg');

        nameMsg.textContent = ''
        dateMsg.textContent = ''
        guestMsg.textContent = ''
    });
});





// home page,
//   3 duplex villa , 
// 4 duplex villa ""
document.addEventListener("DOMContentLoaded", function () {

    const forms = document.querySelectorAll("form");

    forms.forEach(form => {

        const nameInput = form.querySelector('[name="first_name"]');
        const phoneInput = form.querySelector('[name="phone"]');
        const dateInput = form.querySelector('[name="date_range"]');
        const adultsInput = form.querySelector('[name="adults"]');
        const childrenInput = form.querySelector('[name="children"]');
        const roomsInput = form.querySelector('[name="rooms"]');
        const sourceInput = form.querySelector('[name="form_source"]');

        // -----------------------------
        // Create error message elements
        // -----------------------------
        function createMsg(input) {
            if (!input) return null;
            const span = document.createElement("span");
            span.className = "text-danger small d-block";
            input.parentNode.appendChild(span);
            return span;
        }

        const nameMsg = createMsg(nameInput);
        const phoneMsg = createMsg(phoneInput);
        const dateMsg = createMsg(dateInput);
        const adultsMsg = createMsg(adultsInput);
        const childrenMsg = createMsg(childrenInput);
        const roomsMsg = createMsg(roomsInput);

        // -----------------------------
        // Phone: Only 10 digits
        // -----------------------------
        if (phoneInput) {
            phoneInput.addEventListener("input", () => {
                phoneInput.value = phoneInput.value.replace(/\D/g, "").slice(0, 10);
                phoneMsg.textContent = phoneInput.value.length !== 10 ? "Enter 10 digit phone number" : "";
            });
        }

        // -----------------------------
        // Live validations
        // -----------------------------
        if (nameInput) {
            nameInput.addEventListener("input", () => {
                nameMsg.textContent = nameInput.value.trim() === "" ? "Enter your name" : "";
            });
        }

        if (dateInput) {
            dateInput.addEventListener("change", () => {
                dateMsg.textContent = dateInput.value.trim() === "" ? "Select date" : "";
            });
        }

        if (adultsInput) {
            adultsInput.addEventListener("change", () => {
                const v = +adultsInput.value || 0;
                adultsMsg.textContent = v < 0 ? "Invalid adults" : "";
            });
        }

        if (childrenInput) {
            childrenInput.addEventListener("change", () => {
                const v = +childrenInput.value || 0;
                childrenMsg.textContent = v < 0 ? "Invalid children" : "";
            });
        }

        if (roomsInput) {
            roomsInput.addEventListener("change", () => {
                const v = +roomsInput.value || 0;
                roomsMsg.textContent = v < 0 ? "Invalid rooms" : "";
            });
        }

        // -----------------------------
        // Form Submit
        // -----------------------------
        form.addEventListener("submit", function (e) {
            e.preventDefault();

            const formData = new FormData(form);

            let valid = true;

            // Reset messages
            if (nameMsg) nameMsg.textContent = "";
            if (phoneMsg) phoneMsg.textContent = "";
            if (dateMsg) dateMsg.textContent = "";
            if (adultsMsg) adultsMsg.textContent = "";
            if (childrenMsg) childrenMsg.textContent = "";
            if (roomsMsg) roomsMsg.textContent = "";

            const name = nameInput?.value.trim();
            const phone = phoneInput?.value.trim();
            const date = dateInput?.value.trim();
            const adults = +adultsInput?.value || 0;
            const children = +childrenInput?.value || 0;
            const rooms = +roomsInput?.value || 0;

            // Validate name
            if (!name) {
                nameMsg && (nameMsg.textContent = "Enter your name");
                valid = false;
            }

            // Validate phone
            if (!phone || phone.length !== 10) {
                phoneMsg && (phoneMsg.textContent = "Enter valid 10 digit phone number");
                valid = false;
            }

            // Validate date
            if (!date) {
                dateMsg && (dateMsg.textContent = "Select date");
                valid = false;
            }

            // Validate guests/rooms
            if (adults + children + rooms <= 0) {
                adultsMsg && (adultsMsg.textContent = "Select at least one guest or room");
                valid = false;
            }

            if (!valid) return;

            const submitBtn = form.querySelector('[type="submit"]');
            const oldText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = "Submitting...";

            fetch("sendmail.php", {
                method: "POST",
                body: formData
            })
                .then(res => res.json())
                .then(data => {
                    if (data.status === "success") {
                        new bootstrap.Modal(document.getElementById("successModal")).show();

                        const modal = form.closest(".modal");
                        if (modal) {
                            bootstrap.Modal.getOrCreateInstance(modal).hide();
                        }

                        form.reset();
                    } else {
                        new bootstrap.Modal(document.getElementById("errorModal")).show();
                    }
                })
                .catch(() => {
                    new bootstrap.Modal(document.getElementById("errorModal")).show();
                })
                .finally(() => {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = oldText;
                });
        });

    });

});



// contact form
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById("contact_name").addEventListener("input", function () {
        this.value = this.value.replace(/[^A-Za-z\s]/g, "");
    });
});

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

    const form = document.getElementById('contactForm');
    const submitBtn = document.getElementById('contact_submit');

    const inputs = {
        name: document.getElementById('contact_name'),
        email: document.getElementById('contact_email'),
        phone: document.getElementById('contact_phone'),
        purpose: document.getElementById('contact_purpose'),
        checkin: document.getElementById('contact_checkin'),
        checkout: document.getElementById('contact_checkout'),
        message: document.getElementById('contact_message')
    };

    // Create message elements dynamically
    function createMsg(input) {
        const span = document.createElement("small");
        span.className = "text-danger d-block mt-1";
        input.parentNode.appendChild(span);
        return span;
    }

    const msgs = {
        name: createMsg(inputs.name),
        email: createMsg(inputs.email),
        phone: createMsg(inputs.phone),
        checkin: createMsg(inputs.checkin),
        checkout: createMsg(inputs.checkout)
    };

    // --- Live validations ---
    inputs.name.addEventListener('input', () => {
        const regex = /^[A-Za-z\s]+$/;
        if (!inputs.name.value.trim()) {
            msgs.name.textContent = "Enter your name";
        } else if (!regex.test(inputs.name.value.trim())) {
            msgs.name.textContent = "Name can contain only letters and spaces";
        } else {
            msgs.name.textContent = "";
        }
    });

    inputs.email.addEventListener('input', () => {
        const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        msgs.email.textContent = pattern.test(inputs.email.value.trim()) ? "" : "Enter a valid email";
    });

    inputs.phone.addEventListener('input', () => {
        inputs.phone.value = inputs.phone.value.replace(/\D/g, "");
        if (inputs.phone.value.length > 10) inputs.phone.value = inputs.phone.value.slice(0, 10);
        msgs.phone.textContent = inputs.phone.value.length === 10 ? "" : "Phone must be 10 digits";
    });

    function validateDate(input, msgBox) {
        if (!input.value) {
            msgBox.textContent = "Select a date";
            return false;
        }
        msgBox.textContent = "";
        return true;
    }

    inputs.checkin.addEventListener('change', () => validateDate(inputs.checkin, msgs.checkin));
    inputs.checkout.addEventListener('change', () => validateDate(inputs.checkout, msgs.checkout));

    // --- Submit form ---
    form.addEventListener('submit', function (e) {
        e.preventDefault();
        let valid = true;

        const nameRegex = /^[A-Za-z\s]+$/;
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!inputs.name.value.trim() || !nameRegex.test(inputs.name.value.trim())) {
            msgs.name.textContent = "Enter a valid name";
            valid = false;
        }

        if (!inputs.email.value.trim() || !emailPattern.test(inputs.email.value.trim())) {
            msgs.email.textContent = "Enter a valid email";
            valid = false;
        }

        if (!inputs.phone.value.trim() || inputs.phone.value.length !== 10) {
            msgs.phone.textContent = "Phone must be 10 digits";
            valid = false;
        }

        if (!validateDate(inputs.checkin, msgs.checkin)) valid = false;
        if (!validateDate(inputs.checkout, msgs.checkout)) valid = false;

        if (!valid) return;

        const formData = new FormData(form);

        submitBtn.disabled = true;
        const oldText = submitBtn.innerHTML;
        submitBtn.innerHTML = "Submitting...";

        fetch("contactmail.php", {
            method: "POST",
            body: formData
        })
            .then(res => res.json())
            .then(resData => {
                if (resData.status === "success") {
                    new bootstrap.Modal(document.getElementById('successModal')).show();
                    form.reset();
                } else {
                    new bootstrap.Modal(document.getElementById('errorModal')).show();
                }
            })
            .catch(() => new bootstrap.Modal(document.getElementById('errorModal')).show())
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = oldText;
            });
    });
});



// < !--Start of Tawk.to Script-- >

var Tawk_API = Tawk_API || {},
    Tawk_LoadStart = new Date();
(function () {
    var s1 = document.createElement("script"),
        s0 = document.getElementsByTagName("script")[0];
    s1.async = true;
    s1.src = 'https://embed.tawk.to/695d1fda1b9b1e197b60ffb3/1je9s8rm2';
    s1.charset = 'UTF-8';
    s1.setAttribute('crossorigin', '*');
    s0.parentNode.insertBefore(s1, s0);
})();


