<?php include "app_modal.php"; ?>
<!-- <script src="<?= site_url; ?>/assets/js/bootstrap.js"></script> -->
<!-- <script src="<?= site_url; ?>/assets/js/wow.min.js"></script> -->
<!-- <script src="<?= site_url; ?>/assets/js/owl.carousel.js"></script> -->
<!-- <script src="<?= site_url; ?>/assets/js/jquery-fancybox.min.js"></script> -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.0.2/wow.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.1.20/jquery.fancybox.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@25.2.1/build/js/intlTelInput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.9.0/jquery.validate.min.js"></script>
<script src="<?= site_url; ?>/assets/js/theme.js"></script>
<script>
setTimeout(function() {
    const script = document.createElement("script");
    script.src = "https://www.google.com/recaptcha/api.js";
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
}, 5000);
</script>




<script>
/* WhatsApp Form Validation*/
$(document).ready(function() {
   
    if (typeof $.fn.validate === "function") {
        // Initialize validator without static rules for 'mobile'
        $("#whatsapp_form").validate({
            rules: {
                name: "required"
            },
            messages: {
                name: "Please Enter Your Name"
            }
        });

        // Now setup the phone field and its dynamic validation
        setupPhoneValidation("#whatsapp_form");
    } else {
        console.error("jQuery Validate is not loaded.");
    }

    // Form submission handler
    $('#whatsapp_form').submit(function(e) {
        e.preventDefault();

        const input = $("#whatsapp_form .telePhone")[0];
        const selectedCountry = iti.getSelectedCountryData();

        updatePhoneValidation("#whatsapp_form", input, selectedCountry);

        // Check form validity
        if (!$("#whatsapp_form").valid()) {
            return false;
        }

        $(':input[type="submit"]').prop('disabled', true);

        $.ajax({
            url: '<?= site_url; ?>/whatsapp_enq.php',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(result) {
                if (result.status == false) {
                    $('.wht_success_message').text('');
                    $('.wht_error_message').text(result.message_response);
                } else {
                    $('.wht_error_message').text('');
                    $('.wht_success_message').text(
                        "You Have Successfully Submitted enquiry. We will contact you soon."
                    );
                    $('#whatsapp_form').trigger("reset");
                    window.open(result.message_response, '_blank');
                }
                $(':input[type="submit"]').prop('disabled', false);
            },
            error: function() {
                $('.wht_error_message').text('Something went wrong. Please try again.');
                $(':input[type="submit"]').prop('disabled', false);
            }
        });

        return false;
    });
});

/* WhatsApp Form Validation*/


/*enq_pop_form1 */
$(document).ready(function() {
 
        $("#enq_pop_form1").validate({
            rules: {
                name: "required",
                message: {
                    required: true
                },
                location: {
                    required: true
                },
                email: {
                    required: true
                },
             
            },
            messages: {
                name: "Please enter your name",
                message: {
                    required: "Please enter your message"
                },
                email: {
                    required: "Please enter your email address"
                },
                location: {
                    required: "Please enter your location"
                },
                mobile: {
                    required: "Please enter your mobile no.",
                    number: "Mobile No. contains only numbers",
                    minlength: "Your Mobile No. must be at least 10 digits long",
                    maxlength: "Your Mobile No. must be at most 17 digits long",
                },
            },
            errorPlacement: function(error, element) {
                const group = element.closest(".phone-group");

                if (group.length) {
                    group.find(".error-message")
                        .html(error.text())
                        .css("color", "red");
                } else {
                    error.insertAfter(element);
                }
            },
            submitHandler: function(form) {
                $.ajax({
                    url: '<?= site_url; ?>/enquiry_popup.php',
                    type: "POST",
                    data: $("#enq_pop_form1").serialize(),
                    dataType: "json",
                    success: function(response) {
                        if (response.status === true) {
                            $("#enq_pop_up").text(response.message_response).css(
                                "color", "green");
                            $("#enq_pop_form1")[0].reset();
                            grecaptcha.reset();
                        } else {
                            $("#enq_pop_up").text(response.message_response).css(
                                "color", "red");
                        }
                    },
                });
            }
        });
         setupPhoneValidation("#enq_pop_form1");
   
});

/* enq_pop_form1*/


/*product_pop_form */


