<%- include('../catalogCommerce/crudAssets.ejs') %>
<script src="/admin/app-assets/js/core/libraries/jquery.min.js"></script>
<script src="/admin/app-assets/vendors/js/forms/select/select2.full.min.js"></script>
<script src="/admin/app-assets/js/scripts/forms/select/form-select2.js"></script>


<script>
  $(document).ready(function () {
    $('.select2').select2({
      closeOnSelect: true
    });
  });

  const translations = {
    add: "<%= i18n.__('common.add') %>",
    edit: "<%= i18n.__('common.edit') %>",
  };

  function validateInput(input) {

    const i18n = {
      common: {
        emptyField: "<%= i18n.__('common.emptyField') %>",
        minLength: "<%= i18n.__('common.minLength', { minLength: '{{minLength}}' }) %>",
        valueMustGreaterThanZero: "<%= i18n.__('coupons.valueMustGreaterThanZero') %>",
        couponLength: "<%= i18n.__('coupons.couponLength') %>"
      }
    };


    try {

      console.log("input", input);

      const trimmedValue = input.value.trim();
      const minLength = 6;
      const feedback = input.closest('.controls').querySelector('.invalid-feedback');

      const messages = {
        empty: i18n.common.emptyField,
        minLength: i18n.common.minLength.replace('{{minLength}}', minLength),
        valueMustGreaterThanZero: i18n.common.valueMustGreaterThanZero,
        couponLength: i18n.common.couponLength
      };

      const emptyMessage = messages.emptyField;
      const minLengthMessage = messages.minLength.replace('{{minLength}}', minLength);
      const couponLengthMessage = messages.couponLength;
      const valueMustGreaterThanZero = messages.valueMustGreaterThanZero;
      let errorMessage = "";

      if (input.name === 'code' && trimmedValue.length < minLength) {
        errorMessage = couponLengthMessage;
        feedback.textContent = errorMessage;
        input.classList.add('is-invalid');
        input.style.border = '1px solid red';
        input.setCustomValidity(couponLengthMessage);
      } else if (['count', 'discount', 'maxDiscount'].includes(input.name)) {
        const defaultMessage = input.getAttribute("data-default-message");

        if (input.value.trim() === "") {
          feedback.textContent = defaultMessage;
          input.classList.add('is-invalid');
          input.style.border = '1px solid red';
          input.setCustomValidity(defaultMessage);
        } else if (parseFloat(input.value) <= 0) {
          errorMessage = valueMustGreaterThanZero;
          feedback.textContent = errorMessage;
          input.classList.add('is-invalid');
          input.style.border = '1px solid red';
          input.setCustomValidity(valueMustGreaterThanZero);
        } else {
          feedback.textContent = "";
          input.classList.remove('is-invalid');
          input.style.border = "";
          input.setCustomValidity("");
        }
      } else {
        feedback.textContent = "";
        input.classList.remove('is-invalid');
        input.style.border = "";
        input.setCustomValidity("");
      }

    } catch (error) {
      console.error("Validation error:", error);
    }

  }


  function shared(e, action, formElement) {
    e.preventDefault();

    const confirm = translations[action];

    const code = String($('input[name="code"]').val());

    const count = String($('input[name="count"]').val());

    const typeInput = document.querySelector('[name="type"]');
    const type = String(typeInput?.value || '');

    const discount = String($('input[name="discount"]').val());

    const maxDiscount = String($('input[name="maxDiscount"]').val());

    const expireDate = String($('input[name="expireDate"]').val());

    const requiresMaxDiscount = typeInput?.selectedOptions?.[0]
      ?.hasAttribute('data-requires-max-discount');
    let discountValidation = requiresMaxDiscount
      ? discount.trim().length && maxDiscount.trim().length
      : discount.trim().length;

    if (
      !code.trim().length ||
      !count.trim().length ||
      !type.trim().length ||
      !discountValidation ||
      !expireDate.trim().length
    ) {
      $(formElement).removeClass('was-validated');
    } else {
      $(formElement).addClass('was-validated');
    }

    const objData = new FormData(formElement);


    if (
      code.trim().length &&
      count.trim().length &&
      type.trim().length &&
      expireDate.trim().length && discountValidation
    ) {
      ajaxUpload($(formElement), {}, 'uploadWithOutImage', confirm);
    }
  }


  $(document).ready(function () {
    $(document).on('submit', '#addCoupon', function (e) {
      shared(e, 'add', this);
    });

    $(document).on('submit', '#editCoupon', function (e) {
      shared(e, 'edit', this);
    });
  });

  $(document).on("click", ".open-coupon", function (e) {
    $(".coupon_id").val($(this).data("id"));
    $(".code").val($(this).data("code"));
    $("#notify").modal("show");
  });

  $(document).on("click", ".change-coupon-status", function () {

    let status = $(this).data("status");
    console.log("status", status);

    Swal.fire({
      title: "<%= i18n.__('common.continueMessage') %>",
      text: "<%= i18n.__('coupons.changeCouponStatus') %>",
      type: "warning",
      showCancelButton: true,
      confirmButtonClass: "btn btn-primary",
      cancelButtonClass: "btn btn-danger ml-1",
      confirmButtonText: "<%= i18n.__('common.confirm') %>",
      cancelButtonText: "<%= i18n.__('common.cancel') %>",
      buttonsStyling: false,
    }).then((result) => {
      if (result.value) {
        $.ajax({
          type: "POST",
          url: "/dashboard/coupons/closeCoupon",
          data: {
            couponId: $(this).data("id"),
            status,
          },
          dataType: "json",
          success: (response) => {
            console.log("response", response);
            Swal.fire({
              position: "top-center",
              icon: "success",
              type: "success",
              title: response.message,
              showConfirmButton: false,
              timer: 1500,
              confirmButtonClass: "btn btn-primary",
              buttonsStyling: false,
            });
            window.location.reload();
          },
          error: (err) => {

            Swal.fire({
              position: "top-start",
              type: "error",
              title: `${err?.responseJSON?.message || err.responseJSON || err.message}`,
              showConfirmButton: false,
              timer: 1500,
              confirmButtonClass: "btn btn-primary",
              buttonsStyling: false,
            });
          },
        });
      }
    });
  });



  function createCode(number, item) {

    var result = "";
    var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    var charactersLength = characters.length;
    for (var i = 0; i < number; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    if (item == 0) {
      document.getElementsByName("code")[0].value = result;
    } else {
      document.getElementsByName("code")[1].value = result;
    }

    const input = document.querySelector('input[name="code"]');
    validateInput(input);

  }



</script>
