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

    $(document).on('click', '.followup_copy_code', function() {
        var copy_btn = $(this);
        var sc_to_copy = copy_btn.siblings('.followup_code_value').text();
        keproFollowupCopyToClipboard(sc_to_copy);
        copy_btn.text('کپی شد');
        setTimeout(
        function() 
        {
          copy_btn.html(' کپی <span>&#10064;</span>');
        }, 2000);
        
    });

    function keproFollowupCopyToClipboard(element) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(element).select();
        document.execCommand("copy");
        $temp.remove();
    }
    
    $('#fu_code').keypress(function (e) {
        var key = e.which;
        if(key == 13)  // the enter key code
        {
            $(this).siblings('#fu_submit_code').click();
            return false;  
        }
    });


    $('#fu_submit_code').on('click',function(e) {
        e.preventDefault();
        var $this = $(this);
        var fu_code = $('#fu_code').val();
        
        // check order id
        if (followup_is_empty(fu_code)) {
            followup_frontend_messages_generator(followup_messeges.DeliveryCodeWrong);
            return;
        }
        
        var dataToPass = {
                    action: 'followup_search_order_by_delivery_code',
                    code : fu_code,
                    security: followup_front_options.fusearchbydeliverycodenonce,
                };
    
        jQuery.ajax({
            url: followup_front_options.ajaxurl,
            type: 'POST',
            dataType: "html",
            data: dataToPass,
            beforeSend: function(){
              $this.text('در حال جستجوی کد تحویل ...');
            },
            success: function(response) {
              if (response == 'code_not_valid') {
                followup_frontend_messages_generator('کد تحویل معتبر نیست');
              } else if (response == 'order_not_found') {
                followup_frontend_messages_generator('مرسوله ای با این کد تحویل وجود ندارد');
              } else {
                  $('#followup_tracking_body').remove();
                  $('#followup_tracking_wrapper').append(response);
              }
            },
            complete: function() {
              $this.text('بررسی کد تحویل');
            }
        });
    });

    $(document).on('click', '#confirm_devlivery_code',function(e) {
        e.preventDefault();
        var $this = $(this);
        var fu_order_id = $this.attr('data-orderid');
        var fu_code = $this.attr('data-code');
        
        // check order id
        if (followup_is_empty(fu_order_id)) {
            followup_frontend_messages_generator(followup_messeges.OrderIDWrong);
            return;
        }
        // check delivery code
        if (followup_is_empty(fu_code)) {
            followup_frontend_messages_generator(followup_messeges.DeliveryCodeWrong);
            return;
        }
        
        var dataToPass = {
                    action: 'followup_save_order_delivery_code',
                    orderid : fu_order_id,
                    code : fu_code,
                    security: followup_front_options.fusavedeliverycodenonce,
                };
    
        jQuery.ajax({
            url: followup_front_options.ajaxurl,
            type: 'POST',
            dataType: "html",
            data: dataToPass,
            beforeSend: function(){
              $this.find('p span').text('در حال ثبت کد تحویل ...');
            },
            success: function(response) {
              if (response == 'delivery_code_save_failed') {
                followup_frontend_messages_generator('خطایی در ثبت کد تحویل رخ داد', false, '#followup_submit_code_message');
              } else {
                followup_frontend_messages_generator('کد تحویل با موفقیت ثبت شد', true, '#followup_submit_code_message');
                $this.remove();
              }
            },
            complete: function() {
              $this.text('تایید و ثبت کد تحویل');
            }
        });
    });

    
    $('#fu_order_id').keypress(function (e) {
        var key = e.which;
        if(key == 13)  // the enter key code
        {
            $(this).siblings('#fu_submit_search').click();
            return false;  
        }
    });

    $('#fu_submit_search').on('click',function(e) {
        e.preventDefault();
        
        var $this = $(this);
        var fu_order_id = $('#fu_order_id').val();
        var fu_user_id = $('#fu_user_id').val();
        var spam_detector = $('#spam_detector').val();
        
        // check order id
        if (followup_is_empty(fu_order_id)) {
            followup_frontend_messages_generator(followup_messeges.OrderIDWrong);
            return;
        }
        
        // check user id
        if (followup_is_empty(fu_user_id)) {
            followup_frontend_messages_generator(followup_messeges.UserIDWrong);
            return;
        }
        
        // check spam
        if ( ! followup_is_empty(spam_detector)) {
            followup_frontend_messages_generator(followup_messeges.SpamDetected);
            return;
        }
    
        var dataToPass = {
                    action: 'followup_search_order',
                    orderid : fu_order_id,
                    userid : fu_user_id,
                    spam : spam_detector,
                    security: followup_front_options.fusearchordernonce,
                };
    
        
        jQuery.ajax({
            url: followup_front_options.ajaxurl,
            type: 'POST',
            dataType: "html",
            data: dataToPass,
            beforeSend: function(){
              $this.text('در حال جستجو ...');
            },
            success: function(response) {

              var IS_JSON = true;
              try
              {
                var json = $.parseJSON(response);
              }
              catch(err)
              {
                IS_JSON = false;
              }       
              $('#followup_tracking_body').remove();
              if (IS_JSON) {
                if (! response.success) {
                  var responseJson = JSON.parse(response);               
                  followup_frontend_messages_generator(responseJson.data.message);
                }
              } else {
                $('#followup_tracking_wrapper').append(response); 
              }
            },
            complete: function() {
              $this.text('پیگیری سفارش');
            }
        });
    });



    // check empty
    var followup_is_empty = function (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;
        }
    };


    function followup_frontend_messages_generator($message, $success = false, $element='') {
        var cssClass = 'followup-error';
        if ($success == true) {
            cssClass = 'followup-success';
        }

        var target = '#followup_messages';
        if (!followup_is_empty($element)) {
            target = $element;
        }

        $(target).text($message);
        $(target).addClass(cssClass);
        $(target).fadeIn().delay(3000).fadeOut()
    }

    var followup_messeges = {
        DeliveryCodeWrong: "کد تحویل معتبر نیست",
        OrderIDWrong: "شماره سفارش معتبر نیست",
        UserIDWrong: "کاربر معتبر نیست",
        SpamDetected: "فیلد تشخیص ربات معتبر نیست",
      };
});