"use strict";

var lumanPlusPatternSettings = function () {

    const getDetails = function (){
        $(document).on("click",".edit-pattern",function (e){
            e.preventDefault();

            let patternID = $(this).attr('data-pattern-id') ?? 0;

            if ( patternID === 0 ) {
                return;
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'luman_plus_get_pattern_detail',
                    patternID: patternID
                },
                success: function (response){
                    const data = response.data.data ?? {};

                    $("#edit_pattern_modal").modal('show');

                    $("#edit_pattern_modal").find('input[name="pattern_code"]').val(data.pattern ?? '');
                    $("#edit_pattern_modal").find(".pattern-head").text(` [ ${data.name} ]`);
                    $("#edit_pattern_modal").find("#save_service_pattern_setting_button").attr({
                        'data-pattern-id':patternID
                    });

                }
            })

        })
    }

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

            let patternID = $(this).attr('data-pattern-id') ?? 0;

            if ( patternID === 0 ) {
                return;
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    'action': 'luman_plus_save_pattern',
                    'pattern_id': patternID,
                    'pattern_code': $('input[name="pattern_code"]').val(),
                },
                success: function (response) {
                    $("#edit_pattern_modal").modal('hide');

                    if ( response.success ) {
                        toastr.success(response.data.message);
                    }{
                        toastr.warning(response.data.message)
                    }
                },
                error: function (response) {
                    toastr.warning(response.data.message)
                }
            })

        })
    }

    return {
        init: function () {
            getDetails();
            handleUpdate();

            $("#edit_pattern_modal_close").on('click',function (e){
                $("#edit_pattern_modal").modal('hide');
            })
        }
    }
}();

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