$(document).ready(function() {
   


        $("#product_pop_form").validate({
            rules: {
                name: "required",
                message: {
                    required: true
                },
                location: {
                    required: true
                },
                quantity: {
                    required: true
                },
                email: {
                    required: true
                },
                mobile: {
                    required: true,
                    number: true,
                    minlength: 10, // Default for India
                    maxlength: 17,
                },
            },
            messages: {
                name: "Please enter your name",
                message: {
                    required: "Please enter your message"
                },
                email: {
                    required: "Please enter your email address"
                },
                location: {
                    required: "Please enter your location"
                },
                quantity: {
                    required: "Please enter your minimum order quantity"
                },
                mobile: {
                    required: "Please enter your mobile no.",
                    number: "Mobile No. contains only numbers",
                    minlength: "Your Mobile No. must be at least 10 digits long",
                    maxlength: "Your Mobile No. must be at most 4-17 digits long",
                },
            },
             errorPlacement: function(error, element) {
                const group = element.closest(".phone-group");

                if (group.length) {
                    group.find(".error-message")
                        .html(error.text())
                        .css("color", "red");
                } else {
                    error.insertAfter(element);
                }
            },
            submitHandler: function(form) {
                $.ajax({
                    url: '<?= site_url; ?>/enquirycat_popup.php',
                    type: "POST",
                    data: $("#product_pop_form").serialize(),
                    dataType: "json",
                    success: function(response) {
                        if (response.status === true) {
                            $("#cat_pop_up").text(response.message_response).css(
                                "color", "green");
                            $("#product_pop_form")[0].reset();
                            grecaptcha.reset();
                        } else {
                            $("#cat_pop_up").text(response.message_response).css(
                                "color", "red");
                        }
                    },
                });
            }
        });
    setupPhoneValidation("#product_pop_form");
});

/*product_pop_form */

/* Call back */
$(document).ready(function() {
  

        $("#callback_form").validate({
            rules: {
                name: "required",
                mobile: {
                    required: true,
                    number: true,
                    minlength: 10, // Default for India
                    maxlength: 17,
                },
            },
            messages: {
                name: "Please enter your name",
                mobile: {
                    required: "Please enter your mobile no.",
                    number: "Mobile No. contains only numbers",
                    minlength: "Your Mobile No. must be at least 10 digits long",
                    maxlength: "Your Mobile No. must be at most 4-17 digits long",
                },
            },
                    errorPlacement: function(error, element) {
                const group = element.closest(".phone-group");

                if (group.length) {
                    group.find(".error-message")
                        .html(error.text())
                        .css("color", "red");
                } else {
                    error.insertAfter(element);
                }
            },
            submitHandler: function(form) {
                $(':input[type="submit"]').prop('disabled', true);
                $.ajax({
                    url: '<?= site_url; ?>/ajax_enq_action.php',
                    type: "POST",
                    data: $("#callback_form").serialize(),
                    dataType: "json",
                    success: function(response) {
                        if (response.status === true) {
                            $("#cpop_up").text(response.message_response).css("color",
                                "green");
                            $("#callback_form")[0].reset();
                            grecaptcha.reset();
                        } else {
                            $("#cpop_up").text(response.message_response).css("color",
                                "red");
                        }
                    },
                });
            }
        });
        setupPhoneValidation("#callback_form");
   
});
/*Call Back */

/* Contact page Form*/

$(document).ready(function() {
   
    // Validate form only if jQuery Validate is available
 
        $("#contact_form").validate({
            rules: {
                name: "required",
                message: {
                    required: true
                },
                location: {
                    required: true
                },
                email: {
                    required: true,
                    email: true
                },
             
            },
            messages: {
                name: "Please enter your name",
                message: {
                    required: "Please enter your message"
                },
                email: {
                    required: "Please enter your email address",
                    email: "Enter a valid email address"
                },
                location: {
                    required: "Please enter your location"
                },
                mobile: {
                    required: "Please enter your mobile no.",
                    number: "Mobile No. contains only numbers",
                    
                },
            },
              errorPlacement: function(error, element) {
                const group = element.closest(".phone-group");

                if (group.length) {
                    group.find(".error-message")
                        .html(error.text())
                        .css("color", "red");
                } else {
                    error.insertAfter(element);
                }
            },
            submitHandler: function(form) {
                $.ajax({
                    url: '<?= site_url; ?>/contact.php',
                    type: "POST",
                    data: $("#contact_form").serialize(),
                    dataType: "json",
                    success: function(response) {
                        if (response.status === true) {
                            $("#pop_up").text(response.message_response).css("color",
                                "green");
                            $("#contact_form")[0].reset();
                            grecaptcha.reset();
                        } else {
                            $("#pop_up").text(response.message_response).css("color",
                                "red");
                        }
                    },
                });
            }
        });
   
    setupPhoneValidation("#contact_form");
});

  
function ValidateAlpha(evt) {

    var keyCode = (evt.which) ? evt.which : evt.keyCode

    if ((keyCode < 65 || keyCode > 90) && (keyCode < 97 || keyCode > 123) && keyCode != 32)

        return false;

    return true;

}

function isNumberKey(evt) {

    //var e = evt || window.event;

    var charCode = (evt.which) ? evt.which : evt.keyCode

    if (charCode != 46 && charCode > 31 &&

        (charCode < 48 || charCode > 57))

        return false;

    return true;

}

function validateOnlyTextField(element) {

    var str = element.value;

    if (str == ' ') {

        element.value = "";

    }

    if (!(/^[a-zA-Z\s]+$/.test(str))) {

        // console.log('String contain number characters');

        str = str.substr(0, str.length - 1);

        element.value = "";

    }

}




//disabling context menu

