"use strict";

var lumanPlusRecaptchaSettings = function () {

    const handleOptions = function () {
        $(document).on("select2:select", "select[name='default_recaptcha_version']", function (e) {
            e.preventDefault();

            var data = e.params.data;

            if (!data || !data.id || data.id.length === 0) {
                return;
            }

            const option = data.id;

            $(".recaptcha-setting").addClass("d-none disabled");
            $(`.recaptcha-setting[data-type="${option}"]`).removeClass("d-none disabled");
        });
    };


    const handleUpdate = function () {
        $(document).on("click", "#save_recaptcha_setting_button", function (e) {
            e.preventDefault();

            const $form = $("#luman_plus_recaptcha_settings_form");

            const defaultVersion = $form.find("select[name='default_recaptcha_version']").val();
            const $activeContainer = $form.find(`.recaptcha-setting:not(.d-none):not(.disabled)`);

            const visibleInputs = $form.find(":input[name]:not(:disabled):not(.d-none)").not('.recaptcha-setting :input');
            const activeInputs = $activeContainer.find(":input[name]:not(:disabled)");

            const allInputs = visibleInputs.add(activeInputs);
            const formData = allInputs.serialize();

            $.ajax({
                url: ajaxurl,
                type: "POST",
                data: {
                    action: 'luman_plus_save_recaptcha_settings',
                    data: formData
                },
                beforeSend: function () {
                    $('#save_recaptcha_setting_button').prop('disabled', true);
                    $('#save_recaptcha_setting_button .indicator-progress').show();
                    $('#save_recaptcha_setting_button .indicator-label').hide();
                },
                success: function (response) {
                    toastr.clear();
                    toastr.options.positionClass = "toast-bottom-left";

                    toastr.success("تنظیمات با موفقیت ذخیره شد");
                },
                error: function () {
                    toastr.error("خطایی در ذخیره‌سازی تنظیمات رخ داد");
                },
                complete: function () {
                    $('#save_recaptcha_setting_button').prop('disabled', false);
                    $('#save_recaptcha_setting_button .indicator-progress').hide();
                    $('#save_recaptcha_setting_button .indicator-label').show();
                }
            });
        });
    }


    return {
        init: function () {

            handleOptions();
            handleUpdate();
        }
    }
}();

KTUtil.onDOMContentLoaded(function () {
    lumanPlusRecaptchaSettings.init();
});