(function ($) {
    "use strict";

    $(document).on("submit", "form.ajax", function (e) {
        e.preventDefault();
        var dataTableId = $(this).data("table-id");
        var modalId = $(this).data("modal-id");
        var callback = $(this).data("callback");
        var a, s, o, n, r, i, c = $(this).prop("enctype");

        // Add spinner and disable the button
        $(this).find("button[type='submit']").attr("disabled", "true");
        $(this).find("button[type='submit']").prepend('<i class="fa fa-spinner fa-spin"></i> ');

        a = $(this).prop("method");  // HTTP Method
        s = $(this).prop("action"); // URL
        o = function (response) {
            window[callback](response, dataTableId, modalId);
        };
        n = function (error) {
            window[callback](error, dataTableId, modalId);
        };

        r = new FormData($(this)[0]); // Form data
        i = {
            type: a,
            url: s,
            dataType: "json",
            success: o,
            error: n
        };

        if (r !== undefined) {
            i.data = r;
        }
        if ("POST" === a || "post" === a) {
            i.encType = "enctype";
            i.contentType = false;
            i.processData = false;
        }

        $.ajax(i);
    });

    window.formResponse = function (e, d, m) {
        $("form.ajax .fa-spin").remove();
        $("form.ajax button[type='submit']").removeAttr("disabled");
        if (e.status === 'success') {
            toastr.success(e.message);
            if (d !== 'undefined' && d !== '') {
                $("#" + d).DataTable().ajax.reload();
            }
            if (m !== 'undefined' && m !== '') {
                $("#" + m).modal("hide");
            }
        } else {
            toastr.error(e.responseJSON.message);
        }
    }

    $(document).ready(function () {
        let csrfToken = $('meta[name="csrf-token"]').attr('content');
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': csrfToken
            }
        });
    });

    function commonAjaxHelper(method, route, data, successCallback, errorCallback) {
        $.ajax({
            type: method,
            url: route,
            data: data,
            success: function (response) {
                if (successCallback && typeof successCallback === 'function') {
                    successCallback(response);
                }
            },
            error: function (xhr, status, error) {
                if (errorCallback && typeof errorCallback === 'function') {
                    errorCallback(xhr, status, error);
                }
            }
        });
    }

    window.commonAjaxHelper = commonAjaxHelper

    $(document).on('input', '.email-frontend-settings-validation', function () {
        $(this).siblings('.error').remove();
        const email = $(this).val().trim();
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (email === '') {
            $(this).after('<span class="error d-inline-block error fs-6 ms-1 mt-2 text-danger">Email is required.</span>');
        } else if (!emailPattern.test(email)) {
            $(this).after('<span class="error d-inline-block error fs-6 ms-1 mt-2 text-danger">Invalid email format.</span>');
        }
    })
    $(document).on('input', '.phone-frontend-settings-validation', function () {
        $(this).siblings('.error').remove();
        const phone = $(this).val().trim();
        const phonePattern = /^(?:\+?\d{1,3})?[-.\s]?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}$/;
        if (phone === '') {
            $(this).after('<span class="error d-inline-block error fs-6 ms-1 mt-2 text-danger" >Phone number is required.</span>');
        } else if (!phonePattern.test(phone)) {
            $(this).after('<span class="error d-inline-block error fs-6 ms-1 mt-2 text-danger" >Invalid phone number format.</span>');
        }
    })

    $(document).on('click', '.phone-frontend-settings-validation', function () {
        $(this).siblings('.error').remove();
        const phone = $(this).val().trim();
        const phonePattern = /^(?:\+?\d{1,3})?[-.\s]?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}$/;
        if (phone === '') {
            $(this).after('<span class="error d-inline-block error fs-6 ms-1 mt-2 text-danger" >Phone number is required.</span>');
        } else if (!phonePattern.test(phone)) {
            $(this).after('<span class="error d-inline-block error fs-6 ms-1 mt-2 text-danger" >Invalid phone number format.</span>');
        }
    })

    function getWebPageContentWithoutImages(url) {
        $.ajax({
            url: url,
            method: 'GET',
            success: function (response) {
                // Create a temporary element to parse the HTML content
                var tempDiv = $('<div>').html(response);

                // Remove all image tags
                tempDiv.find('img').remove();

                // Get the cleaned content
                var contentWithoutImages = tempDiv.html();

            },
            error: function () {
                console.error('Failed to fetch the content from the URL');
            }
        });
    }

    function loadingHide(selector, selectorType) {
        var selectorText = selector;

        if (selectorType === 'id') {
            selectorText = '#' + selector;
        } else if (selectorType === 'class') {
            selectorText = '.' + selector;
        }

        // Corrected element selection
        $(selectorText + " .fa-spin").remove();
        $(selectorText).removeAttr("disabled");
    }

    window.loadingHide = loadingHide;

    function loadingShow(selector, selectorType) {
        var selectorText = selector;

        if (selectorType === 'id') {
            selectorText = '#' + selector;
        } else if (selectorType === 'class') {
            selectorText = '.' + selector;
        }

        // Corrected element selection
        $(selectorText).attr("disabled", "true");
        $(selectorText).prepend('<i class="fa fa-spinner fa-spin"></i> ');
    }

    window.loadingShow = loadingShow;


})(window.jQuery);
