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

  if ($('body.wp-admin.post-type-shop_order').length > 0) {
    jalaliDatepicker.startWatch({
        maxDate: 'today',
        zIndex: '999999999',
        autoReadOnlyInput : 'true',
    });
  }

  $(function() {
      setTimeout(function() {
          $(".followup_success,.followup_error").fadeOut(500)
      }, 3000);
  });

  function followup_action_generator(checkbox_obj, character) {
    
    if ($('.fu_send_tracking_codes').length > 0) {
      var dataActionValue = $('.fu_send_tracking_codes').attr('data-action');

      if( checkbox_obj.is(":checked") ){
        if(dataActionValue.indexOf(character) === -1){
          dataActionValue += character;
        }
      } else {
          dataActionValue = dataActionValue.replace(character, '');
      }
      $('.fu_send_tracking_codes').attr('data-action', dataActionValue);
    }
    if ($('#followup_submit_tracking').length > 0) {
      var dataActionValue = $('#followup_submit_tracking').attr('data-action');

      if( checkbox_obj.is(":checked") ){
        if(dataActionValue.indexOf(character) === -1){
          dataActionValue += character;
        }
      } else {
          dataActionValue = dataActionValue.replace(character, '');
      }
      $('#followup_submit_tracking').attr('data-action', dataActionValue);
    }

  }
  
  function followup_add_character_to_action(character) {
    if ($('.fu_send_tracking_codes').length > 0) {
      var dataActionValue = $('.fu_send_tracking_codes').attr('data-action');
      if(dataActionValue.indexOf(character) === -1){
        dataActionValue += character;
        $('.fu_send_tracking_codes').attr('data-action', dataActionValue);
      }
    }
    if ($('#followup_submit_tracking').length > 0) {
      var dataActionValue = $('#followup_submit_tracking').attr('data-action');
      if(dataActionValue.indexOf(character) === -1){
        dataActionValue += character;
        $('#followup_submit_tracking').attr('data-action', dataActionValue);
      }
    }
  }

  function followup_remove_character_to_action(character) {
    if ($('.fu_send_tracking_codes').length > 0) {
      var dataActionValue = $('.fu_send_tracking_codes').attr('data-action');
      dataActionValue = dataActionValue.replace(character, '');
      $('.fu_send_tracking_codes').attr('data-action', dataActionValue);
    }
    if ($('#followup_submit_tracking').length > 0) {
      var dataActionValue = $('#followup_submit_tracking').attr('data-action');
      dataActionValue = dataActionValue.replace(character, '');
      $('#followup_submit_tracking').attr('data-action', dataActionValue);
    }
  }

  function followupCheckIfAtLeastOneChecked(checkboxIds) {
      var atLeastOneChecked = false;
      for(var i = 0; i < checkboxIds.length; i++){
          if($('#' + checkboxIds[i]).prop('checked')){
              atLeastOneChecked = true;
              return true;
          }
      }
      return false;
  }

  $('#saveinadminnote').on('change', function(){
    followup_action_generator($(this), 'a');
  });
  $('#saveincustomernote').on('change', function(){
    followup_action_generator($(this), 'c');
  });
  $('#saveinorderdata').on('change', function(){
    followup_action_generator($(this), 'o');
  });


  $('.remove_order_tracking_info').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);  
    var trackingId = $this.data('trackingid');
      
      // نمایش پیام تاییدیه
      if (confirm('آیا مطمئن هستید که می‌خواهید این اطلاعات را حذف کنید؟')) {
          // ارسال درخواست AJAX به فایل admin-ajax.php در وردپرس
          $.ajax({
              type: 'POST',
              url: ajaxurl, // از متغیر ajaxurl وردپرس برای تعیین مسیر استفاده کنید
              data: {
                  action: 'remove_tracking_info', // نام عملیات وردپرس
                  tracking_id: trackingId // شناسه پیگیری برای حذف
              },
              beforeSend: function(){
                $this.siblings('.fu-element-wrapper.fu-loading').removeClass('fu-hide');
              },
              success: function(response) {
                  if (response == 'success') {
                    $this.parent('.fut_info').remove();
                  } else {
                    alert('حذف اطلاعات انجام نشد');
                  }
                  
              },
              complete:function(){
                $this.siblings('.fu-element-wrapper.fu-loading').addClass('fu-hide');
              }
          });
      }
  });

  $('#sendsms').on('change', function(){
    if($(this).is(':checked')){
      $('#followup_submit_tracking').text('ثبت و ارسال کد رهگیری');
      followup_add_character_to_action('s');
    } else {
      $('#followup_submit_tracking').text('ثبت کد رهگیری');
      followup_remove_character_to_action('s');
    }
  });

  $('#preventsms').on('change', function(){
    if($(this).is(':checked')){
      $('#followup_submit_tracking').text('ثبت کد رهگیری');
      followup_remove_character_to_action('s');
    } else {
      $('#followup_submit_tracking').text('ثبت و ارسال کد رهگیری');
      followup_add_character_to_action('s');
    }
  });

  $(document).ready(function() {
    if ($('#productsSelect').length > 0) {
      $('#productsSelect').select2(); 
    }
  });

  jQuery( function($){
    // on upload button click
    $( 'body' ).on( 'click', '.rudr-upload', function( event ){
      event.preventDefault(); // prevent default link click and page refresh
      
      const button = $(this)
      const imageId = button.next().next().val();
      
      const customUploader = wp.media({
        title: 'انتخاب تصویر', // modal window title
        library : {
          uploadedTo : wp.media.view.settings.post.id, // attach to the current post?
          type : 'image'
        },
        button: {
          text: 'استفاده از این تصویر' // button label text
        },
        multiple: false
      }).on( 'select', function() { // it also has "open" and "close" events
        const attachment = customUploader.state().get( 'selection' ).first().toJSON();
        button.removeClass( 'button' ).html( '<img src="' + attachment.url + '">'); // add image instead of "Upload Image"
        button.next().show(); // show "Remove image" link
        button.next().next().val( attachment.id ); // Populate the hidden field with image ID
      })
      
      // already selected images
      customUploader.on( 'open', function() {
  
        if( imageId ) {
          const selection = customUploader.state().get( 'selection' )
          attachment = wp.media.attachment( imageId );
          attachment.fetch();
          selection.add( attachment ? [attachment] : [] );
        }
        
      })
  
      customUploader.open()
    
    });
    // on remove button click
    $( 'body' ).on( 'click', '.rudr-remove', function( event ){
      event.preventDefault();
      const button = $(this);
      button.next().val( '' ); // emptying the hidden field
      button.hide().prev().addClass( 'button' ).html( 'تصویر مرسوله' ); // replace the image with text
    });
  });

  $('.fu_send_tracking_codes').on('click',function(e) { 
    e.preventDefault();
    if (confirm("آیا برای این انجام این عملیات مطمئن هستید؟")) {
      var fileName = $(this).attr('data-filename');

      var checkboxIds = ['sendsms', 'saveinadminnote', 'saveincustomernote', 'saveinorderdata']; // به عنوان مثال
      var action_result = followupCheckIfAtLeastOneChecked(checkboxIds);

      // check order id
      if ( ! action_result ) {
        followup_admin_messages_generator(followup_messeges.MinActionRequired);
        return;
      }


      var actions_list = $(this).attr('data-action');


      if (followup_is_empty(fileName)) {
          alert('نام فایل معتبر نیست');
      }

      jQuery.ajax({
          url: followup_admin_options.ajaxurl,
          type: 'POST',
          data: {
              action: 'followup_send_bulk_sms',
              filename : fileName,
              action_todo : actions_list,
          },
          beforeSend: function() {
            $('.mreeir-element-wrapper.mreeir-loading').removeClass('mreeir-hide');
          },
          success: function(response) {
            $('.mreeir-element-wrapper.mreeir-loading').addClass('mreeir-hide');
            alert(response.data.message);
            location.reload();
          },
          complete: function() {
            $('.mreeir-element-wrapper.mreeir-loading').addClass('mreeir-hide');
          }
      });
    }
  });

  $('.fu_delete_file').on('click',function(e) { 
    e.preventDefault();
    if (confirm("آیا مطمئن هستید که می‌خواهید این فایل را حذف کنید؟")) {
      var fileName = $(this).attr('data-filename');

      if (followup_is_empty(fileName)) {
          alert('نام فایل معتبر نیست');
      }

      jQuery.ajax({
          url: followup_admin_options.ajaxurl,
          type: 'POST',
          data: {
              action: 'followup_delete_file',
              filename : fileName,
          },
          beforeSend: function() {
            $('.mreeir-element-wrapper.mreeir-loading').removeClass('mreeir-hide');
          },
          success: function(response) {
            $('.mreeir-element-wrapper.mreeir-loading').addClass('mreeir-hide');
            alert(response.data.message);
            location.reload();
          },
          complete: function() {
            $('.mreeir-element-wrapper.mreeir-loading').addClass('mreeir-hide');
          }
      });
  }

  });

  $('#followup_submit_tracking').on('click',function(e) {
      e.preventDefault();
      var $this = $(this);
      var fu_action = $this.attr('data-action');
      var fu_order_id = $('#followup_orderid').val();
      var mobile   = $('#followup_mobile').val();
      var fu_tracking_code = $('#followup_tracking_code').val();

      var fu_image = $('#rudr_img').val();
      var fu_date = $('#followup_date').val();
      var fu_selected_products = $('#productsSelect').val();
      var fu_selected_company = $('#shippingcompanies_dropdown').val();


      var checkboxIds = ['sendsms', 'saveinadminnote', 'saveincustomernote', 'saveinorderdata']; // به عنوان مثال
      var action_result = followupCheckIfAtLeastOneChecked(checkboxIds);

      // check order id
      if ( ! action_result ) {
        followup_admin_messages_generator(followup_messeges.MinActionRequired);
        return;
      }

      // check order id
      if (followup_is_empty(fu_order_id)) {
          followup_admin_messages_generator(followup_messeges.OrderIDWrong);
          return;
      }
      
      // check mobile
      if (fu_action == 'ss') {
        if (followup_is_empty(mobile) || ! followup_is_mobile(mobile)) {
            followup_admin_messages_generator(followup_messeges.MobileWrong);
            return;
        }
      }

      // check tracking code
      if (followup_is_empty(fu_tracking_code)) {
          followup_admin_messages_generator(followup_messeges.TrackingcCodeWrong);
          return;
      }

      var dataToPass = {
                  action: 'followup_submit_data',
                  orderid : fu_order_id,
                  to : mobile,
                  trackingcode : fu_tracking_code,
                  action_method : fu_action,
                  image : fu_image,
                  date : fu_date,
                  products : fu_selected_products,
                  company: fu_selected_company,
                  security: followup_admin_options.noncefusendsms,
              };

      for (k in dataToPass){
          if(dataToPass[k]=="") delete dataToPass[k];
      }
      
      jQuery.ajax({
          url: followup_admin_options.ajaxurl,
          type: 'POST',
          dataType: "html",
          data: dataToPass,
          beforeSend: function() {
            $this.parent('#kerasno_smstoc_su_wrapper').siblings('.fu-element-wrapper.fu-loading').removeClass('fu-hide');
          },
          success: function(response) {
            followup_admin_messages_generator(response, true);
          },
          complete: function() {
            $this.parent('#kerasno_smstoc_su_wrapper').siblings('.fu-element-wrapper.fu-loading').addClass('fu-hide');
          }
      });
  });


// 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_is_email(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

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

function followup_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;
}

function followup_notification(message) {
  jQuery.toast({
    text: message,
    showHideTransition: "fade",
    textAlign: "center",
    stack: false,
    position: "bottom-center",
    bgColor: "#444",
    textColor: "#fff",
    loaderBg: "#9EC600",
    class: "mreeir-error-toast",
    hideAfter: 3000,
    allowToastClose: false,
  });
}

function followup_admin_messages_generator($message, $success = false) {
  var cssClass = 'followup-error';
  if ($success == true) {
      cssClass = 'followup-success';
  }
  $('#followup_result_display').text($message);
  $('#followup_result_display').addClass(cssClass);
  $('#followup_result_display').fadeIn().delay(10000).fadeOut()
}

var followup_messeges = {
  MinActionRequired: "لطفاً حداقل یک عملیات را انتخاب کنید",
  OrderIDWrong: "شماره سفارش معتبر نیست",
  MobileWrong: "شماره موبایل معتبر نیست",
  TrackingcCodeWrong: "کد رهگیری معتبر نیست",
  SpamDetected: "فیلد تشخیص ربات معتبر نیست",
};

});