jQuery(document).ready(function($) {
var ksiteurl = kavehShopData.ksiteurl;
var highestPrice = kavehShopData.highestPrice;
var highestPrice = kavehShopData.highestPrice * 1;
var lowestPrice = kavehShopData.lowestPrice;
var lowestPrice = kavehShopData.lowestPrice * 1;
var ajaxnoinsingle = kavehShopData.ajaxnoinsingle;
var woocommerce_cart_redirect_after_add = kavehShopData.woocommerce_cart_redirect_after_add;
var cart_url = kavehShopData.cart_url;

// Category Price
const categoryPrice = document.getElementById("category-price");
if (categoryPrice) {
noUiSlider.create(categoryPrice, {
  start: [lowestPrice, highestPrice],
  margin: 1000,
  behaviour: "drag",
  connect: true,
  range: {
    min: lowestPrice,
    max: highestPrice,
  },
});
var limitFieldMin = document.getElementById("category-price-min");
var limitFieldMax = document.getElementById("category-price-max");

var updateCount = 0;
categoryPrice.noUiSlider.on("update", function (values, handle) {
  updateCount++;
  if (updateCount > 2) {
    (handle ? limitFieldMax : limitFieldMin).value = new Intl.NumberFormat("en").format(Number(values[handle])) + " تومان";
    setTimeout(function(){
      filterProducts();
    }, 2500);
  } else {
    // Skip the first update
    (handle ? limitFieldMax : limitFieldMin).value = new Intl.NumberFormat("en").format(Number(values[handle])) + " تومان";
  }
});
}
// Open Child Category Sidebar
const itemsSidebar = document.querySelectorAll(
  ".category-sidebar-box-items li.has-child span"
);
if (itemsSidebar.length > 0) {
  itemsSidebar.forEach((item) => {
    item.addEventListener("click", (ev) => {
      const el = ev.target,
        content = el.nextElementSibling,
        parent = el.parentElement;

      parent.classList.toggle("opened");

      if (parent.classList.contains("opened")) {
        content.style.height = content.scrollHeight + "px";

        setTimeout(() => {
          content.style.height = "auto";
        }, 300);
      } else {
        content.style.height = content.scrollHeight + "px";

        setTimeout(() => {
          content.style.height = 0;
        }, 10);
      }
    });
  });
}
// Sidebar Category
const btnOpenSidebarCategory = document.querySelector(".category-btn-filter"),
  sidebarCategory = document.querySelector(".category-sidebar"),
  backdropSidebarCategory = document.querySelector(
    ".category-sidebar-backdrop"
  );

if (btnOpenSidebarCategory) {
  btnOpenSidebarCategory.addEventListener("click", () => {
    sidebarCategory.classList.add("open");
  });

  backdropSidebarCategory.addEventListener("click", () => {
    sidebarCategory.classList.remove("open");
  });
}


jQuery('ul.attrhidden li input').on('click', function(e) {
  e.preventDefault();
  jQuery(this).toggleClass('activeFilter');
  // Find the closest ancestor ul.attrhidden
  var closestUlAttrHidden = jQuery(this).closest('ul.attrhidden');
  // Find the .attrhiddeninput within the closest ancestor
  var attrHiddenInput = closestUlAttrHidden.find('.attrhiddeninput');
  editFilterInputs(attrHiddenInput, jQuery(this).attr('myid'));
  filterProducts();
});


jQuery('ul.cathidden li input').on('click', function(e) {
  e.preventDefault();
  jQuery(this).toggleClass('activeFilter');
  editFilterInputs(jQuery('.filterhiddeninput'), jQuery(this).attr('myid'));
  filterProducts();
});


function editFilterInputs(inputField, value) {
  const currentFilters = inputField.val().split(',');
  const newFilter = value.toString();

if (currentFilters.includes(newFilter)) {
  const j = currentFilters.indexOf(newFilter);
  currentFilters.splice(j, 1);
  inputField.val(currentFilters);
  } else {
  inputField.val(inputField.val() + ',' + newFilter);
  }
}


var checkBoxexit = document.getElementById("onlysale");
  if (checkBoxexit){
    checkBoxexit.addEventListener('click', function(e){
      filterProducts()
    });
  }

var checkBoxexit1 = document.getElementById("exists-products");
if(checkBoxexit1){
  checkBoxexit1.addEventListener('click', function(e){
    filterProducts()
  });
}



jQuery(document).on('click', '.pg1 a.page-numbers', function(a) {
  a.preventDefault();
  var fired_a = jQuery(this).text();
  var ajaxurl = ksiteurl + "/kfilters/filter_kaveh/";
  var attrHiddenInputs = document.querySelectorAll('.attrhiddeninput');
  var count = attrHiddenInputs.length;
  var taxIds = []; 
  var attrId = []; 
  let catIds = []; 
  if(jQuery('.name-category').length){
    if (jQuery('.name-category').attr('catid').length > 1) {
      if (jQuery('.filterhiddeninput').val().split(',').length > 1) {
        catIds = jQuery('.filterhiddeninput').val().split(',');
      }
      else if(jQuery('.name-category').attr('catid').length > 1){
        catIds = jQuery('.name-category').attr('catid');
      }
    } 
    else {
      catIds = jQuery('.filterhiddeninput').val().split(',');
    }
  }
  else if(jQuery('.filterhiddeninput').length){
    catIds = jQuery('.filterhiddeninput').val().split(',');
  }
  
  const sortt = jQuery('.category-sort ul li input:checked').attr('id');
  for (let i = 0; i < count; i++) {
    taxIds.push(jQuery(attrHiddenInputs[i]).val().split(',')); 
    attrId.push(jQuery(attrHiddenInputs[i]).attr('taxid')); 
  }
  const serializedAttrId = JSON.stringify(attrId);
  const serializedTaxIds = JSON.stringify(taxIds);
  jQuery.ajax({
    url: ajaxurl,
    type: 'post',
    data: {
      onsalee: jQuery('#onlysale').is(':checked'),
      onstock: jQuery('#exists-products').is(':checked'),
      pricemin: jQuery('.noUi-handle.noUi-handle-lower').attr('aria-valuenow'),
      pricemax: jQuery('.noUi-handle.noUi-handle-lower').attr('aria-valuemax'),
      count: count,
      attrId: serializedAttrId, // Send serialized JSON string
      taxIds: serializedTaxIds, // Send serialized JSON string
      catIds: catIds,
      sortt: sortt,
      page: fired_a,
    },
    beforeSend: function (inum) {
      Notiflix.Block.pulse('body');
    },
    success: function (data) {
      jQuery('#woor').html(data);
      jQuery('.woocommerce-pagination.pg2').remove();
      Notiflix.Block.remove('body');
    },
  });
  return false;
});



function filterProducts() {
  var ajaxurl = ksiteurl + "/kfilters/filter_kaveh/";
  var attrHiddenInputs = document.querySelectorAll('.attrhiddeninput');
  var count = attrHiddenInputs.length;
  var taxIds = []; 
  var attrId = []; 
  let catIds = []; 
  if(jQuery('.name-category').length){
    if (jQuery('.name-category').attr('catid').length > 1) {
      if (jQuery('.filterhiddeninput').val().split(',').length > 1) {
        catIds = jQuery('.filterhiddeninput').val().split(',');
      }
      else if(jQuery('.name-category').attr('catid').length > 1){
        catIds = jQuery('.name-category').attr('catid');
      }
    } 
    else {
      catIds = jQuery('.filterhiddeninput').val().split(',');
    }
  }
  else if(jQuery('.filterhiddeninput').length){
    catIds = jQuery('.filterhiddeninput').val().split(',');
  }


  const sortt = jQuery('.category-sort ul li input:checked').attr('id');
  for (let i = 0; i < count; i++) {
    taxIds.push(jQuery(attrHiddenInputs[i]).val().split(',')); 
    attrId.push(jQuery(attrHiddenInputs[i]).attr('taxid')); 
  }
  const serializedAttrId = JSON.stringify(attrId);
  const serializedTaxIds = JSON.stringify(taxIds);
  jQuery.ajax({
    url: ajaxurl,
    type: 'post',
    data: {
      onsalee: jQuery('#onlysale').is(':checked'),
      onstock: jQuery('#exists-products').is(':checked'),
      pricemin: jQuery('.noUi-handle.noUi-handle-lower').attr('aria-valuenow'),
      pricemax: jQuery('.noUi-handle.noUi-handle-lower').attr('aria-valuemax'),
      count: count,
      attrId: serializedAttrId, // Send serialized JSON string
      taxIds: serializedTaxIds, // Send serialized JSON string
      catIds: catIds,
      sortt: sortt,
    },
    beforeSend: function (inum) {
      Notiflix.Block.pulse('body');
    },
    success: function (data) {
      jQuery('#woor').html(data);
      jQuery('.woocommerce-pagination.pg2').remove();
      Notiflix.Block.remove('body');

    },
  });
  return false;
}


jQuery('li > #sort-2').click(function() {
  filterProducts();
})
jQuery('li > #sort-3').click(function() {
  filterProducts();
})
jQuery('li > #sort-4').click(function() {
  filterProducts();
})
jQuery('li > #sort-1').click(function() {
  filterProducts();
})



jQuery(document).on('click', '.single_add_to_cart_button', function (e) {
  // Check if the button has the disabled attribute
  if (jQuery(this).is(':disabled')) {
    // If it has the disabled attribute, do nothing
    return;
  }
  if (jQuery(this).hasClass('disabled')) {
    // If it has the disabled class, do nothing
    return;
  }

  if (ajaxnoinsingle == '1') {
    // Check if the button is inside .insingle_pr
    if (jQuery(this).closest('.insingle_pr').length > 0) {
      // If it is, do nothing
      return;
    }
  }
  e.preventDefault();
  var jQuerythisbutton = jQuery(this),
    jQueryform = jQuerythisbutton.closest('form.cart'),
    id = jQuerythisbutton.attr('value'),
    product_qty = jQueryform.find('input[name=quantity]').val() || 1,
    product_id = jQueryform.find('input[name=product_id]').val() || id,
    variation_id = jQueryform.find('input[name=variation_id]').val() || 0;
  var data = {
    product_id: product_id,
    product_sku: '',
    quantity: product_qty,
    variation_id: variation_id,
  };
  jQuery(document.body).trigger('adding_to_cart', [jQuerythisbutton, data]);
  jQuery.ajax({
    type: 'post',
    url: ksiteurl + "/kaveh_ajaxx_add_to_cart/kaveh_ajaxx_add_to_cart",
    data: data,
    beforeSend: function () {
      Notiflix.Block.dots('body');
    },
    complete: function () {
      Notiflix.Block.remove('body');
    },
    success: function (response) {
      if (response.error && response.product_url) {
        window.location = response.product_url;
        return;
      } else {
        jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, jQuerythisbutton]);
        Notiflix.Notify.success('محصول با موفقیت به سبد خرید اضافه شد', {
          timeout: 3000,
          rtl: true,
          position: 'left-bottom',
          fontFamily: 'ybakh',
        });
        if(woocommerce_cart_redirect_after_add === 'yes'){
          window.location.href = cart_url;
        }
      }
    },
  });
  return false;
});
})