var is_shared;
var is_ippanel;
var is_payamakpanel;
var is_kavehnegar;
var is_smsir;
var is_ghasedak;

var is_payamresan;
var is_dosefr98sms;
var is_asanak;




var passed_step;


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

    function manage_connection_fields() {
        
        $('#username').val('').show();
        $('#password').val('').show();
        $('#pattern').val('').show();
        $('#sender').val('').show();

        // hide all tutorials link
        $('.tut_suggestion').hide();
        
        // hide all tips
        $('.tips').hide();

        // ------------------- ghasedak
        if ( is_shared == 'no' ) {
            $('#pattern_not_need').show();
            $('#pattern').val('0').hide();
        }

        // ------------------- ghasedak
        if ( is_ghasedak == 'yes' && is_shared == 'yes' ) {
            $('#tut_ghasedak').show();
            $('#ghasedak_username_tip').show();
            $('#ghasedak_password_tip').show();
            $('#ghasedak_sender_tip').show();
            $('#username').val('0').hide();
            $('#sender').val('0').hide();
        }
        
        // ------------------- sms.ir
        if ( is_smsir == 'yes' && is_shared == 'yes' ) {
            $('#tut_smsir').show();
            $('#smsir_username_tip').show();
            $('#smsir_password_tip').show();
            $('#smsir_sender_tip').show();
            $('#username').val('0').hide();
            $('#sender').val('0').hide();
        }

        // ------------------- kavenegar
        if ( is_kavehnegar == 'yes' && is_shared == 'yes' ) {
            $('#tut_kavenegar').show();
            $('#kavenegar_password_tip').show();
            $('#password').val('0').hide();
        }

        // ------------------- payamak panel
        if ( is_payamakpanel == 'yes' && is_shared == 'yes' ) {
            $('#payamakpanel_sender_tip').show();
            $('#tut_payamakpanel').show();
            $('#sender').val('0').hide();
        }

        // ------------------- ippanel
        if ( is_ippanel == 'yes' && is_shared == 'yes' ) {
            $('#ippanel_sender_tip').show();
            $('#tut_ippanel').show();
            $('#sender').val('3000505');
        }
    }
    
    // init select2
    $('.kerasno_wizard_sms_panel').select2();
    
    // save sms company
    $('.smscompany').on('click', function(e) {
        e.preventDefault();
        var thisButton = $(this);
        var panel_name = $('.kerasno_wizard_sms_panel').val();
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wizard_save_company',
                panel : panel_name,
            },
            beforeSend: function() {
                thisButton.closest(".erp-setup-content").find(".kloading").removeClass("khide");
            },
            success: function(response) {               
                if (response.success) {
                    is_ippanel = response.data.is_ippanel;
                    is_payamakpanel = response.data.is_payamakpanel;
                    is_shared = response.data.is_shared;
                    is_dosefr98sms = response.data.is_dosefr98sms;
                    is_asanak = response.data.is_asanak;
                    is_payamresan = response.data.is_payamresan;
                    is_kavehnegar = response.data.is_kavehnegar;
                    is_smsir = response.data.is_smsir;
                    is_ghasedak = response.data.is_ghasedak;

                    mreeir_notification(response.data.message);
                    thisButton.siblings('.skip-wizard-step').trigger('click');
                    manage_connection_fields();
                } else {
                    mreeir_notification(response.data.message, false);
                }
            },
            complete: function() {
              thisButton.closest(".erp-setup-content").find(".kloading").addClass("khide");
            }
        });
    });

    // save connection settings
    $('.connection').on('click', function(e) {
        e.preventDefault();
        var thisButton = $(this);
        var $username = $('#username').val();
        var $password = $('#password').val();
        var $pattern = $('#pattern').val();
        var $sender = $('#sender').val();

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wizard_save_connection_settings',
                username: $username,
                password: $password,
                pattern: $pattern,
                sender: $sender,
            },
            beforeSend: function() {
                thisButton.closest(".erp-setup-content").find(".kloading").removeClass("khide");
            },
            success: function(response) {               
                if (response.success) {
                    mreeir_notification(response.data.message);
                    thisButton.siblings('.skip-wizard-step').trigger('click');
                    $('#mobile').focus();
                } else {
                    mreeir_notification(response.data.message, false);
                }
            },
            complete: function() {
              thisButton.closest(".erp-setup-content").find(".kloading").addClass("khide");
            }
        });
    });


    $("#checkout_force_login, #woo_myaccount_redirect, #woo_resetpass_redirect, #woo_fill_bill_phone").click(function(){
        var isChecked = $(this).prop("checked"); 
        // $(this).prop("checked", !isChecked);
        if(isChecked){
            $(this).attr('checked', true);
        } else {
            $(this).attr('checked', false);
        }
    });

    // save woocommerce settings
    $('.woocommerce').on('click', function(e) {
        e.preventDefault();
        var thisButton = $(this);
        var $checkout_force_login = $('#checkout_force_login').prop("checked");
        var $woo_myaccount_redirect = $('#woo_myaccount_redirect').prop("checked");
        var $woo_resetpass_redirect = $('#woo_resetpass_redirect').prop("checked");
        var $woo_fill_bill_phone = $('#woo_fill_bill_phone').prop("checked");

        if ( $checkout_force_login) {
            $checkout_force_login = 'yes';
        } else {
            $checkout_force_login = 'no';
        }

        if ( $woo_myaccount_redirect) {
            $woo_myaccount_redirect = 'yes';
        } else {
            $woo_myaccount_redirect = 'no';
        }

        if ( $woo_resetpass_redirect) {
            $woo_resetpass_redirect = 'yes';
        } else {
            $woo_resetpass_redirect = 'no';
        }

        if ( $woo_fill_bill_phone) {
            $woo_fill_bill_phone = 'yes';
        } else {
            $woo_fill_bill_phone = 'no';
        }


        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wizard_save_woocommerce_settings',
                checkout_force_login: $checkout_force_login,
                woo_myaccount_redirect: $woo_myaccount_redirect,
                woo_resetpass_redirect: $woo_resetpass_redirect,
                woo_fill_bill_phone: $woo_fill_bill_phone,
            },
            beforeSend: function() {
                thisButton.closest(".erp-setup-content").find(".kloading").removeClass("khide");
            },
            success: function(response) {               
                if (response.success) {
                    mreeir_notification(response.data.message);
                } else {
                    mreeir_notification(response.data.message, false);
                }
            },
            complete: function() {
              thisButton.closest(".erp-setup-content").find(".kloading").addClass("khide");
            }
        });
    });

    function wizard_change_current_value(selector, number, minus = false) {
        var currentValue = parseInt($(selector).text());
        var newValue = '';
        if (! minus ) {
            newValue = currentValue + number;
        } else {
            newValue = currentValue - number;
        }
        $(selector).animate({
            opacity: 0
        }, 500, function() {
            $(this).text(newValue).css('color', 'green');
            $(this).animate({
                opacity: 1
            }, 500);
        });
    }

    // migrate mobile numbers
    $('.migration').on('click', function(e) {
        e.preventDefault();
        var thisButton = $(this);

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wizard_migrate_mobiles',
            },
            beforeSend: function() {
                thisButton.closest(".erp-setup-content").find(".kloading").removeClass("khide");
            },
            success: function(response) {               
                if (response.success) {
                    mreeir_notification(response.data.message);
                    wizard_change_current_value('span.value.kerasno', response.data.billing + response.data.digits);
                    wizard_change_current_value('span.value.digits', response.data.digits, true);
                    wizard_change_current_value('span.value.billing', response.data.billing, true);
                } else {response.data.billing
                    mreeir_notification(response.data.message, false);
                }
            },
            complete: function() {
              thisButton.closest(".erp-setup-content").find(".kloading").addClass("khide");
            }
        });
    });

    $('#mobile').keypress(function (e) {
        var key = e.which;
        if(key == 13)  // the enter key code
        {
            $('#sendtest').click();
            return false;  
        }
    });
    // test send
    $('#sendtest').on('click', function(e) {
        e.preventDefault();
        var thisButton = $(this);
        var $mobile = $('#mobile').val();
        
        if (!mreeir_is_mobile($mobile)) {
            mreeir_notification(wizard_messeges.mobileNumberNotValid, false);
            return;
        }

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mreeir_send_sms_panel_test',
                mobile: $mobile,
                panel : 'master_panel',
                security: nonce,
            },
            beforeSend: function() {
                thisButton.closest(".erp-setup-content").find(".kloading").removeClass("khide");
            },
            success: function(response) {             
                if ( response == 'success' ) {
                    mreeir_notification(wizard_messeges.testSMSSent);
                } 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 ) {
                                mreeir_notification(response.data.message, false);
                            } else {
                                if ( response == 'wrong-info' ) {
                                    mreeir_notification(wizard_messeges.mobileNumberNotValid, false);
                                }
                                if ( response == 'send-failed' ) {
                                    mreeir_notification(wizard_messeges.testSMSSentFailed, false);
                                }
                            }
                        },
                        complete: function() {
                        }
                    }); // end inner ajax

                }
            },
            complete: function() {
                thisButton.closest(".erp-setup-content").find(".kloading").addClass("khide");
            }
        });
    });
    
    // navigation click
    $('.wizard-navigation').on('click', function(e){
        e.preventDefault();
        $('.wizard-navigation').removeClass('active');
        $(this).addClass('active');

        var current_id = $(this).attr('data-stepnumber');
        $('.erp-setup-content').css('display', 'none');
        $('.erp-setup-content[data-stepnumber="'+ current_id +'"]').css('display', 'flex');
    });

    // prevent # in url
    $('.wizard-navigation a').on('click', function(e){
        e.preventDefault();
    });

    // first step
    $('.wizard_first_step').on('click', function(e){
        e.preventDefault();
        var activeStepNumber = $('li.active').data('stepnumber');
        $('li.active').removeClass('active');
        $('li[data-stepnumber="' + (activeStepNumber + 1) + '"]').addClass('active');
        $('li[data-stepnumber="' + (activeStepNumber + 1) + '"]').trigger('click');
    });

    // skip button
    $('.skip-wizard-step').click(function(e) {
        e.preventDefault();
        var activeStepNumber = $('li.active').data('stepnumber');
        $('li.active').removeClass('active');
        $('li[data-stepnumber="' + (activeStepNumber + 1) + '"]').addClass('active');
        $('li[data-stepnumber="' + (activeStepNumber + 1) + '"]').trigger('click');
    });


    // functions
    function mreeir_notification (message, success = true, time = 4) {
        var background_color = '#dc3545';
        if (success) {
            background_color = 'green';
        }

        $.toast({
            text: message,
            showHideTransition: 'fade',
            textAlign: 'center',
            stack: true,
            position: 'bottom-center',
            bgColor: background_color,
            textColor: '#fff',
            loaderBg: '#222',
            class: 'mreeir-error-toast',
            hideAfter: time * 1000 ,
            allowToastClose: false,
        });
    }

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

    function mreeir_correct_mobile_number( $mobile ) {
        var inputs = "" + $mobile;
        new_val = inputs.replace(/۰/g, '0').replace(/۱/g, '1').replace(/۲/g, '2').replace(/۳/g, '3').replace(/۴/g, '4').replace(/۵/g, '5').replace(/۶/g, '6').replace(/۷/g, '7').replace(/۸/g, '8').replace(/۹/g, '9').replace(/٤/g, '4').replace(/٥/g, '5').replace(/٦/g, '6');        
        new_val = new_val.replace(/٠/g, '0').replace(/١/g, '1').replace(/٢/g, '2').replace(/٣/g, '3').replace(/٤/g, '4').replace(/۵/g, '5').replace(/٦/g, '6').replace(/٧/g, '7').replace(/٨/g, '8').replace(/٩/g, '9').replace(/٤/g, '4').replace(/٥/g, '5').replace(/٦/g, '6');
        return new_val;   
    }

    var wizard_messeges = {
        mobileNumberNotValid:"شماره موبایل معتبر نیست",
        testSMSSent:"پیامک تست با موفقیت ارسال شد",
        testSMSSentFailed:"خطا در ارسال پیامک؛ تنظیمات خود را بررسی کنید",
        successSaved:"ذخیره سازی با موفقیت انجام شد",
        failSaved:"متاسفانه ذخیره سازی انجام نشد",
    };

});