jQuery(document).ready(function($){
    
    // ---------------------- add dynamic fields to sms body
    $(document).on('click', '.dynamic_fields_placeholder .kes_field', function(){
        var text = $(this).attr('data-fieldid');
        text = '{{'+text+'}}';
        var teatarea_obj = $('#acf-field_658e7e01db05d');
        teatarea_obj.val(teatarea_obj.val() + text);
    });


    checkSelectValue();
    function checkSelectValue() {
        var selectValue = $('#acf-field_669a201a39167').val();
        if (selectValue !== '0') {
            selectFormOnChangeEvent(selectValue);
        }
    }

    // ---------------------- select elementor form 
    $('#acf-field_669a201a39167').on('change', function(){
        selectFormOnChangeEvent($(this).val())
    });

    $("#acf-field_658ef2e89bd46").on('change', function(){
        pattern_variables_generator($(this).val());        
    });

    function pattern_variables_generator(value) {
        var fieldsArray = ["pagename", "description", "date", "pageurl", "time", "name", "url"];
        var ippanel_result = "";
        var payamakpanel_result = "";
        counter = 0;
        var resultArray = [];
        for (var fieldValue of value) {
            var isField = fieldsArray.includes(fieldValue);
    
            if (!isField) {
                resultArray.push('<span>field' + fieldValue+ '</span>');
            } else {
                resultArray.push('<span>' + fieldValue + '</span>');

                ippanel_result += '<span>' + fieldValue + '</span>';
            }
            payamakpanel_result += '<span>' + "{"+counter+"}" + '</span>' ;
            counter++;
        }

        var IppanelSpanHtml =  resultArray.join("");
        var PayamakPanelSpanHtml = payamakpanel_result;
    
        // قرار دادن نتیجه در المان با سلکتور مشخص
        $('#ippanel .panel_vars').html(IppanelSpanHtml);
        $('#payamakpanel .panel_vars').html(PayamakPanelSpanHtml);
    }
    

    function selectFormOnChangeEvent(value) {
        var parts  = value.split("-");
        var formID = parts[0];
        var postID = parts[1];
        $('#acf-field_659057a750ce8').val(formID);
        $('#acf-field_65905e888d5bb').val(postID);
        jQuery.ajax({
            url: ajaxurl ,
            type: 'POST',
            data: {
                action: 'kes_get_elementor_form_fields',
                form_id : formID,
                post_id : postID,
                pageid: kesGetUrlParameter('post'),
            },
            beforeSend: function() {
                $('#optionsloadingwrapper').css('display', 'flex');
            },
            success: function(response) {
                
                if (response.success) {
                
                    // set normal sms variables
                    $('.dynamic_fields_placeholder').html(response.data.normal);
                    
                    // set recipients variables
                    var recipients_items = Object.entries(response.data.recipients).map(([key, value]) => {
                        return `<option value="${key}">${value}</option>`;
                    });
                    $("#acf-field_658fdd83aa83e").html(recipients_items);

                    $("#acf-field_658fdd83aa83e").val(response.data.selected_recipients);
                    $("#acf-field_658fdd83aa83e").trigger('change');

                   
                    var send_model = response.data.send_model;
                    if (send_model == 'pattern') {
                        
                        var allfields = response.data.pattern;
                        var selectedfields = response.data.pattern_selected;
    
                        var sortedObjectA = {};

                        selectedfields.forEach(function(key) {
                            if (allfields.hasOwnProperty(key)) {
                                sortedObjectA[key] = allfields[key];
                            }
                        });
    
                        Object.keys(allfields).forEach(function(key) {
                            if (!sortedObjectA.hasOwnProperty(key)) {
                                sortedObjectA[key] = allfields[key];
                            }
                        });
    
                        // set pattern sms variables
                        var pattern_items = Object.entries(sortedObjectA).map(([key, value]) => {
                            return `<option value="${key}">${value}</option>`;
                        });
                        $("#acf-field_658ef2e89bd46").html(pattern_items);
    
                        $("#acf-field_658ef2e89bd46").val(response.data.pattern_selected);
                        $("#acf-field_658ef2e89bd46").trigger('change');

                    } else {

                        // set pattern sms variables
                        var pattern_items = Object.entries(response.data.pattern).map(([key, value]) => {
                            return `<option value="${key}">${value}</option>`;
                        });
                        $("#acf-field_658ef2e89bd46").html(pattern_items);
                    }



                }
            },
            complete: function() {
                $('#optionsloadingwrapper').css('display', 'none');
            }
        });
    }

    function kesGetUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;
    
        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');
    
            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    };


});