var base_url = document.location.origin + '/all-seasons-makhana/adminex';


$(document).on('click', '#addCategoryForm', function (e) {
  e.preventDefault();
  let categoryName = $('#categoryNameID').val().trim();

  if (categoryName === '') {
    $('#categoryNameID').css('border-color', '#ff031c');
    $('.catErrr').html('Category name is required').show().fadeOut(3000);
    return false;
  }

  // Fetch CSRF token from hidden input generated by form_open()
  let csrfInput = $('#addCategoryFrm').find('input[type="hidden"]');
  let csrfName = csrfInput.attr('name');
  let csrfHash = csrfInput.val();

  $.ajax({
    url: base_url + '/save-category',
    type: "POST",
    dataType: "json",
    data: {category_name: categoryName, [csrfName]: csrfHash},
    success: function (response) {
      
      // Update CSRF token if regenerate = TRUE
      if (response.csrfHash) {
        csrfInput.val(response.csrfHash);
      }

      if (response.status === 'success') {
        $('#addCategoryModal').modal('hide');
        $('#displayMsg').html('<div class="alert alert-primary">'+response.msg+'</div>');
        setTimeout(reloadPage, 800);
      } else if (response.status === 'validation_error') {
        $('.catErrr').html(response.msg).show().fadeOut(3000);
        return false;
      } else {
        $('#displayMsg').html('<div class="alert alert-danger">'+response.msg+'</div>');
        setTimeout(reloadPage, 800);
        return false;
      }
    },
    error: function () {
      alert('Something went wrong. Please try again.');
    }
  });
});


$(document).on('click', '.editCategoryBtn', function () {
  var categoryId   = $(this).data('id');
  var categoryName = $(this).data('name');
  $('#editCategoryId').val(categoryId);
  $('.editCategoryName').val(categoryName);
  $('#editCategory').modal('show');
});


$('#updateCatBtn').on('click', function (e) {
  e.preventDefault();

  let categoryId    = $('#editCategoryId').val();
  let categoryName  = $('#editCatNameID').val();
  let hdnCatName    = $('input[name="hdn_cat_name"]').val();

  if (categoryName === '') {
    $('#editCatNameID').css('border-color', '#ff031c');
    $('#editCatErrr').html('Category name is required').show().fadeOut(3000);
    return false;
  }

  // Fetch CSRF token from hidden input generated by form_open()
  let csrfInput = $('#addCategoryFrm').find('input[type="hidden"]');
  let csrfName = csrfInput.attr('name');
  let csrfHash = csrfInput.val();

  $.ajax({
    url: base_url + '/edit-category',
    type: 'POST',
    dataType: 'json',
    data: { category_id: categoryId, category_name: categoryName, hdn_cat_name: hdnCatName, [csrfName]: csrfHash},
    success: function (response) {
      console.log(response);
      
      // Update CSRF token if regenerate = TRUE
      if (response.csrfHash) {
        csrfInput.val(response.csrfHash);
      }

      if (response.status === 'success') {
        $('#editCategory').modal('hide');
        $('#displayMsg').html('<div class="alert alert-primary">'+response.msg+'</div>');
        setTimeout(reloadPage, 800);
      } else if (response.status === 'validation_error') {
        $('#editCatErrr').html(response.msg).show().fadeOut(3000);
        return false;
      } else {
        $('#displayMsg').html('<div class="alert alert-danger">'+response.msg+'</div>');
        setTimeout(reloadPage, 800);
        return false;
      }

    }
  });
});


function reloadPage() {
  location.reload();
}


function readURL(input) {
  $('#preViewId').css('display', 'block');
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#preViewId').attr('src', e.target.result).width(135).height(115);
    };
    reader.readAsDataURL(input.files[0]);
  }
}


$(document).ready(function () {
  $(".alert").delay(2000).fadeOut(2000);
});


$(document).ready(function () {
  $('.getDatePicker').datepicker({
    //changeMonth: true,
    //changeYear: true
    dateFormat: "dd-mm-yy"
  });
});


$(document).on('click', '#saveCouponBtnID', function (e) {
  e.preventDefault();
  let couponName      = $('#couponCodeID').val().trim();
  let expiryDate      = $('#expiryDateID').val().trim();
  let discountType    = $('#discountTypeID').val().trim();
  let discountValue   = $('#discountValueID').val().trim();    
  let minOrderAmount  = $('#minOrderAmountID').val().trim();

  if (couponName === '') {
    $('#couponCodeID').css('border-color', '#ff031c');
    $('.cpnErrr').html('Coupon code is required').show().fadeOut(3000);
    return false;
  }else if(expiryDate === ''){
    $('#expiryDateID').css('border-color', '#ff031c');
    $('.cpnExpErrr').html('Expiry date is required').show().fadeOut(3000);
    return false;
  }else{
    let csrfInput = $('#addCouponFrmID').find('input[type="hidden"]');
    let csrfName = csrfInput.attr('name');
    let csrfHash = csrfInput.val();

    $.ajax({
      url: base_url + '/save-coupons',
      type: "POST",
      dataType: "json",
      data: {coupon_code: couponName, expiry_date: expiryDate, discount_type: discountType, discount_value: discountValue, min_order_amount: minOrderAmount, [csrfName]: csrfHash},
      success: function (response) {
       
        if (response.csrfHash) {
          csrfInput.val(response.csrfHash);
        }

        if (response.status === 'success') {
          $('#addCouponsModal').modal('hide');
          $('#displayMsg').html('<div class="alert alert-primary">'+response.msg+'</div>');
          setTimeout(reloadPage, 800);
        } else if (response.status === 'validation_error') {
          $('.cpnErrr').html(response.msg).show().fadeOut(3000);
          return false;
        } else {
          $('#displayMsg').html('<div class="alert alert-danger">'+response.msg+'</div>');
          setTimeout(reloadPage, 800);
          return false;
        }
      },
      error: function () {
        alert('A duplicate entry was detected or an unexpected error occurred. Please try again.');
        location.reload();
      }
    });
  }
});