jQuery(document).ready(function ($) {
  var global_elements_hide;

  jQuery(document).ready(function($){
      $('#kerasno-register-telegram-webhook').on('click', function(e){
          e.preventDefault(); // جلوگیری از رفتار پیش‌فرض دکمه
          var status = $('#webhook-status');
          var btn = $(this);
          var originalText = btn.text();

          // غیرفعال کردن دکمه و تغییر متن
          btn.prop('disabled', true).text('لطفا منتظر بمانید');
          status.text('در حال ثبت وب‌هوک...');

          $.ajax({
              url: ajaxurl,
              type: 'POST',
              data: { action: 'kerasno_register_telegram_webhook' },
              success: function(response){
                  // دوباره فعال کردن دکمه و بازگرداندن متن اصلی
                  btn.prop('disabled', false).text(originalText);

                  if(response.success === true){
                      // پیام موفقیت
                      status.text(response.message); 
                      mreeir_notification("اتصال سایت شما به تلگرام به خوبی برقرار شد ✅", "success");
                  } else {
                      // پیام شکست
                      status.text(response.message); 
                      mreeir_notification("اتصال برقرار نشد ❌: " + response.message, "error");
                  }
              },
              error: function(){
                  // دوباره فعال کردن دکمه و بازگرداندن متن اصلی
                  btn.prop('disabled', false).text(originalText);

                  status.text('خطا در ثبت وب‌هوک');
                  mreeir_notification("اتصال برقرار نشد. اطلاعات نام کاربری و توکن را بررسی کنید ❌", "error");
              }
          });
      });
  });


  document.querySelectorAll('.has-sub').forEach(btn => {
    btn.addEventListener('click', () => {
      btn.nextElementSibling.style.display =
        btn.nextElementSibling.style.display === 'block' ? 'none' : 'block';
    });
  });

  document.querySelectorAll('.kepro-option').forEach(toggle => {
      toggle.addEventListener('change', function () {
          fetch(ajaxurl, {
              method: 'POST',
              headers: {'Content-Type': 'application/x-www-form-urlencoded'},
              body: new URLSearchParams({
                  action: 'kepro_save_systems_option',
                  option: this.dataset.option,
                  security: mreeir_admin_options.noncecheckkey,
                  value: this.checked ? '1' : '0'
              })
          })
          .then(res => res.json())
          .then(data => {
              if(data.success){
                  console.log('Saved:', data.data);
          mreeir_notification("ذخیره سازی با موفقیت انجام شد", "success");
              } else{
                  mreeir_notification("خطا در ذخیره سازی اطلاعات", "error");
              }
          });
      });
  });

  // ----------- inline test gateway - main
  $("#send_test_sms").on("click", function (e) {
    e.preventDefault();

    var testBTN = $(this);
    var panel_val = $("#acf-field_622c8a75870c9-field_622c6f771b87c")
      .find(":selected")
      .val();
    var username_val = $("#acf-field_622c8a75870c9-field_622c6fe69837e").val();
    var password_val = $("#acf-field_622c8a75870c9-field_622c70019837f").val();
    var sender_val = $("#acf-field_622c8a75870c9-field_622c701498380").val();
    var pattern_val = $("#acf-field_622c8a75870c9-field_622c702998381").val();
    var mobile_val = $("#acf-field_622c8a75870c9-field_6562ff7f9b612").val();

    if (!mreeir_is_mobile(mobile_val)) {
      $("#kerasno_test_message_main")
        .addClass("kerasno_red")
        .text("شماره موبایل باید 11 رقمی بوده و با 09 شروع شود")
        .show()
        .delay(4000)
        .fadeOut("slow");
      return;
    }

    jQuery.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "kerasno_check_main_gateway",
        panel: panel_val,
        username: username_val,
        password: password_val,
        sender: sender_val,
        pattern: pattern_val,
        mobile: mobile_val,
      },
      beforeSend: function () {
        testBTN.text("در حال ارسال ...");
      },
      success: function (response) {
        var first_response = response.data.message;
        if (response.success) {
          mreeir_notification(first_response, "success");
        } else {
          jQuery.ajax({
            // start inner ajax
            url: ajaxurl,
            type: "POST",
            data: {
              action: "kerasno_get_last_send_error",
            },
            beforeSend: function () {},
            success: function (response) {
              var second_reponse = response.data.message;
              if (response.success) {
                mreeir_notification(second_reponse);
              } else {
                mreeir_notification(first_response);
              }
            },
            complete: function () {},
          }); // end inner ajax
        }
      },
      complete: function () {
        testBTN.text("ارسال پیامک");
      },
    });
  });

  // ----------- inline test otp gateway
  $("#send_test_ussd").on("click", function (e) {
    e.preventDefault();

    var testBTN = $(this);
    var mobile_val = $("#acf-field_6690f4670033e-field_6690f46700340").val();

    if (!mreeir_is_mobile(mobile_val)) {
      mreeir_notification("شماره موبایل باید 11 رقمی بوده و با 09 شروع شود");
      return;
    }

    jQuery.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "kepro_ussd_set_otp_test",
        mobile: mobile_val,
      },
      beforeSend: function () {
        testBTN.text("در حال تست ...");
      },
      success: function (response) {
        var first_response = response.data.message;
        if (response.success) {
          mreeir_notification(first_response, "success");
        } else {
          mreeir_notification(response.data.message);
        }
      },
      complete: function () {
        testBTN.text("تست کد دستوری USSD");
      },
    });
  });

  // ----------- inline test voice gateway
  $("#send_test_voice").on("click", function (e) {
    e.preventDefault();

    var testBTN = $(this);
    var mobile_val = $("#acf-field_6690f47b00347-field_6690f47c00349").val();

    if (!mreeir_is_mobile(mobile_val)) {
      mreeir_notification("شماره موبایل باید 11 رقمی بوده و با 09 شروع شود");
      return;
    }

    jQuery.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "kepro_voice_set_otp_test",
        mobile: mobile_val,
      },
      beforeSend: function () {
        testBTN.text("در حال تست ...");
      },
      success: function (response) {
        var first_response = response.data.message;
        if (response.success) {
          mreeir_notification(first_response, "success");
        } else {
          mreeir_notification(response.data.message);
        }
      },
      complete: function () {
        testBTN.text("تست تماس تلفنی");
      },
    });
  });

  // ----------- inline test gateway - backup
  $("#send_test_sms_backup").on("click", function (e) {
    e.preventDefault();
    var testBTN = $(this);
    var panel_val = $("#acf-field_65630de0119b5-field_65630de0119b6")
      .find(":selected")
      .val();
    var username_val = $("#acf-field_65630de0119b5-field_65630de0119b9").val();
    var password_val = $("#acf-field_65630de0119b5-field_65630de0119ba").val();
    var sender_val = $("#acf-field_65630de0119b5-field_65630de0119bb").val();
    var pattern_val = $("#acf-field_65630de0119b5-field_65630de0119bc").val();
    var mobile_val = $("#acf-field_65630de0119b5-field_65630de0119b7").val();

    if (!mreeir_is_mobile(mobile_val)) {
      $("#kerasno_test_message_backup")
        .addClass("kerasno_red")
        .text("شماره موبایل باید 11 رقمی بوده و با 09 شروع شود")
        .show()
        .delay(4000)
        .fadeOut("slow");
      return;
    }

    jQuery.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "kerasno_check_main_gateway",
        panel: panel_val,
        username: username_val,
        password: password_val,
        sender: sender_val,
        pattern: pattern_val,
        mobile: mobile_val,
      },
      beforeSend: function () {
        testBTN.text("در حال ارسال ...");
      },
      success: function (response) {
        var first_response = response.data.message;
        if (response.success) {
          mreeir_notification(first_response, "success");
        } else {
          jQuery.ajax({
            // start inner ajax
            url: ajaxurl,
            type: "POST",
            data: {
              action: "kerasno_get_last_send_error",
            },
            beforeSend: function () {},
            success: function (response) {
              var second_reponse = response.data.message;
              if (response.success) {
                mreeir_notification(second_reponse);
              } else {
                mreeir_notification(first_response);
              }
            },
            complete: function () {},
          }); // end inner ajax
        }
      },
      complete: function () {
        testBTN.text("ارسال پیامک");
      },
    });
  });

  // ----------- form generator start

  $(".kerasno_inline_save").on("click", function () {
    var save_btn = $(this);
    var classes = $(this).attr("class").split(" ");
    var secondClass = classes[1];

    var user_id = $("#kerasno_extra_info #current_user_id").val();
    var current_value = $(this)
      .siblings(".kerasno_inline_current_value." + secondClass)
      .text();
    var item_value = $(this)
      .siblings(".kerasno_inline_input." + secondClass)
      .val();
    var item_title = $(this)
      .parent()
      .siblings(".kerasno_inline_title." + secondClass)
      .text();

    var $loading = $(
      "#kerasno_extra_info .mreeir-element-wrapper.mreeir-loading"
    );

    $.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "kerasno_proform_save_user_profile",
        itemkey: secondClass,
        itemvalue: item_value,
        currentvalue: current_value,
        itemtitle: item_title,
        userid: user_id,
      },
      beforeSend: function () {
        $loading.removeClass("mreeir-hide");
      },
      success: function (response) {
        if (response.success) {
          mreeir_notification(response.data.message, "success");
          $(".kerasno_inline_input").hide();
          $(".kerasno_inline_save").hide();
          $(".kerasno_inline_cancel").hide();

          save_btn.siblings(".kerasno_inline_current_value").text(item_value);
          save_btn.siblings(".kerasno_inline_current_value").show();
          save_btn.siblings(".kerasno_inline_edit").show();
        } else {
          mreeir_notification(response.data.message);
        }
      },
      complete: function () {
        $loading.addClass("mreeir-hide");
      },
    });
  });

  $(".kerasno_inline_edit").on("click", function () {
    $(".kerasno_inline_input").hide();
    $(".kerasno_inline_save").hide();
    $(".kerasno_inline_cancel").hide();
    $(".kerasno_inline_current_value").show();
    $(".kerasno_inline_edit").show();

    $(this).siblings(".kerasno_inline_input").show();
    $(this).siblings(".kerasno_inline_save").show();
    $(this).siblings(".kerasno_inline_cancel").show();
    $(this).siblings(".kerasno_inline_current_value").hide();
    $(this).hide();
    $(this).siblings(".kerasno_inline_input").focus();
  });

  $(".kerasno_inline_cancel").on("click", function () {
    $(".kerasno_inline_input").hide();
    $(".kerasno_inline_save").hide();
    $(".kerasno_inline_cancel").hide();

    $(this).siblings(".kerasno_inline_current_value").show();
    $(this).siblings(".kerasno_inline_edit").show();
  });

  $(document).on("click", '[data-name="add-layout"]', function () {
    var myArray = [
      "kfgr_mobile",
      "kfgr_name",
      "kfgr_fname",
      "kfgr_displayname",
      "kfgr_username",
      "kfgr_email",
      "kfgr_password",
      "kfgr_userrole",
      "kfgr_captcha",
    ];

    var layoutList = [];
    // پیدا کردن تمام المان‌های div با کلاس layout
    $("div.layout:visible").each(function () {
      var dataLayoutValue = $(this).attr("data-layout");
      layoutList.push(dataLayoutValue);
    });

    // آرایه جدید برای آیتم‌های مشابه
    var repeated_items = [];

    // مقایسه آیتم‌ها و ایجاد آرایه جدید
    for (var i = 0; i < layoutList.length; i++) {
      if (myArray.includes(layoutList[i])) {
        repeated_items.push(layoutList[i]);
      }
    }

    $(".acf-tooltip ul li a[data-layout]").each(function () {
      var dataLayout = $(this).attr("data-layout");

      if (repeated_items.includes(dataLayout)) {
        $(this).closest("li").css("background", "red");
        $(this).prop("disabled", true);

        $(this).css("text-decoration", "line-through");
        $(this).css("color", "white");
      }
    });
  });

  // ----------- form generator end

  $(".sms_arg").on("click", function () {
    $("textarea#acf-field_633005c5f3b7d").val(
      $("textarea#acf-field_633005c5f3b7d").val() +
        " %" +
        $(this).attr("id") +
        "% "
    );
  });

  //first time page loaded
  let selectedValue = $("select#acf-field_632f4766dc024").val();
  mreeir_control_args_visibility(selectedValue);

  $("select#acf-field_632f4766dc024").change(function () {
    mreeir_control_args_visibility($(this).val());
  });

  function mreeir_control_args_visibility($selected_id) {
    // 0  - mobile
    // 1  - display_name
    // 3  - username
    // 4  - date
    // 5  - time
    // 6  - post_title
    // 7  - author_name
    // 8  - comment_link
    // 9  - comment_text
    // 10 - random_password
    // 11 - user_role

    switch ($selected_id) {
      case "user-welcome":
        {
          mreeir_show_hide_args_by_number(["0", "1", "3", "4", "5"]);
          global_elements_hide = [
            "mobile",
            "display_name",
            "username",
            "date",
            "time",
          ];
        }
        break;
      case "user-userpass":
        {
          mreeir_show_hide_args_by_number(["0", "3", "4", "5", "10"]);
          global_elements_hide = [
            "mobile",
            "username",
            "date",
            "time",
            "random_password",
          ];
        }
        break;
      case "admin-register-alarm":
        {
          mreeir_show_hide_args_by_number(["0", "1", "3", "4", "5"]);
          global_elements_hide = [
            "mobile",
            "display_name",
            "username",
            "date",
            "time",
          ];
        }
        break;
      case "admin-register-warning":
        {
          mreeir_show_hide_args_by_number(["0", "1", "3", "4", "5", "11"]);
          global_elements_hide = [
            "mobile",
            "display_name",
            "username",
            "date",
            "time",
            "user_role",
          ];
        }
        break;
      case "admin-login-warning":
        {
          mreeir_show_hide_args_by_number(["0", "1", "3", "4", "5", "11"]);
          global_elements_hide = [
            "mobile",
            "display_name",
            "username",
            "date",
            "time",
            "user_role",
          ];
        }
        break;

      case "user-submitcomment":
      case "user-approvecomment":
      case "user-newreply":
      case "admin-newcomment":
        {
          mreeir_show_hide_args_by_number([
            "0",
            "1",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "11",
          ]);
          global_elements_hide = [
            "mobile",
            "display_name",
            "username",
            "date",
            "time",
            "user_role",
            "post_title",
            "author_name",
            "comment_link",
            "comment_text",
          ];
        }
        break;
    }
  }

  $(document).on(
    "click",
    ".acf-field-6330600564090 .acf-actions > a",
    function (e) {
      e.preventDefault();

      $(".acf-tooltip ul li a").hide();
      let argsLen = global_elements_hide.length;
      for (let i = 0; i < argsLen; i++) {
        $(".acf-tooltip ul li a")
          .filter('[data-layout="' + global_elements_hide[i] + '"]')
          .show();
      }
    }
  );

  function mreeir_show_hide_args_by_number(param) {
    $(".sms_arg").hide();
    let argsLen = param.length;

    for (let i = 0; i < argsLen; i++) {
      $(".sms_arg")
        .filter('[data-argument-id="' + param[i] + '"]')
        .show();
    }
  }

  $("#exportmobilebasedwoo").click(function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");
    // Make an AJAX request to generate the CSV
    $.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "kerasno_generate_csv_woo",
      },
      beforeSend: function () {
        $loading.removeClass("mreeir-hide");
      },
      success: function (data) {
        var today = new Date();
        var date =
          today.getFullYear() +
          "-" +
          (today.getMonth() + 1) +
          "-" +
          today.getDate();

        // Create a temporary anchor element and trigger the download
        var link = document.createElement("a");
        link.href = window.URL.createObjectURL(new Blob([data]));
        link.download = "kerasno-mobiles-woo-" + date + ".csv";
        link.click();
      },
      complete: function () {
        $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
      },
    });
  });

  $("#exportmobilebasedwp").click(function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");
    // Make an AJAX request to generate the CSV
    $.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "kerasno_generate_csv_wp",
      },
      beforeSend: function () {
        $loading.removeClass("mreeir-hide");
      },
      success: function (data) {
        var today = new Date();
        var date =
          today.getFullYear() +
          "-" +
          (today.getMonth() + 1) +
          "-" +
          today.getDate();
        // Create a temporary anchor element and trigger the download
        var link = document.createElement("a");
        link.href = window.URL.createObjectURL(new Blob([data]));
        link.download = "kerasno-mobiles-wp-" + date + ".csv";
        link.click();
      },
      complete: function () {
        $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
      },
    });
  });

  $("#createemailforusers").click(function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");
    // AJAX request
    $.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "kerasno_create_email_for_users",
      },
      beforeSend: function () {
        $loading.removeClass("mreeir-hide");
      },
      success: function (response) {
        if (response != "0") {
          mreeir_notification(
            response + " " + mreeir_messeges.createdEmailSuccess,
            "success"
          );
        }
        if (response == "0") {
          mreeir_notification(mreeir_messeges.createdEmailFailed);
        }
      },
      complete: function () {
        $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
      },
      error: function (xhr, ajaxOptions, thrownError) {
        mreeir_notification(mreeir_messeges.createdEmailError);
      },
    });
  });

  var kerasno_detail_update = $(
    'tr[data-slug="kerasno-pro"] td.column-description.desc .plugin-version-author-uri a.open-plugin-details-modal'
  );
  if (kerasno_detail_update.length > 0) {
    kerasno_detail_update.removeClass("thickbox");
    kerasno_detail_update.attr(
      "href",
      "https://docs.kerasno.com/kerasno-changelog/"
    );
    kerasno_detail_update.attr("target", "_blank");
  }

  function mreeir_admin_messages_generator($message, $success = false) {
    var cssClass = "kerasno-error";
    if ($success == true) {
      cssClass = "kerasno-success";
    }
    $("#kerasno_result_display").text($message);
    $("#kerasno_result_display").addClass(cssClass);
    $("#kerasno_result_display").fadeIn().delay(3000).fadeOut();
  }

  $("#kerasno_smstoc_submit").on("click", function (e) {
    e.preventDefault();

    var mobile = $("#kerasno_smstoc_mobile").val();
    var message_body = $("#kerasno_smstoc_ta").val();
    var order_id = $("#kerasno_smstoc_orderid").val();
    if (mreeir_is_empty(mobile) || !mreeir_is_mobile(mobile)) {
      mreeir_admin_messages_generator(mreeir_messeges.smstocustomer_nomobile);
      return;
    }
    if (mreeir_is_empty(message_body)) {
      mreeir_admin_messages_generator(
        mreeir_messeges.smstocustomer_fill_message
      );
      return;
    }

    jQuery.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "mreeir_send_sms_from_order_edit",
        orderid: order_id,
        to: mobile,
        message: message_body,
        security: mreeir_admin_options.sendsmstocustomer,
      },
      beforeSend: function () {
        $("#kerasno-admin-loading").show();
      },
      success: function (response) {
        if (response == "success") {
          $("#kerasno_smstoc_ta").val("");
          mreeir_admin_messages_generator(
            mreeir_messeges.smstocustomer_success,
            true
          );
        }
        if (response == "failed") {
          mreeir_admin_messages_generator(mreeir_messeges.smstocustomer_failed);
        }
        if (response == "wrong-info") {
          mreeir_admin_messages_generator(mreeir_messeges.smstocustomer_error);
        }
      },
      complete: function () {
        $("#kerasno-admin-loading").hide();
      },
    });
  });

  $("#pusers-export").on("click", function (e) {
    e.preventDefault();

    var fromDate = $("#userprdstartdate").val();
    var toDate = $("#userprdenddate").val();
    var status = $("#acf-field_629713b5a2447").val();
    status = status.join();

    var productSource = $("#acf-field_629710a15259b").val();
    var include_exclude = "";
    var products_list = "";

    if (productSource == "include") {
      include_exclude = "include";
      products_list = $("#acf-field_629711e75259d").val();
      products_list = products_list.join();
    } else if (productSource == "exclude") {
      include_exclude = "exclude";
      products_list = $("#acf-field_629711a85259c").val();
      products_list = products_list.join();
    } else {
      include_exclude = "all";
    }

    if (productSource != "all" && mreeir_is_empty(products_list)) {
      mreeir_notification(mreeir_messeges.pleaseSelectProduct);
      return;
    }
    if (mreeir_is_empty(status)) {
      mreeir_notification(mreeir_messeges.pleaseSelectStatus);
      return;
    }

    // return;
    jQuery.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "mreeir_generate_product_customers_list",
        security: mreeir_admin_options.generatepusers,
        startdate: fromDate,
        enddate: toDate,
        orderStatus: status,
        inex: include_exclude,
        products: products_list,
      },
      beforeSend: function () {
        jQuery.AjaxDownloader({
          url: mreeir_admin_options.ajaxurl,
          data: {
            action: "mreeir_generate_product_customers_list",
            security: mreeir_admin_options.generatepusers,
            startdate: fromDate,
            enddate: toDate,
            orderStatus: status,
            inex: include_exclude,
            products: products_list,
          },
        });
        $("#userprd-loading").show();
      },
      success: function (response) {
        if (response == "nothing") {
          mreeir_notification(mreeir_messeges.nothing);
        }
        $("#userprd-loading").hide();
      },
      complete: function () {
        $("#userprd-loading").hide();
      },
    });
  });

  $.AjaxDownloader = function (options) {
    // Settings
    var settings = $.extend(
      true,
      {},
      {
        data: $.ajaxSetup()["data"] || {},
        url: $.ajaxSetup()["url"],
      },
      options
    );

    // Create Form
    var form = $("<form>", {
      action: settings.url,
      method: "POST",
      target: "AjaxDownloaderIFrame",
    }).appendTo("body");

    // Append Data
    $.each(settings.data, function (key, val) {
      $("<input>", {
        type: "hidden",
        name: key,
        value: typeof val == "object" ? JSON.stringify(val) : val,
      }).appendTo(form);
    });

    // Submit Form
    form.submit();
    form.remove();
  };

  // Create AjaxDownloaderIFrame
  $(document).ready(function () {
    $("<iframe>", {
      name: "AjaxDownloaderIFrame",
    })
      .hide()
      .appendTo("body");
  });

  // delete logs from list table
  $('body[class*="kerasno-statistics"] .actions.bulkactions #doaction').on(
    "click",
    function () {
      let self = $(this);

      let selected = $("#bulk-action-selector-top").val();

      if ("trash" != selected) return;

      let postIDs = [];
      $.each($(".selected-logs"), function (index, elem) {
        if ($(elem).prop("checked")) {
          let postID = $(elem)
            .parents("tr")
            .find(".sender_panel .logid")
            .attr("data-logid");

          postIDs.push(postID);
        }
      });

      let ajaxurl = mreeir_admin_options.ajaxurl;
      let data = {
        action: "mreeir_delete_multiple_logs",
        post_ids: postIDs,
      };

      $("#kerasno-admin-loading").show();
      jQuery.post(ajaxurl, data, function (response) {
        if (response == "0") {
          var bulk_error_message = "هیچ رکوردی حذف نشد";
          mreeir_notification(bulk_error_message);
        }
        if (response != "0") {
          var bulk_success_message =
            "تعداد " + response + " رکورد با موفقیت حدف شد";
          mreeir_notification(bulk_success_message, "success");
        }
        $("#kerasno-admin-loading").hide();
        setTimeout(function () {
          location.reload(true);
        }, 3000);
      });
    }
  );

  // delete downloader from list table
  $("body.admin_page_downloaders .actions.bulkactions #doaction").on(
    "click",
    function () {
      let self = $(this);

      let selected = $("#bulk-action-selector-top").val();

      if ("trash" != selected) return;

      let postIDs = [];
      $.each($(".selected-dlrs"), function (index, elem) {
        if ($(elem).prop("checked")) {
          let postID = $(elem)
            .parents("tr")
            .find(".mobile .downloadersID")
            .attr("data-dlrid");

          postIDs.push(postID);
        }
      });

      let ajaxurl = mreeir_admin_options.ajaxurl;
      let data = {
        action: "mreeir_delete_multiple_downloaders",
        post_ids: postIDs,
      };

      $("#kerasno-admin-loading").show();
      jQuery.post(ajaxurl, data, function (response) {
        if (response == "0") {
          var bulk_error_message = "هیچ رکوردی حذف نشد";
          mreeir_notification(bulk_error_message);
        }
        if (response != "0") {
          var bulk_success_message =
            "تعداد " + response + " رکورد با موفقیت حدف شد";
          mreeir_notification(bulk_success_message, "success");
        }
        $("#kerasno-admin-loading").hide();
        setTimeout(function () {
          location.reload(true);
        }, 3000);
      });
    }
  );

  if (
    $(".acf-field .userprd-wrapper.dates-wrapper").length > 0 ||
    $("div#mreeir-export-downloads-inner form#dl-report-form").length > 0
  ) {
    jalaliDatepicker.startWatch({
      maxDate: "today",
      zIndex: "999999999",
      autoReadOnlyInput: "true",
    });
  }

  // downloads start -----------------------------------------------
  $(".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();
  }
  // downloads end -----------------------------------------------

  // -------- Recreate Default Pages
  $("#recreate-pages").on("click", function (e) {
    e.preventDefault();
    var areyousure = confirm(
      "آیا مطمئن هستید که می خواهید برگه های پیشفرض افزونه را مجدداً ایجاد کنید؟"
    );
    var $loading = $(this)
      .parent()
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");
    if (areyousure) {
      jQuery.ajax({
        url: mreeir_admin_options.ajaxurl,
        type: "POST",
        data: {
          action: "mreeir_recreate_default_pages_ajax",
          security: mreeir_admin_options.recreatepages,
        },
        beforeSend: function () {
          $loading.removeClass("mreeir-hide");
        },
        success: function (response) {
          if (response == "success") {
            mreeir_notification(
              mreeir_messeges.pagesCreatedSuccessfully,
              "success"
            );
          }
          if (response == "failed") {
            mreeir_notification(mreeir_messeges.pagesCreatedError);
          }
        },
        complete: function () {
          $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
        },
      });
    }
  });

  // -------- License Page - Chekc Key
  $("#verifykey").on("click", function (e) {
    e.preventDefault();
    var $key = $("#key").val();
    var $product = $("#product").val();
    var licenseData = {
      action: "check_license_key",
      security: mreeir_admin_options.noncecheckkey,
      key: $key,
    };

    $.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      dataType: "json",
      // async: false,
      data: licenseData,
      beforeSend: function () {},
      success: function (response) {
        var res = $.parseJSON(response);
        if (res.result == "valid") {
          // alert( ' OK ');
        } else if (res.result == "notvalid") {
          // alert( ' NO ');
        } else {
          // alert(res.message);
        }
      },
      complete: function () {},
    });
  });

  // -------- Tools Page - Test Panel Send SMS
  $("#mobile").keypress(function (e) {
    var key = e.which;
    if (key == 13) {
      // the enter key code
      $("#verifypanel").click();
      return false;
    }
  });

  $("#verifypanel").on("click", function (e) {
    e.preventDefault();
    var $mobile = $("#mobile").val();
    var $panel = $("#panel").val();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");
    $mobile = mreeir_correct_mobile_number($mobile);

    if (mreeir_is_empty($mobile) || !mreeir_is_mobile($mobile)) {
      mreeir_notification(mreeir_messeges.mobileNotValid);
      return;
    }

    jQuery.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "mreeir_send_sms_panel_test",
        mobile: $mobile,
        panel: $panel,
        security: mreeir_admin_options.noncesendtestsms,
      },
      beforeSend: function () {
        $loading.removeClass("mreeir-hide");
      },
      success: function (response) {
        if (response == "success") {
          mreeir_notification(mreeir_messeges.testSMSSent, "success");
        } 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);
              } else {
                if (response == "wrong-info") {
                  mreeir_notification(mreeir_messeges.mobileNotValid);
                }
                if (response == "send-failed") {
                  mreeir_notification(mreeir_messeges.testSMSSentFailed);
                }
              }
            },
            complete: function () {},
          }); // end inner ajax
        }
      },
      complete: function () {
        $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
      },
    });
  });

  // -------- Tools Page - Migrate From Digits
  $("#migratefromdigits").on("click", function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");

    jQuery.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "mreeir_migrate_from_digits",
        security: mreeir_admin_options.noncefromdigits,
      },
      beforeSend: function () {
        $loading.removeClass("mreeir-hide");
      },
      success: function (response) {
        if (response != "0") {
          mreeir_notification(
            response + mreeir_messeges.migrateSuccess,
            "success"
          );
          change_current_value(".ktools-value.digits-value", response, true);
        }
        if (response == "0") {
          mreeir_notification(mreeir_messeges.migrateFailed);
        }
      },
      complete: function () {
        $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
      },
    });
  });

  // -------- Tools Page - Migrate From WooCommerce Billing Phoen
  $("#migratefromwoobilling").on("click", function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");

    jQuery.ajax({
      url: mreeir_admin_options.ajaxurl,
      type: "POST",
      data: {
        action: "mreeir_migrate_from_woo_billing",
        security: mreeir_admin_options.noncefromwoobilling,
      },
      beforeSend: function () {
        $loading.removeClass("mreeir-hide");
      },
      success: function (response) {
        if (response != "0") {
          mreeir_notification(
            response + mreeir_messeges.migrateSuccess,
            "success"
          );
          change_current_value(".ktools-value.billing-value", response, true);
        }
        if (response == "0") {
          mreeir_notification(mreeir_messeges.migrateFailed);
        }
      },
      complete: function () {
        $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
      },
    });
  });

  // -------- Tools Page - Copy Fields
  $("#fieldscopy").on("click", function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");
    var from_field = $(this).siblings("#copy_field_from").val();
    var to_field = $(this).siblings("#copy_field_to").val();

    if (mreeir_is_empty(from_field) || mreeir_is_empty(to_field)) {
      mreeir_notification("فیلدهای مبدا و مقصد الزامی هستند");
      return;
    }

    if (confirm("این عملیات برگشت ناپذیر است. آیا مطمئن هستید؟")) {
      jQuery.ajax({
        url: mreeir_admin_options.ajaxurl,
        type: "POST",
        data: {
          action: "mreeir_copy_fields",
          from: from_field,
          to: to_field,
          security: mreeir_admin_options.copyfieldsnonce,
        },
        beforeSend: function () {
          $loading.removeClass("mreeir-hide");
        },
        success: function (response) {
          if (response != "0") {
            mreeir_notification(
              response + mreeir_messeges.copySuccess,
              "success"
            );
          }
          if (response == "0") {
            mreeir_notification(mreeir_messeges.copyFailed);
          }
        },
        complete: function () {
          $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
        },
      });
    }
  });

  // -------- Tools Page - Change Userames
  $("#changeusername").on("click", function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");
    if (confirm("این عملیات برگشت ناپذیر است. آیا مطمئن هستید؟")) {
      jQuery.ajax({
        url: mreeir_admin_options.ajaxurl,
        type: "POST",
        data: {
          action: "mreeir_change_usernames_in_db",
          security: mreeir_admin_options.noncechangeusernames,
        },
        beforeSend: function () {
          $loading.removeClass("mreeir-hide");
        },
        success: function (response) {
          if (response != "0") {
            mreeir_notification(
              response + mreeir_messeges.changeUsernamesSuccess,
              "success"
            );
          }
          if (response == "0") {
            mreeir_notification(mreeir_messeges.changeUsernamesFailed);
          }
        },
        complete: function () {
          $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
        },
      });
    }
  });

  // -------- Tools Page - Delete All Logs
  $("#deletealllogs").on("click", function (e) {
    e.preventDefault();
    var $loading = $(this)
      .parent()
      .parent()
      .siblings(".mreeir-element-wrapper.mreeir-loading");

    if (confirm("این عملیات برگشت ناپذیر است. آیا مطمئن هستید؟")) {
      jQuery.ajax({
        url: mreeir_admin_options.ajaxurl,
        type: "POST",
        data: {
          action: "mreeir_delete_all_logs",
          security: mreeir_admin_options.noncedeletealllogs,
        },
        beforeSend: function () {
          $loading.removeClass("mreeir-hide");
        },
        success: function (response) {
          if (response == "success") {
            mreeir_notification(
              mreeir_messeges.deletealllogssuccess,
              "success"
            );
          }
          if (response == "failed") {
            mreeir_notification(mreeir_messeges.deletealllogsfailed);
          }
        },
        complete: function () {
          $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
        },
      });
    }
  });

  var mreeir_notification = function (message, success = "") {
    var $_bg_color = "red";
    if (success == "success") {
      var $_bg_color = "green";
    }

    $.toast({
      text: message,
      showHideTransition: "slide",
      textAlign: "center",
      stack: false,
      position: "bottom-center",
      bgColor: $_bg_color,
      textColor: "#fff", //'#721c24',
      loaderBg: "#333",
      class: "mreeir-error-toast",
      hideAfter: 8000,
      allowToastClose: true,
    });
    $(".mreeir-element-wrapper.mreeir-loading").addClass("mreeir-hide");
  };

  var mreeir_is_mobile = function (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;
  }

  // check empty function
  var mreeir_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;
    }
  };

  // Copy Shortcodes To Clipboard
  $(".shcs-item-copy").on("click", function () {
    var sc_to_copy = $(this).siblings(".shcs-item-code").html();
    var $this = $(this);
    mreeir_copy_shortcode_to_clipboard(sc_to_copy);
    $(this).children(".shcs-copy").hide();
    $(this).children(".shcs-copy-done").show();
    setTimeout(function () {
      $this.children(".shcs-copy-done").hide();
      $this.children(".shcs-copy").show();
    }, 2000);
  });

  // Copy Shortcodes To Clipboard
  $(".kepro-shcs-item-copy").on("click", function () {
    var sc_to_copy = $(this).siblings(".kepro-shcs-item-code").html();
    var $this = $(this);
    mreeir_copy_shortcode_to_clipboard(sc_to_copy);
    $(this).children(".kepro-shcs-copy").hide();
    $(this).children(".kepro-shcs-copy-done").show();
    setTimeout(function () {
      $this.children(".kepro-shcs-copy-done").hide();
      $this.children(".kepro-shcs-copy").show();
    }, 2000);
  });

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

  // Copy Shortcodes To Clipboard - CallBack
  function mreeir_copy_shortcode_to_clipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(element).select();
    document.execCommand("copy");
    $temp.remove();
  }

  var mreeir_messeges = {
    mobileNotValid: "شماره موبایل وارد شده معتبر نیست",
    testSMSSent:
      "پیامک تست ارسال شد. جهت اطمینان از دریافت پیامک، موبایل خود را بررسی کنید",
    migrateSuccess: " شماره با موفقیت به کراسنو منتقل شد",
    createdEmailSuccess: "ایمیل با موفقیت ایجاد شد",
    createdEmailFailed: "هیچ ایمیلی ایجاد نشد",
    createdEmailError: "عملیات ایجاد ایمیل با خطا مواجه شد",
    copySuccess: " فیلد با موفقیت منتقل شد",
    migrateFailed: "هیچ شماره ای منتقل نشد",
    copyFailed: "هیچ فیلدی تکثیر نشد",
    changeUsernamesSuccess: " نام کاربری با موفقیت تغییر داده شدند",
    changeUsernamesFailed: "هیچ نام کاربری تغییر داده نشد",
    testSMSSentFailed: "خطا در ارسال پیامک تست. تنظیمات درگاه را بررسی کنید",
    pagesCreatedSuccessfully: "برگه های پیشفرض با موفقیت ایجاد شدند",
    pagesCreatedError: "خطایی در هنگام ایجاد برگه های پیشفرض رخ داده است",
    pleaseSelectProduct: "لطفاً یک یا چند محصول را انتخاب کنید",
    pleaseSelectStatus: "لطفاً یک یا چند وضعیت سفارش را انتخاب کنید",
    nothing: "موردی برای خروجی گرفتن وجود ندارد",

    smstocustomer_nomobile: "شماره موبایل خریدار این سفارش وجود ندارد",
    smstocustomer_fill_message: "متن پیامک را وارد کنید",
    smstocustomer_success: "پیامک ارسال شد",
    smstocustomer_failed: "ارسال پیامک انجام نشد",
    smstocustomer_error: "اطلاعات پیامک نامعتبر است",

    deletealllogssuccess: "تمام گزارش های ارسال پیامک با موفقیت حذف شدند",
    deletealllogsfailed: "عملیات حذف با خطا مواجه شد",

    groupnameempty: "نام گروه خالی است",
    groupadded: "گروه با موفقیت اضافه شد",
    groupedited: "گروه با موفقیت ویرایش شد",
    grouperror: "اطلاعات معتبر نیست یا گروه تکراری است",
    grouprepeated: "نام گروه تکراری است",
    grouprepeatededit: "نام گروه تغییری نداشته است",

    mobilerequired: "ورود شماره موبایل الزامی است",
    useradded: "مشترک با موفقیت اضافه شد",
    useredited: "مشترک با موفقیت ویرایش شد",
    usererror: "اطلاعات معتبر نیست یا مشترک تکراری است",
    userrepeated: "اطلاعات تکراری است",
    userrepeatededit: "اطلاعات تغییری نداشته است",
  };
});
