jQuery(document).ready(function($) {
  var timer;
  jQuery('.fetchinpu').on('input', function() {
      var searchTerm = jQuery(this).val();
      clearTimeout(timer);
      // Wait for 500 milliseconds after user stops typing
      timer = setTimeout(function() {
          if (searchTerm.length >= 2) {
              performSearch(searchTerm);
          } else {
              Notiflix.Block.dots('.seabox');
          }
      }, 500);
  });

  function performSearch(searchQuery) {
      jQuery.ajax({
          url: ksiteurl + '/wp-json/wp/v2/product?_embed&search=' + searchQuery,
          type: 'GET',
          beforeSend: function() {
              Notiflix.Block.dots('.seabox');
          },
          success: function(data) {
              if (data.length === 0) {
                  jQuery('.datafetch3').hide();
                  jQuery('.row.srows').hide();
                  Notiflix.Notify.failure('هیچ چیزی یافت نشد', {
                    timeout: 3000,
                    rtl: true,
                    position: 'center-center',
                    fontFamily: 'ybakh',
                    zindex: 99999999,
                  });
                  Notiflix.Block.remove('.seabox');
              } else {
                jQuery('.row.srows').show();
                var resultsHtml = '';
                var count = 0;
                jQuery.each(data, function(index, item) {
                  if (count < 8) {
                    var title = item.title.rendered;
                    var category = '';
                    if (item._embedded['wp:term'] && item._embedded['wp:term'][0] && item._embedded['wp:term'][0][0]) {
                        category = item._embedded['wp:term'][0][0].name;
                    }
                    resultsHtml += `
                    <div class="swiper-slide">
                          <a href="${item.link}">
                              <div class="prseabox rounded-4 p-2">
                                  <div class="row align-items-center justify-content-center">
                                      <div class="col-4">
                                          <img class="p-2 d-inline boxim rounded-3" src="${item.kaveh_custom.thumbnail_url}" alt="${item.title.rendered}">
                                      </div>
                                      <div class="col">
                                          <p class="d-inline mx-2">${title.substring(0, 22)}...</p>
                                          <span class="rizs ms-2">در دسته ${category}</span>
                                      </div>
                                  </div>
                              </div>
                          </a>
                      </div>
                    `;
                    count++;
                  }
                });
                jQuery('.datafetch3').show();
                jQuery('.datafetch3').html(resultsHtml);
                  var resultsHtml2 = '';
                  var count = 0;
                  jQuery.each(data, function(index, item) {
                    if (count < 3) {
                      var title = item.title.rendered;
                      resultsHtml2 += `
                          <a href="${item.link}">
                              <div class="lisea mt-2 py-2 pe-2 ps-2">
                                  <div class=" d-inline seer mx-2">
                                      <i class="far fa-circle"></i>
                                  </div>
                                  <span class="f-sea">${title.substring(0, 30)}...</span>
                                  <i class="isax isax-arrow-left-1"></i>
                              </div>
                          </a>
                      `;
                      count++;
                    } 
                  });
                  resultsHtml2 += `
                      <a href="/shop?s=${searchQuery}" class="d-block wrbut"> مشاهده همه
                          <i class="isax isax-arrow-left5"></i>
                      </a>
                  `;
                  jQuery('.datafetch').html(resultsHtml2);
                  var resultsHtml3 = '';
                  var count = 0;
                  var addedCategories = []; // Array to keep track of added categories
                  
                  jQuery.each(data, function(index, item) {
                      if (count < 3) {
                          var category = '';
                          var categorylink = '';
                          if (item._embedded['wp:term'] && item._embedded['wp:term'][0] && item._embedded['wp:term'][0][0]) {
                              category = item._embedded['wp:term'][0][0].name;
                              var categorylink = item._embedded['wp:term'][0][0].link;
                          }
                  
                          // Check if category has already been added
                          if (addedCategories.indexOf(category) === -1) {
                              resultsHtml3 += `
                              <a href="${categorylink}">
                                  <div class="lisea mt-2 py-2 pe-2 ps-2">
                                      <div class=" d-inline seer mx-2">
                                          <i class="far fa-circle"></i>
                                      </div>
                                      <span class="f-sea">${category}</span>
                                      <span class="rizs ms-2"> مشاهده کنید</span>
                                      <i class="isax isax-arrow-left-1"></i>
                                  </div>
                              </a>
                              `;
                              addedCategories.push(category); // Add category to the addedCategories array
                              count++;
                          }
                      }
                  });
                  jQuery('.datafetch2').html(resultsHtml3);
                  Notiflix.Block.remove('.seabox');
              }
          },
          error: function(xhr, status, error) {
              // console.error(xhr.responseText);
          }
      });
  }
});


jQuery(document).ready(function($) {
  jQuery(document).on('click', '.nav-header-cart-dropdown-two .changeinp', function() {
  var quantityInput = jQuery(this).siblings('.quantity').find('input[type=number]');
  var newQuantity = parseInt(quantityInput.val());
  var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
  // Send AJAX request to update the cart
  jQuery.ajax({
    url: ksiteurl + "/kaveh_ajax_update_cart_kk/kaveh_ajax_update_cart_kk", 
    type: 'POST',
    data: {
      cart_item_key: cartItemKey,
      quantity: newQuantity
    },
    beforeSend: function () {
        jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
    },
    success: function(response) {
      // Update the cart UI with the updated fragments
      if (response && response.fragments) {
        jQuery.each(response.fragments, function(key, value) {
          jQuery(key).replaceWith(value);
        });
      }
    },
    error: function(xhr, status, error) {
      // Handle any error that occurred during the AJAX request
    }
  });
});
});