document.onkeydown = function(e) {

    if (e.ctrlKey &&

        (e.keyCode === 67 ||

            e.keyCode === 86 ||

            e.keyCode === 85 ||

            e.keyCode === 117)) {

        return false;

    } else {

        return true;

    }

};

$(document).keypress("u", function(e) {

    if (e.ctrlKey) {

        return false;

    } else {

        return true;

    }

});

document.addEventListener("contextmenu", function(e) {

    e.preventDefault();

}, false);
</script>

<script>
/* =====================================================
   SETUP PHONE VALIDATION (PER PHONE GROUP)
===================================================== */
/* =====================================================
   SETUP PHONE VALIDATION (PER PHONE GROUP)
===================================================== */
function setupPhoneValidation(group, options = {}) {

    const input     = group.querySelector(".phone-input");
    const codeInput = group.querySelector(".country_code");
    const nameInput = group.querySelector(".country_name");
    const isoInput  = group.querySelector(".country_iso");
    const errorEl   = group.querySelector(".error-message");

    if (!input) return;

    const iti = window.intlTelInput(input, {
        initialCountry: "",
        separateDialCode: true,
        allowDropdown: true,
        dropdownContainer: options.dropdownContainer || document.body,
        utilsScript:
          "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/25.2.1/build/js/utils.min.js"
    });

    // clear hidden fields initially
    codeInput.value = "";
    nameInput.value = "";
    isoInput.value  = "";

    // country change
    input.addEventListener("countrychange", () => {
        const c = iti.getSelectedCountryData();

        codeInput.value = c.dialCode || "";
        nameInput.value = c.name || "";
        isoInput.value  = c.iso2 || "";

        errorEl.textContent = "";
        updatePhoneRules(input.closest("form"), input, c);
    });

    // sanitize input
    input.addEventListener("input", () => {
        input.value = input.value.replace(/\D/g, "").replace(/^0+/, "");
        errorEl.textContent = "";
    });

    // validation function (FIXED)
    group.validatePhone = function () {

        if (!isoInput.value) {
            errorEl.textContent = "Please select country code";
            input.focus();              // ✅ supported
            return false;
        }

        // OPTIONAL strict validation
        // if (!iti.isValidNumber()) {
        //     errorEl.textContent = "Please enter a valid mobile number";
        //     return false;
        // }

        return true;
    };
}

/* =====================================================
   UPDATE RULES (jQuery Validate Sync)
===================================================== */
function updatePhoneRules(form, input, country) {
    let validator = $(form).data("validator");
    if (!validator) return;

    let field = input.name;

    if (country.iso2 === "in") {
        $(input).attr({ minlength: 10, maxlength: 10 });

        validator.settings.rules[field] = {
            required: true,
            minlength: 10,
            maxlength: 10,
            digits: true
        };

        validator.settings.messages[field] = {
            required: "Please enter your mobile no.",
            minlength: "Your Mobile No. must be 10 digits",
            maxlength: "Your Mobile No. must be 10 digits"
        };
    } else {
        $(input).attr({ minlength: 4, maxlength: 17 });

        validator.settings.rules[field] = {
            required: true,
            minlength: 4,
            maxlength: 17,
            digits: true
        };

        validator.settings.messages[field] = {
            required: "Please enter your mobile no.",
            minlength: "Your Mobile No. must be 4–17 digits long",
            maxlength: "Your Mobile No. must be 4–17 digits long"
        };
    }
}


/* =====================================================
   INIT ALL PHONE GROUPS
===================================================== */
function initAllPhoneGroups(root = document) {
    root.querySelectorAll(".phone-group").forEach(group => {
        if (!group._itiInitialized) {
            setupPhoneValidation(group, {
                dropdownContainer: group.closest(".modal") || document.body
            });
            group._itiInitialized = true;
        }
    });
}

document.addEventListener("DOMContentLoaded", () => {
    initAllPhoneGroups(document);
});
/* =====================================================
   PAGE LOAD
===================================================== */
// document.addEventListener("DOMContentLoaded", () => {
//     initAllPhoneGroups(document);
// });

/* =====================================================
   MODAL SUPPORT
===================================================== */
document.addEventListener("shown.bs.modal", e => {
    initAllPhoneGroups(e.target);
});

/* =====================================================
   FORM SUBMIT (🔥 MAIN FIX HERE)
===================================================== */
document.querySelectorAll("form").forEach(form => {
    form.addEventListener("submit", function (e) {

        //e.preventDefault(); // ❗ ALWAYS stop first

        let allValid = true;

        form.querySelectorAll(".phone-group").forEach(group => {
            if (!group.validatePhone()) {
                allValid = false;
            }
        });

        if (!allValid) {
            return false; // ❌ STOP – no popup, no ajax
        }

        /* ✅ ONLY VALID FORM REACHES HERE */

        // If normal submit required
        // form.submit();

        // OR if AJAX submit
        if (typeof $ !== "undefined") {
            $.ajax({
                url: form.action,
                type: "POST",
                data: $(form).serialize(),
                success: function () {
                    $(".success-msg")
                        .text("Submitted Successfully.")
                        .show();
                }
            });
        }
    });
});
</script>