"use strict";

var lumanPlusServiceSettings = function () {

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

            var data = e.params.data;

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

            const option = data.id;

            $(".service_detail_container").addClass("d-none disabled");
            $(`.${option}`).removeClass("d-none disabled");
        });
    };


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

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

            const defaultService = $form.find("select[name='default_service']").val();
            const $activeContainer = $form.find(`.service_detail_container.${defaultService}:not(.d-none):not(.disabled)`);

            const visibleInputs = $form.find(":input[name]:not(:disabled):not(.d-none)").not('.service_detail_container :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_service_settings',
                    data: formData
                },
                beforeSend: function () {
                    $('#save_service_setting_button').prop('disabled', true);
                    $('#save_service_setting_button .indicator-progress').show();
                    $('#save_service_setting_button .indicator-label').hide();
                },
                success: function (response) {
                    toastr.clear();
                    toastr.options.positionClass = "toast-bottom-left";
                    console.log(toastr.options);

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


    return {
        init: function () {

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

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