jQuery(document).ready( function($) {

        $('div[data-name="woosub_panel"] div[data-type="message"].acf-field .acf-label').click(function(){
            var _this = $(this);
            var current_text = _this.find('label').text();
            var _panel = _this.parent('.acf-field').siblings('div[data-name="woosmspanel"]').find('select').val();               
            var _username = _this.parent('.acf-field').siblings('div[data-name="username"]').find('input').val();
            var _password = _this.parent('.acf-field').siblings('div[data-name="password"]').find('input').val();
            var _sender = _this.parent('.acf-field').siblings('div[data-name="sender_number"]').find('input').val();
            var _pattern = _this.parent('.acf-field').siblings('div[data-name="pattern"]').find('input').val();
            var _mobile = _this.parent('.acf-field').siblings('div[data-name="woosub_test_mobile"]').find('input').val();
            var variables_or_text = '';

            if ( ! woosub_is_mobile(_mobile) ) {
                woosub_show_error('شماره موبایل را وارد کنید');
                return;
            }

            if (_this.closest('.acf-field.acf-field-group').siblings('.acf-field-textarea:not(.acf-hidden)').find('textarea').length > 0) {
                variables_or_text = _this.closest('.acf-field.acf-field-group').siblings('.acf-field-textarea:not(.acf-hidden)').find('textarea').val();
            } else {
                variables_or_text = _this.closest('.acf-field.acf-field-group').siblings('.acf-field-select').find('select').val();
            }
            if ( ! woosub_is_empty('_pattern') ) {
                variables_or_text = JSON.stringify(variables_or_text);
            }
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'woosub_send_test_sms',
                    panel : _panel,
                    username : _username,
                    password : _password,
                    sender : _sender,
                    pattern : _pattern,
                    mobile : _mobile,
                    variablesortext : variables_or_text,
                },
                beforeSend: function() {
                    _this.find('label').text('در حال انجام ...');
                },
                success: function (response) {
                    if (response.success) {
                        woosub_show_success(response.data.message);    
                    } else {
                        jQuery.ajax({ // start inner ajax
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'kerasno_get_last_send_error',
                            },
                            beforeSend: function() {
                            },
                            success: function(response) {               
                                if ( response.success ) {
                                    woosub_show_error(response.data.message);
                                } else {
                                    if ( response == 'wrong-info' ) {
                                        woosub_show_error(mreeir_messeges.mobileNotValid);
                                    }
                                    if ( response == 'send-failed' ) {
                                        woosub_show_error(mreeir_messeges.testSMSSentFailed);
                                    }
                                }
                            },
                            complete: function() {
                            }
                        }); // end inner ajax
                    }
                },
                    complete: function() {
                    _this.find('label').text(current_text);
                }
            });
    
        });

        $(document).on('click','div[data-name="woocom_ared_panel"] div[data-type="message"].acf-field .acf-label', function(){
                var _this = $(this);
                var current_text = _this.find('label').text();
                var _panel = _this.parent('.acf-field').siblings('div[data-name="woosmspanel"]').find('select').val();               
                var _username = _this.parent('.acf-field').siblings('div[data-name="username"]').find('input').val();
                var _password = _this.parent('.acf-field').siblings('div[data-name="password"]').find('input').val();
                var _sender = _this.parent('.acf-field').siblings('div[data-name="sender_number"]').find('input').val();
                var _pattern = _this.parent('.acf-field').siblings('div[data-name="pattern"]').find('input').val();
                var _mobile = _this.parent('.acf-field').siblings('div[data-name="woosub_test_mobile"]').find('input').val();
                var variables_or_text = '';

                if ( ! woosub_is_mobile(_mobile) ) {
                    woosub_show_error('شماره موبایل را وارد کنید');
                    return;
                }

                if (_this.closest('.acf-field.acf-field-group').siblings('.acf-field-textarea:not(.acf-hidden)').find('textarea').length > 0) {
                    variables_or_text = _this.closest('.acf-field.acf-field-group').siblings('.acf-field-textarea:not(.acf-hidden)').find('textarea').val();
                } else {
                    variables_or_text = _this.closest('.acf-field.acf-field-group').siblings('div[data-name="woocom_ared_vars"].acf-field-select').find('select').val();
                }
                if ( ! woosub_is_empty('_pattern') ) {
                    variables_or_text = JSON.stringify(variables_or_text);
                }
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'woosub_send_test_sms',
                        panel : _panel,
                        username : _username,
                        password : _password,
                        sender : _sender,
                        pattern : _pattern,
                        mobile : _mobile,
                        variablesortext : variables_or_text,
                    },
                    beforeSend: function() {
                        _this.find('label').text('در حال انجام ...');
                    },
                    success: function (response) {
                        if (response.success) {
                            woosub_show_success(response.data.message);    
                        } else {
                            jQuery.ajax({ // start inner ajax
                                url: ajaxurl,
                                type: 'POST',
                                data: {
                                    action: 'kerasno_get_last_send_error',
                                },
                                beforeSend: function() {
                                },
                                success: function(response) {               
                                    if ( response.success ) {
                                        woosub_show_error(response.data.message);
                                    } else {
                                        if ( response == 'wrong-info' ) {
                                            woosub_show_error(mreeir_messeges.mobileNotValid);
                                        }
                                        if ( response == 'send-failed' ) {
                                            woosub_show_error(mreeir_messeges.testSMSSentFailed);
                                        }
                                    }
                                },
                                complete: function() {
                                }
                            }); // end inner ajax
                        }
                    },
                        complete: function() {
                        _this.find('label').text(current_text);
                    }
                });

        }); 
        
        $(document).on('click','div[data-name="woocom_afinish_panel"] div[data-type="message"].acf-field .acf-label', function(){
            var _this = $(this);
            var current_text = _this.find('label').text();
            var _panel = _this.parent('.acf-field').siblings('div[data-name="woosmspanel"]').find('select').val();               
            var _username = _this.parent('.acf-field').siblings('div[data-name="username"]').find('input').val();
            var _password = _this.parent('.acf-field').siblings('div[data-name="password"]').find('input').val();
            var _sender = _this.parent('.acf-field').siblings('div[data-name="sender_number"]').find('input').val();
            var _pattern = _this.parent('.acf-field').siblings('div[data-name="pattern"]').find('input').val();
            var _mobile = _this.parent('.acf-field').siblings('div[data-name="woosub_test_mobile"]').find('input').val();
            var variables_or_text = '';

            if ( ! woosub_is_mobile(_mobile) ) {
                woosub_show_error('شماره موبایل را وارد کنید');
                return;
            }

            if (_this.closest('.acf-field.acf-field-group').siblings('.acf-field-textarea:not(.acf-hidden)').find('textarea').length > 0) {
                variables_or_text = _this.closest('.acf-field.acf-field-group').siblings('.acf-field-textarea:not(.acf-hidden)').find('textarea').val();
                console.log('aaaaaaaaaaaaa');
            } else {
                variables_or_text = _this.closest('.acf-field.acf-field-group').siblings('div[data-name="woocom_afinish_vars"].acf-field-select').find('select').val();
                console.log('BBBBBBBBBBBB');
            }
            if ( ! woosub_is_empty('_pattern') ) {
                variables_or_text = JSON.stringify(variables_or_text);
            }
            console.log("🚀 ~ $ ~ variables_or_text:", variables_or_text)
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'woosub_send_test_sms',
                    panel : _panel,
                    username : _username,
                    password : _password,
                    sender : _sender,
                    pattern : _pattern,
                    mobile : _mobile,
                    variablesortext : variables_or_text,
                },
                beforeSend: function() {
                    _this.find('label').text('در حال انجام ...');
                },
                success: function (response) {
                    if (response.success) {
                        woosub_show_success(response.data.message);    
                    } else {
                        jQuery.ajax({ // start inner ajax
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'kerasno_get_last_send_error',
                            },
                            beforeSend: function() {
                            },
                            success: function(response) {               
                                if ( response.success ) {
                                    woosub_show_error(response.data.message);
                                } else {
                                    if ( response == 'wrong-info' ) {
                                        woosub_show_error(mreeir_messeges.mobileNotValid);
                                    }
                                    if ( response == 'send-failed' ) {
                                        woosub_show_error(mreeir_messeges.testSMSSentFailed);
                                    }
                                }
                            },
                            complete: function() {
                            }
                        }); // end inner ajax
                    }
                },
                    complete: function() {
                    _this.find('label').text(current_text);
                }
            });

        });
            

        $('.inline_action_viewlist').click(function(e) {
            e.preventDefault();
            var currentBTN = $(this);
            var rowID = $(this).attr('data-recordid');
            var current_text = currentBTN.text();

            var targetTable = 'sms';
            if ($('body').hasClass('admin_page_woosub-emailsendlist')) {
                targetTable = 'email';
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'woosub_action_recipients_list',
                    rowid: rowID,
                    target : targetTable,
                },
                beforeSend: function() {
                    currentBTN.text('در حال انجام ...');
                    $('#my_thickbox_content').html('');
                },
                
                success: function (response) {
                    if (response.success) {
                        var recipients = JSON.parse(response.data.message[0]); // تبدیل پاسخ به آرایه
                        var recipientList = '<ul>'; // آماده‌سازی لیست HTML
                        $.each(recipients, function(index, recipient) {
                            recipientList += '<li>' + recipient + '</li>';
                        });
                        recipientList += '</ul>';
                        recipientList = '<button id="copy_recipients_btn">کپی کردن</button>' + recipientList;
                        // قراردادن لیست در داخل ThickBox
                        $('#my_thickbox_content').html(recipientList);

                        // نمایش لیست در ThickBox بعد از اینکه محتوای جدید اضافه شد
                        tb_show('لیست گیرندگان', '#TB_inline?width=600&height=400&inlineId=my_thickbox_content', null);

                         $('#copy_recipients_btn').click(function() {
                            var allRecipients = recipients.join(', ');
                            navigator.clipboard.writeText(allRecipients).then(function() {
                                alert('کپی انجام شد !');
                            }).catch(function(error) {
                                alert('خطایی در کپی کردن رخ داد: ' + error);
                            });
                        });

                        currentBTN.text(current_text);
                    } else {
                        currentBTN.text(current_text);
                        woosub_show_error(response.data.message);
                    }
                },
                comnplete: function(){
                    currentBTN.text(current_text);
                }
            });
        });


        $('.woosubaction-addtoqueue').click(function(e) {
            e.preventDefault();
            var currentBTN = $(this);
            var rowID = $(this).attr('data-recordid');
            var currentStatusID = $(this).attr('data-currentstatus');
            var current_text = currentBTN.text();
            var _email_or_sms = 'sms';
            if ($('body').hasClass('admin_page_woosub-emailsendlist')) {
                _email_or_sms = 'email';
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'woosub_action_add_to_queue',
                    rowid: rowID,
                    currentstatus: currentStatusID,
                    emailorsms : _email_or_sms,
                },
                beforeSend: function() {
                    currentBTN.text('در حال انجام ...');
                },
                
                success: function (response) {
                    if (response.success) {
                        woosub_show_success(response.data.message);
                        var newBTNLabel = 'در صف ارسال';
                        if ( currentStatusID == 1 ) {
                            newBTNLabel = 'ارسال مجدد ناموفق ها';
                        }
                        if ( currentStatusID == 6 ) {
                            newBTNLabel = 'ارسال مجدد کامل';
                        }
                        currentBTN.parent('td.actions.column-actions').siblings('td.send_status.column-send_status').html('<span style="font-weight:bold;color:#000">'+newBTNLabel+'</span>');
                        currentBTN.text('لغو');
                        currentBTN.removeClass('woosubaction-addtoqueue');
                        currentBTN.addClass('woosubaction-cancelsend');
                    } else {
                        currentBTN.text(current_text);
                        woosub_show_error(response.data.message);
                    }
                },
            });
        });

        $('.woosubaction-cancelsend').click(function(e) {
            e.preventDefault();
            var currentBTN = $(this);
            var rowID = $(this).attr('data-recordid');
            var current_text = currentBTN.text();
            var _email_or_sms = 'sms';
            if ($('body').hasClass('admin_page_woosub-emailsendlist')) {
                _email_or_sms = 'email';
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'woosub_action_cancel',
                    rowid: rowID,
                    emailorsms : _email_or_sms,
                },
                beforeSend: function() {
                    currentBTN.text('در حال انجام ...');
                },
                
                success: function (response) {
                    if (response.success) {
                        woosub_show_success(response.data.message);
                        currentBTN.parent('td.actions.column-actions').siblings('td.send_status.column-send_status').html('<span style="font-weight:bold;color:brown;">لغو شده</span>');
                        currentBTN.text('افزودن به صف ارسال');
                        currentBTN.removeClass('woosubaction-cancelsend');
                        currentBTN.addClass('woosubaction-addtoqueue');
                    } else {
                        currentBTN.text(current_text);
                        woosub_show_error(response.data.message);
                    }
                },
            });
        });

        // test dedicated email server
        if ( $('.acf-field.acf-field-button-group.acf-field-670a34e72143a .acf-input label').length > 0 ) {
            var testEmailBTN = $('.acf-field.acf-field-button-group.acf-field-670a34e72143a .acf-input label');
            testEmailBTN.click(function(){
                var current_text = testEmailBTN.text();
                var host = $('input#acf-field_670a305065267-field_670a306a65268').val();
                var port = $('input#acf-field_670a305065267-field_670a30af65269').val();
                var username = $('input#acf-field_670a305065267-field_670a310c6526b').val();
                var password = $('input#acf-field_670a305065267-field_670a31436526c').val();
                var sender = $('input#acf-field_670a305065267-field_670a31546526d').val();
                var auth = $('.acf-field.acf-field-button-group.acf-field-670a5bea54089 .acf-button-group label.selected input').val();
                var ssltsl = $('.acf-field.acf-field-button-group.acf-field-670a30cc6526a .acf-button-group label.selected input').val();

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'woosub_send_test_email',
                        host: host,
                        port: port,
                        ssltsl: ssltsl,
                        username: username,
                        password: password,
                        sender: sender,
                        auth: auth,
                    },
                    beforeSend: function() {
                        testEmailBTN.text('در حال انجام ...');
                    },
                    success: function (response) {
                        if (response.success) {
                            woosub_show_success(response.data.message);    
                        } else {
                            woosub_show_error(response.data.message);    
                        }
                    },
                     complete: function() {
                        testEmailBTN.text(current_text);
                    }
                });
        
            });
        }
        
        setTimeout(function() {
            $("select[id^='acf-field_65ce7028e69d6']").trigger('change');
            $("select[id^='acf-field_66ea9f524f3b4']").trigger('change');
            $("select[id^='acf-field_66ed209d0fca2']").trigger('change');
        }, 2000);
        
        // ---------------------- add dynamic fields to sms body
        $(document).on('click', '.woocomsms_fields_wrapper span', function(){
            var text = $(this).attr('data-fieldid');
            text = '{{'+text+'}}';
            var teatarea_obj = $(this).closest('.acf-field').siblings('.acf-field-textarea').find('textarea');
            teatarea_obj.val(teatarea_obj.val() + text);
        });
        
        // ---------------------- add dynamic fields to email body
        $(document).on('click', 'div#acf-group_670971c42087c .woocomsms_fields_wrapper span', function() {
            var text = $(this).attr('data-fieldid');
            text = '{{' + text + '}}';

            // پیدا کردن نام فیلد WYSIWYG مرتبط
            var field = $(this).closest('.acf-field').siblings('.acf-field-wysiwyg');
            var textarea_id = field.find('textarea.wp-editor-area').attr('id');
            
            // دسترسی به ادیتور فعال TinyMCE
            var editor = tinyMCE.get(textarea_id);

            if (editor && !editor.isHidden()) {
                // درج متن در مکان‌نما یا انتهای محتوا
                editor.execCommand('mceInsertContent', false, ' ' + text);
            } else {
                // اگر ادیتور در حالت Text (HTML) بود
                var textarea = $('#' + textarea_id);
                textarea.val(textarea.val() + ' ' + text);
            }
        });

        //add normal sms variable to sms body
        $(document).on('click', '.woosub_fields_wrapper span', function(){
            var field = "{{" + $(this).data('fieldid') + "}}";           
            $(this).closest('.acf-field').siblings('.acf-field[data-name="woocom_ared_body"]').find('textarea').append(field);
        });
        
        //show pattern variable to user
        $(document).on('change', '.acf-field[data-name="woosub_vars"] select', function() {
            
            var value = $(this).val();
            var payamakpanel_result = "";
            counter = 0;
            var resultArray = [];
            for (var fieldValue of value) {
                resultArray.push("<span>" + fieldValue + "</span>");
                payamakpanel_result += "<span>" + "{" + counter + "}" + "</span>";
                counter++;
            }

            var IppanelSpanHtml = resultArray.join("");
            var PayamakPanelSpanHtml = payamakpanel_result;

            $(this).closest('.acf-field').siblings('.acf-field-message').find(".ippanel .panel_vars").html(IppanelSpanHtml);
            $(this).closest('.acf-field').siblings('.acf-field-message').find(".payamakpanel .panel_vars").html(PayamakPanelSpanHtml);
        });

        // Populate panel_vars on page load
        function populatePanelVarsOnLoad() {
            // For woosub_vars select fields
            $('.acf-field[data-name="woosub_vars"] select').each(function() {
                var value = $(this).val();
                if (value) {
                    updatePanelVars($(this), value);
                }
            });
            
            // For woocom_afinish_vars select fields
            $('.acf-field[data-name="woocom_afinish_vars"] select').each(function() {
                var value = $(this).val();
                if (value) {
                    updatePanelVars($(this), value);
                }
            });
            
            // For woocom_ared_vars select fields
            $('.acf-field[data-name="woocom_ared_vars"] select').each(function() {
                var value = $(this).val();
                if (value) {
                    updatePanelVars($(this), value);
                }
            });
            
            // For acf-field-65cf0fac6ee02 select fields
            $('.acf-field-65cf0fac6ee02 select').each(function() {
                var value = $(this).val();
                if (value) {
                    woosub_pattern_variables_generator(value, $(this));
                }
            });
        }
        
        // Helper function to update panel vars (extracted from existing change handlers)
        function updatePanelVars(selectElement, value) {
            var payamakpanel_result = "";
            var counter = 0;
            var resultArray = [];
            if (value && Array.isArray(value)) {
                for (var fieldValue of value) {
                    resultArray.push("<span>" + fieldValue + "</span>");
                    payamakpanel_result += "<span>" + "{" + counter + "}" + "</span>";
                    counter++;
                }
            }

            var IppanelSpanHtml = resultArray.join("");
            var PayamakPanelSpanHtml = payamakpanel_result;

            selectElement.closest('.acf-field').siblings('.acf-field-message').find(".ippanel .panel_vars").html(IppanelSpanHtml);
            selectElement.closest('.acf-field').siblings('.acf-field-message').find(".payamakpanel .panel_vars").html(PayamakPanelSpanHtml);
        }
        
        // Call the function after a short delay to ensure DOM is fully loaded
        setTimeout(populatePanelVarsOnLoad, 1000);
            
        //show pattern variable to user
        $(document).on('change', '.acf-field[data-name="woocom_afinish_vars"] select', function() {
            
            var value = $(this).val();
            var payamakpanel_result = "";
            counter = 0;
            var resultArray = [];
            for (var fieldValue of value) {
                resultArray.push("<span>" + fieldValue + "</span>");
                payamakpanel_result += "<span>" + "{" + counter + "}" + "</span>";
                counter++;
            }

            var IppanelSpanHtml = resultArray.join("");
            var PayamakPanelSpanHtml = payamakpanel_result;

            $(this).closest('.acf-field').siblings('.acf-field-message').find(".ippanel .panel_vars").html(IppanelSpanHtml);
            $(this).closest('.acf-field').siblings('.acf-field-message').find(".payamakpanel .panel_vars").html(PayamakPanelSpanHtml);
        });

        $(document).on('change', '.acf-field[data-name="woocom_ared_vars"] select', function(){
            var value = $(this).val();
            // var fieldsArray = ["sitename", "sitetagline", "date", "time"];
            var payamakpanel_result = "";
            counter = 0;
            var resultArray = [];
            for (var fieldValue of value) {
                resultArray.push("<span>" + fieldValue + "</span>");
                payamakpanel_result += "<span>" + "{" + counter + "}" + "</span>";
                counter++;
            }

            var IppanelSpanHtml = resultArray.join("");
            var PayamakPanelSpanHtml = payamakpanel_result;

            $(this).closest('.acf-field').siblings('.acf-field[data-name="woocom_ared_normalvar"]').find(".ippanel .panel_vars").html(IppanelSpanHtml);
            $(this).closest('.acf-field').siblings('.acf-field[data-name="woocom_ared_normalvar"]').find(".payamakpanel .panel_vars").html(PayamakPanelSpanHtml);
        });


        // shortcode copy
        $('.ksscs-wapper').on('click',function(){
            var sc_to_copy = $(this).children('.ksscs-holder').html();
            kerasnocopyToClipboard(sc_to_copy);
            $(this).children('.ks-sc-copied').fadeIn('fast').delay(2000).fadeOut();
        });

        function kerasnocopyToClipboard(element) {
            var $temp = $("<input>");
            $("body").append($temp);
            $temp.val(element).select();
            document.execCommand("copy");
            $temp.remove();
        }


        $(document).on('change', '.acf-field-65cf0fac6ee02 select', function() {
            woosub_pattern_variables_generator($(this).val(), $(this));        
        });

        function woosub_pattern_variables_generator(value, object) {
            
            var fieldsArray = ["producttitle", "productid", "productsku", "producturl", "date", "time", "sitename", "sitetagline"];
            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;
        
            // قرار دادن نتیجه در المان با سلکتور مشخص
            object.closest('.acf-field').siblings('.acf-field-65d05e4ee5b5d').find('.ippanel.panel_wrapper .panel_vars').html(IppanelSpanHtml);
            object.closest('.acf-field').siblings('.acf-field-65d05e4ee5b5d').find('.payamakpanel.panel_wrapper .panel_vars').html(PayamakPanelSpanHtml);
        }

        function woosub_show_success(message) {
            $.toast({
                text: message,
                showHideTransition: 'fade',
                textAlign: 'center',
                stack: false,
                position: 'bottom-center',
                bgColor: '#3c763d',
                textColor: '#ffffff',
                loaderBg: 'green',
                class: 'woosub-toast',
                hideAfter: 10000,
                allowToastClose: false,
            });
        }

        function woosub_show_error (message) {
            $.toast({
                text: message,
                showHideTransition: 'fade',
                textAlign: 'center',
                stack: false,
                position: 'bottom-center',
                bgColor: '#ef342f',
                textColor: '#ffffff',
                loaderBg: '#c10500',
                class: 'woosub-toast',
                hideAfter: 10000,
                allowToastClose: false,
            });
        }


        // check empty function
        function woosub_is_empty (data) {
            if(typeof(data) === 'object'){
                if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
                    return true;
                }else if(!data){
                    return true;
                }
                return false;
            }else if(typeof(data) === 'string'){
                if(!data.trim()){
                    return true;
                }
                return false;
            }else if(typeof(data) === 'undefined'){
                return true;
            }else{
                return false;
            }
        }


        // check mobile format
        var woosub_is_mobile = function (mobileNumber) {
            var regex = /^09\d{9}$/;
            return regex.test(mobileNumber);
        }

});// end document ready