jQuery(document).ready(function($) {
  jQuery(document).on('click', '.nav-header-cart-dropdown-two .delete', function(e) {
	e.preventDefault();
  var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
  // Send AJAX request to update the cart
  jQuery.ajax({
    url: ksiteurl + "/kaveh_ajax_update_cart_kk/kaveh_ajax_update_cart_kk_remove", 
    type: 'POST',
    data: {
      cart_item_key: cartItemKey,
      quantity: 0
    },
    beforeSend: function () {
        jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
    },
    success: function(response) {
      // Update the cart UI with the updated fragments
      if (response && response.fragments) {
        jQuery.each(response.fragments, function(key, value) {
          jQuery(key).replaceWith(value);
        });
      }
    },
    error: function(xhr, status, error) {
      // Handle any error that occurred during the AJAX request
    }
  });
});
});


jQuery(document).ready(function($) {
    jQuery(document).on('click', '.cart-sliding-content .changeinp', function() {
    var quantityInput = jQuery(this).siblings('.quantity').find('input[type=number]');
    var newQuantity = parseInt(quantityInput.val());
    var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
    // Send AJAX request to update the cart
    jQuery.ajax({
      url: ksiteurl + "/kaveh_ajax_update_cart_kk/kaveh_ajax_update_cart_kk", 
      type: 'POST',
      data: {
        cart_item_key: cartItemKey,
        quantity: newQuantity
      },
      beforeSend: function () {
          jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
      },
      success: function(response) {
        // Update the cart UI with the updated fragments
        if (response && response.fragments) {
          jQuery.each(response.fragments, function(key, value) {
            jQuery(key).replaceWith(value);
          });
        }
      },
      error: function(xhr, status, error) {
        // Handle any error that occurred during the AJAX request
      }
    });
  });
});


jQuery(document).on('click', '.eyeid', function(emy) {
  var fired_button = jQuery(this).attr('value');
  jQuery.ajax({
      url: ksiteurl + "/kaveh_ajax_popup/kaveh_ajax_popup",
      type: 'post',
      data: { 
        postid: fired_button, 
      },
      beforeSend: function(inud){
        Notiflix.Block.dots('#ajax_popup');
      },
      success: function(data) {
        jQuery('#ajax_popup').html( data );
      },

    });
    return false;
});


jQuery(document).on('click', '#kaveh_new_address', function($) {
  var user_id = jQuery(this).attr('userid');
  jQuery.ajax({
    url: ksiteurl + "/kaveh_ajax_checkout/new_address_modal",
    type: 'post',
    data: { 
      user_id: user_id,
    },
    beforeSend: function(){
      Notiflix.Block.dots('body');
    },
    success: function(data) {
      jQuery('.inner-modal').html(data);
      Notiflix.Block.remove('body');
    },

  });
  return false;
})


jQuery(document).on('click', '#kaveh_edit_address', function($) {
  var id = jQuery(this).attr('icd');
  var user_id = jQuery(this).attr('userid');
  jQuery.ajax({
    url: ksiteurl + "/kaveh_ajax_checkout/edit_address_modal",
    type: 'post',
    data: { 
      id: id,
      user_id: user_id,
    },
    beforeSend: function(){
      Notiflix.Block.dots('body');
    },
    success: function(data) {
      jQuery('.inner-modal').html(data);
      Notiflix.Block.remove('body');
    },

  });
  return false;
})


jQuery(document).on('click', '#kaveh_remove_address', function($) {
  var id = jQuery(this).attr('icd');
  var user_id = jQuery(this).attr('userid');
  jQuery.ajax({
    url: ksiteurl + "/kaveh_ajax_checkout/remove_address_modal",
    type: 'post',
    data: { 
      id: id,
      user_id: user_id,
    },
    beforeSend: function(){
      Notiflix.Block.dots('body');
    },
    success: function(data) {
      jQuery('#modern_checkout').html(data);
      Notiflix.Block.remove('body');
    },

  });
  return false;
})


jQuery(document).on('click', '#kaveh_save_address', function() {
  // Validation flag
  var isValid = true;

  // Validate each input field
  jQuery('input[name^="billing_"], select[name^="billing_"]').each(function() {
    if (jQuery(this).val() === '') {
      isValid = false;
      // You can add your validation error handling here, like showing an error message.
      alert('تمام فیلد ها الزامیست. لطفاً همه فیلد ها را پر کنید');
      return false; // Stop the loop if any field is empty
    }
  });
  
  // If validation failed, don't proceed with AJAX call
  if (!isValid) {
    return false;
  }

  // If all required fields are filled, proceed with AJAX call
  jQuery.ajax({
    url: ksiteurl + "/kaveh_ajax_checkout/add_address_modal",
    type: 'post',
    data: { 
      user_id: jQuery(this).attr('userid'),
      billing_first_name: jQuery('input[name="billing_first_name"]').val(),
      billing_last_name: jQuery('input[name="billing_last_name"]').val(),
      billing_phone: jQuery('input[name="billing_phone"]').val(),
      billing_email: jQuery('input[name="billing_email"]').val(),
      billing_state: jQuery('select[name="billing_state"]').find(":selected").val(),
      billing_city: jQuery('input[name="billing_city"]').val(),
      billing_address_1: jQuery('input[name="billing_address_1"]').val(),
      billing_address_2: jQuery('input[name="billing_address_2"]').val(),
      billing_postcode: jQuery('input[name="billing_postcode"]').val(),
      billing_company: jQuery('input[name="billing_company"]').val(),
      billing_country: jQuery('select[name="billing_country"]').find(":selected").val(),
    },
    beforeSend: function(){
      Notiflix.Block.dots('body');
    },
    success: function(data) {
      jQuery('#modal-new-address').modal('toggle');
      jQuery('#modern_checkout').html(data);
      Notiflix.Block.remove('body');
    }
  });

  return false; // Prevent default form submission
});
