import * as alies_localization from "./wcmlim_utility/generic/wcmlim_localization.js";
import * as alies_listOrdering from "./wcmlim_utility/generic/wcmlim_listOrdering.js";
import * as alies_sc_listOrdering from "./wcmlim_utility/generic/wcmlim_sc_listOrdering.js";
import * as alies_getcookies from "./wcmlim_utility/generic/wcmlim_getcookies.js";
import * as alies_setcookies from "./wcmlim_utility/generic/wcmlim_setcookies.js";
import * as alies_mapWidget from "./wcmlim_utility/generic/wcmlim_map_widget.js";
import * as alies_selectLocation from "./wcmlim_utility/generic/wcmlim_select_location.js";
// import * as alies_showPosition from "./wcmlim_utility/generic/wcmlim_show_possition.js";
import * as alies_GlobalMapList from "./wcmlim_utility/generic/wcmlim_global_maplist.js";
import * as alies_setLocation from "./wcmlim_utility/generic/wcmlim_set_location.js";
import * as alies_cookieExists from "./wcmlim_utility/generic/wcmlim_cookie_exists.js";
import * as alies_VariationIdCheck from "./wcmlim_utility/generic/wcmlim_variation_check.js";
import * as alies_CommonFunction from "./wcmlim_utility/generic/wcmlim_common_functions.js";
import * as alies_ChangeLc from "./wcmlim_utility/generic/wcmlim_change_lc_select.js";
import * as alies_SubmitPostcodeProduct from "./wcmlim_utility/generic/wcmlim_submit_postcode_product.js";
const currentProductId = wcmlim_product_data.product_id;


var localization = alies_localization.wcmlim_localization();

//import {test} from "./wcmlim_utlity/generic/wcmlim_localization.js";

/**
 * Retrieves the value of a specified cookie by name.
 *
 * @param {string} name - The name of the cookie to retrieve.
 * @returns {string|null} The value of the cookie, or null if the cookie does not exist.
 */
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
  }
  else
  {
      begin += 2;
      var end = document.cookie.indexOf(";", begin);
      if (end == -1) {
      end = dc.length;
      }
  }
  // because unescape has been deprecated, replaced with decodeURI
  //return unescape(dc.substring(begin + prefix.length, end));
  return decodeURI(dc.substring(begin + prefix.length, end));
} 

/**
 * Updates the quantity input field based on the selected location.
 *
 * @param {string} location - The selected location.
 * @param {number} quantity - The quantity to set.
 */
function wcmlim_set_quantity_input(location){
  const variationId = jQuery("input.variation_id").val();
  jQuery
  .ajax({
    url: localization.ajaxurl,
    type: "post",
    data: {
      currentProductId: currentProductId,
      variationId: variationId,
      selectedLocation: location,
      action: "wcmlim_get_quantity_attributes",
    },
    success: function (response) {
      if (response.data.backorder) {
        jQuery(".qty").val(1);
        jQuery(".qty").removeAttr("max");
        jQuery(".qty").prop('disabled', false);
        jQuery(".qty").trigger('change');
        jQuery(".single_add_to_cart_button").show();
        jQuery(".single_add_to_cart_button").removeClass("disabled");
        jQuery(".input-text").show();
        jQuery(".quantity").show();
        jQuery("#globMsg").hide();
        jQuery("#losm").hide();
        jQuery(".qty").removeAttr("max");
        jQuery(".stock").hide();
      } else if (response.data.backorder == false && response.data.stock <= 0) {
        jQuery(".qty").val(0);
jQuery(".qty").attr("max", 0);
jQuery(".qty").prop('disabled', true); 
jQuery(".qty").trigger('change');
        jQuery(".single_add_to_cart_button").hide();
        jQuery(".quantity").hide();
        jQuery("#globMsg").hide();
        jQuery("#losm").show();
        // add stock status message for location if not there
        if (!response.data.is_prodict_variable && location != -1) {
          if (jQuery("#losm").length === 0) {
            jQuery("<p id='losm'> " + (response.data.soldout || "Out of Stock") + "</p>").insertAfter(".Wcmlim_prefloc_sel");
          }
        }
      } else {
        jQuery(".qty").val(1);
jQuery(".qty").attr("max", response.data.stock);
jQuery(".qty").prop('disabled', false);
jQuery(".qty").trigger('change');
        jQuery(".single_add_to_cart_button").removeClass("disabled");
        jQuery("#globMsg").show();
        if(response.data.threshold_text != null){
          jQuery("#globMsg").html(`<b>${response.data.threshold_text}</b>`);
        }
        jQuery("#losm").hide();
        // add stock status message for location if not there
        if (!response.data.is_prodict_variable && location != -1) {
          if (jQuery("#globMsg").length === 0) {
            if(localization.is_hide_stock_count == 'on'){
              jQuery("<p id='globMsg'> " + response.data.instock + "</p>").insertAfter(".Wcmlim_prefloc_sel");
            } else {
              jQuery("<p id='globMsg'> <b>" + response.data.stock + "</b> " + response.data.instock + "</p>").insertAfter(".Wcmlim_prefloc_sel");
            }
          }
        }
      }
    }
  });
}

/**
 * Restricts the quantity in the cart page based on the stock available at the selected location.
 */
function restrictCartQuantity() {
  jQuery(".cart_item").each(function () {
    const cartItem = jQuery(this);
    const productId = cartItem.find(".product-name a").data("product-id");
    const selectedLocation = getCookie("wcmlim_selected_location");

    if (productId && selectedLocation) {
      jQuery.ajax({
        url: localization.ajaxurl,
        type: "post",
        data: {
          action: "wcmlim_get_stock_for_location",
          product_id: productId,
          location: selectedLocation,
        },
        success: function (response) {
          if (response.success && response.data.stock !== undefined) {
            const maxStock = response.data.stock;
            const quantityInput = cartItem.find(".quantity input.qty");
            const currentQuantity = parseInt(quantityInput.val());

            if (currentQuantity > maxStock) {
              quantityInput.val(maxStock);
              Swal.fire({
                icon: "error",
                text: `The maximum quantity available for this product at the selected location is ${maxStock}.`,
              });
            }

            quantityInput.attr("max", maxStock);
          }
        },
      });
    }
  });
}

// Trigger the restriction on cart page load and quantity change
jQuery(document).ready(function () {
  if (jQuery(".woocommerce-cart-form").length > 0) {
    restrictCartQuantity();

    jQuery(document).on("change", ".quantity input.qty", function () {
      restrictCartQuantity();
    });
  }
});

jQuery(document).ready(($) => {
  $.noConflict();
  alies_CommonFunction.Hide_OOS_Product_Allover();

  alies_CommonFunction.NearbyLocationFn();

  alies_listOrdering.listOrdering();
  alies_sc_listOrdering.sc_listOrdering();
  alies_mapWidget.mapWidget("elementIdGlobalMap", "rangeInput", "my_current_location");
  alies_mapWidget.mapWidget("elementIdGlobalMaplist", "rangeInputList", "my_current_location_list");
  alies_GlobalMapList.GlobalMapList("elementIdGlobalMap", "rangeInput");
  alies_GlobalMapList.GlobalMapList("wcmlim_storeshrtsearch_input", "storeshrtsearchstore");
  alies_GlobalMapList.GlobalMapList("elementIdGlobalMaplist", "rangeInputList");
  alies_GlobalMapList.rangeInputCallback("rangeInput");
  alies_GlobalMapList.rangeInputCallback("rangeInputList");

  alies_CommonFunction.autodetectFn();

  alies_CommonFunction.Restricted_Location();
  alies_cookieExists.CookieExists();
  alies_VariationIdCheck.variationIdExists();
  alies_CommonFunction.isLocationsGroupFn();

  // get selected location from cookie
  var selectedLocation = getCookie('wcmlim_selected_location');

  $("#select_location").on("change", function (e) {
   var value = $(this).find(":selected").val();
   
   jQuery
   .ajax({
     url: localization.ajaxurl,
     type: "post",
     data: {
       loc_key: value,
       action: "wcmlim_set_location_on_change",
      }, // run after location change
      success: function(response) {
        if (response.data == "success") {
          // set the quanity input value and attribute according to location
          wcmlim_set_quantity_input(value);
          if(selectedLocation != value){
            selectedLocation = value;
          }
        }
      }
    });

    if ($(".wclimadvlist").length < 1) {
      alies_selectLocation.select_location(this);
    }
  });

  
  document.querySelectorAll(".location-stock-item").forEach(item => {
    item.addEventListener("click", function () {
        let radio = this.querySelector("input[type='radio']");
        alies_selectLocation.select_location(radio);
        if (radio) {
            radio.checked = true;
            handleLocationChange(radio);
        }
    });
});


function handleLocationChange(radio) {
  let value = radio.value;
  jQuery
  .ajax({
    url: localization.ajaxurl,
    type: "post",
    data: {
      loc_key: radio.value,
      action: "wcmlim_set_location_on_change",
     }, // run after location change
     success: function(response) {
       if (response.data == "success") {
         // set the quanity input value and attribute according to location
         wcmlim_set_quantity_input(value); 
         if(selectedLocation != value){
           selectedLocation = value;
         }
       }
       if( jQuery('#wcmlim-sidePopup').length > 0 ) {
        jQuery("#wcmlim-sidePopup").css('width', '0px');
       }
       if( jQuery('#wcmlim-modalPopup').length > 0 ) {
        jQuery("#wcmlim-modalPopup").css('display', 'none');
       }
     }
   });
   
   if (localization.isClearCart == "on") {
    calltothecartupdate(value);
   }

   highlightSelectedLocation();
}

function calltothecartupdate(value) {
  
  jQuery.ajax({
              type: "POST",
              url: localization.ajaxurl,
              data: {
                e_value : value,
                action: "wcmlim_ajax_cart_count",
                security: localization.security,
              },
              success(response) {
                // NEW: Handle purchase_one_location scenarios
                if (typeof response === 'string' && response.startsWith('{')) {
                  try {
                          const responseData = JSON.parse(response);
                          
                          if (responseData.status === 'location_change') {
                              // All products available at new location - offer to change location
                              Swal.fire({
                                  title: wc_add_to_cart_params._purchase_change_location_text,
                                  text: `Your cart contains items from ${responseData.current_location}. Do you want to change all items to ${responseData.new_location_name}?`,
                                  icon: "question",
                                  showCancelButton: true,
                                  confirmButtonColor: "#3085d6",
                                  cancelButtonColor: "#d33",
                                  confirmButtonText: "Yes, Change Location!",
                                  cancelButtonText: "Cancel"
                              }).then((result) => {
                                  if (result.isConfirmed) {
                                      console.log('User confirmed location change');
                                      console.log('Response data:', responseData);
                                      
                                      // Update cart location via AJAX
                                      let ajaxurl;
                                      if (typeof multi_inventory !== 'undefined' && multi_inventory.ajaxurl) {
                                          ajaxurl = multi_inventory.ajaxurl;
                                      } else if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.ajax_url) {
                                          ajaxurl = wc_add_to_cart_params.ajax_url;
                                      } else {
                                          console.error('No AJAX URL found');
                                          Swal.fire({ 
                                              title: "Error!", 
                                              text: "AJAX URL not available. Please refresh the page and try again.", 
                                              icon: "error" 
                                          });
                                          return;
                                      }
                                      
                                      console.log('AJAX URL:', ajaxurl);
                                      
                                      jQuery.ajax({
                                          url: ajaxurl,
                                          type: "post",
                                          data: { 
                                              action: "wcmlim_update_cart_location",
                                              new_location_id: responseData.new_location_id,
                                              new_location_key: value,
                                              remove_unavailable: false,
                                              security: localization.security
                                          },
                                          beforeSend: function() {
                                              console.log('Sending AJAX request to update cart location');
                                          },
                                          success(updateResponse) {
                                              console.log('AJAX success response:', updateResponse);
                                              try {
                                                  const updateData = JSON.parse(updateResponse);
                                                  console.log('Parsed response:', updateData);
                                                  if (updateData.status === 'success') {
                                                      Swal.fire({ 
                                                          title: "Location Updated!", 
                                                          text: `Cart location changed to ${updateData.new_location}. Product added successfully!`, 
                                                          icon: "success" 
                                                      }).then(() => {
                                                          window.location.href = window.location.href;
                                                      });
                                                  } else {
                                                      console.error('Update failed:', updateData);
                                                      Swal.fire({ 
                                                          title: "Error!", 
                                                          text: updateData.message || "Failed to update cart location.", 
                                                          icon: "error" 
                                                      });
                                                  }
                                              } catch (e) {
                                                  console.error('Error parsing response:', e, updateResponse);
                                                  Swal.fire({ 
                                                      title: "Error!", 
                                                      text: "Invalid response from server.", 
                                                      icon: "error" 
                                                  });
                                              }
                                          },
                                          error(xhr, status, error) {
                                              console.error('AJAX error:', {xhr, status, error});
                                              console.error('Response text:', xhr.responseText);
                                              Swal.fire({ 
                                                  title: "Error!", 
                                                  text: "Failed to update cart location: " + error, 
                                                  icon: "error" 
                                              });
                                          }
                                      });
                                  } else {
                                      console.log('User cancelled location change');
                                      jQuery.ajax({
                                          url: localization.ajaxurl,
                                          type: "post",
                                          data: { 
                                              action: "wcmlim_set_location_on_change",
                                              loc_key: responseData.current_location_key,
                                              security: localization.security
                                          },
                                          success: function(response) {
                                              console.log('Cookie reset successful:', response);
                                              // Set cookies on client side as well
                                              alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                              alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                              
                                              jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                              jQuery(".single_add_to_cart_button").prop("disabled", false);
                                              jQuery(".wcmlim_cart_valid_err").remove();
                                              window.location.href = window.location.href;
                                          },
                                          error: function(xhr, status, error) {
                                              console.error('Error setting cookies:', error);
                                              // Fallback: set cookies on client side only
                                              alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                              alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                              
                                              jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                              jQuery(".single_add_to_cart_button").prop("disabled", false);
                                              jQuery(".wcmlim_cart_valid_err").remove();
                                              window.location.href = window.location.href;
                                          }
                                      });
                                  }
                              });
                              return false;
                          }
                          
                          if (responseData.status === 'unavailable_products') {
                              // Some products not available at new location - offer to clear cart
                              let unavailableList = responseData.unavailable_products.map(p => `• ${p.name} (Qty: ${p.quantity})`).join('\n');
                              
                              Swal.fire({
                                  title: wc_add_to_cart_params._purchase_change_location_notavailtext,
                                  text: `The following products are not available at ${responseData.new_location_name}:\n\n${unavailableList}\n\nDo you want to remove these products and move the remaining items to ${responseData.new_location_name}?`,
                                  icon: "warning",
                                  showCancelButton: true,
                                  confirmButtonColor: "#d33",
                                  cancelButtonColor: "#3085d6",
                                  confirmButtonText: "Yes, Remove & Update!",
                                  cancelButtonText: "Cancel"
                              }).then((result) => {
                                  if (result.isConfirmed) {
                                      // Remove only unavailable products and update available ones to new location
                                      jQuery.ajax({
                                          url: localization.ajaxurl,
                                          type: "post",
                                          data: { 
                                              action: "wcmlim_update_cart_location",
                                              unavailable_products: JSON.stringify(responseData.unavailable_products),
                                              new_location_id: responseData.new_location_id,
                                              new_location_key: value,
                                              remove_unavailable: true,
                                              security: localization.security
                                          },
                                          beforeSend: function() {
                                              jQuery(".wcmlim_cart_valid_err").html("<center><i class='fas fa-spinner fa-spin'></i> Updating cart...</center>");
                                          },
                                          success(output) {
                                              console.log('Cart updated successfully:', output);
                                              try {
                                                  const updateData = JSON.parse(output);
                                                  if (updateData.status === 'success') {
                                                      let message = `Location changed to ${updateData.new_location}.`;
                                                      
                                                      // If products were removed, show details
                                                      if (updateData.removed_products && updateData.removed_products.length > 0) {
                                                          message += `\n\nRemoved products:\n${updateData.removed_products.map(name => `• ${name}`).join('\n')}`;
                                                      }
                                                      
                                                      Swal.fire({ 
                                                          title: "Cart Updated!", 
                                                          text: message,
                                                          icon: "success" 
                                                      }).then(() => {
                                                          // Continue with normal location change processing
                                                          jQuery(".single_add_to_cart_button").prop("disabled", false);
                                                          jQuery(".wcmlim_cart_valid_err").remove();
                                                          alies_selectLocation.select_location("#select_location");
                                                          // Refresh the page to update cart display
                                                          window.location.href = window.location.href;
                                                      });
                                                  } else {
                                                      Swal.fire({ 
                                                          title: "Error!", 
                                                          text: updateData.message || "Failed to update cart.", 
                                                          icon: "error" 
                                                      });
                                                  }
                                              } catch (e) {
                                                  console.error('Error parsing response:', e);
                                                  Swal.fire({ 
                                                      title: "Error!", 
                                                      text: "Invalid response from server.", 
                                                      icon: "error" 
                                                  });
                                              }
                                          },
                                          error: function(xhr, status, error) {
                                              console.error('Error updating cart:', error);
                                              Swal.fire({ 
                                                  title: "Error!", 
                                                  text: "There was an error updating the cart.", 
                                                  icon: "error" 
                                              });
                                              // Reset dropdown to previous location
                                              jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                              jQuery(".single_add_to_cart_button").prop("disabled", false);
                                              jQuery(".wcmlim_cart_valid_err").remove();
                                          }
                                      });
                                  } else {
                                      // User cancelled - reset dropdown to previous location
                                      console.log('User cancelled, resetting to previous location');
                                      
                                      // Make AJAX call to set cookies properly on server side
                                      jQuery.ajax({
                                          url: localization.ajaxurl,
                                          type: "post",
                                          data: { 
                                              action: "wcmlim_set_location_on_change",
                                              loc_key: responseData.current_location_key,
                                              security: localization.security
                                          },
                                          success: function(response) {
                                              console.log('Cookie reset successful:', response);
                                              // Set cookies on client side as well
                                              alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                              alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                              
                                              jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                              jQuery(".single_add_to_cart_button").prop("disabled", false);
                                              jQuery(".wcmlim_cart_valid_err").remove();
                                              window.location.href = window.location.href;
                                          },
                                          error: function(xhr, status, error) {
                                              console.error('Error setting cookies:', error);
                                              // Fallback: set cookies on client side only
                                              alies_setcookies.setcookie("wcmlim_selected_location", responseData.current_location_key);
                                              alies_setcookies.setcookie("wcmlim_selected_location_termid", responseData.current_location_id);
                                              
                                              jQuery("#wcmlim-change-lc-select").val(responseData.current_location_key);
                                              jQuery(".single_add_to_cart_button").prop("disabled", false);
                                              jQuery(".wcmlim_cart_valid_err").remove();
                                              window.location.href = window.location.href;
                                          }
                                      });
                                  }
                              });
                              return false;
                          }
                      } catch (e) {
                          // Not a JSON response, continue with normal processing
                          console.log('Non-JSON response received:', response);
                      }
                } 
                
              },
            });
}


function highlightSelectedLocation() {
  let selectedLocation = document.querySelector('input[name="select_location"]:checked');
  document.querySelectorAll('.location-stock-item').forEach(item => item.classList.remove('highlighted'));
  if (selectedLocation) {
      selectedLocation.closest('.location-stock-item').classList.add('highlighted');
  }
}

jQuery(document).on("click", ".wcmlim-storeshrtlocation_item", function () {
  let radio = this.querySelector("input[type='radio']");
  if (radio) {
      radio.checked = true;
      handleStoreChange(radio, "yes");
  }
});

function handleStoreChange(radio) {
  let value = radio.value;
  jQuery
  .ajax({
    url: localization.ajaxurl,
    type: "post",
    data: {
      loc_key: radio.value,
      action: "wcmlim_set_location_on_change",
     }, // run after location change
     success: function(response) {
       if (response.data == "success") {
          if(selectedLocation != value){
            selectedLocation = value;
          }
       }
       jQuery('#wcmlim-storeshrtclosePopupBtn').trigger('click');
     }
   });

   highlightSelectedLocationStore();
}


function highlightSelectedLocationStore() {
  let selectedLocation = document.querySelector('input[name="select_location"]:checked');
  if(jQuery(".wcmlim-storeshrtlocation_item").length > 0) {
    document.querySelectorAll('.wcmlim-storeshrtlocation_item').forEach(item => item.classList.remove('highlighted'));
    if (selectedLocation) {
        let locationName = selectedLocation.dataset.locationname;
        jQuery("#wcmlim-storeshrtselected").text(locationName);
        jQuery('#wcmlim_storeshrtsearch_input').val(locationName);
        if(jQuery('#wcmlim_storeshrtsearch_input').val() != "") {
          jQuery("#wcmlim-storeshrtdetect_icons").hide();
          jQuery("#wcmlim-storeshrtsearch_icons").hide();
          jQuery("#wcmlim-storeshrtsearch_apply").show();
          jQuery("#wcmlim-storeshrtsearch_remove").show();
        } else {
          jQuery("#wcmlim-storeshrtdetect_icons").show();
          jQuery("#wcmlim-storeshrtsearch_icons").show();
          jQuery("#wcmlim-storeshrtsearch_apply").hide();
          jQuery("#wcmlim-storeshrtsearch_remove").hide();
        }
        selectedLocation.closest('.wcmlim-storeshrtlocation_item').classList.add('highlighted');
    }
  }
}


  let loader = alies_CommonFunction.loaderhtml();
  alies_SubmitPostcodeProduct.submitPostcodeProduct(loader);

  /**
   * Pincode change.
   */
  $(document).on("click", "[data-wpzc-form-open]", (e) => {
    e.preventDefault();
    $(".class_post_code").val("");
    $(".postcode-checker-change").hide();
    $(".postcode-location-distance").hide();
    $(".postcode-checker-div")
      .removeClass("postcode-checker-div-hide")
      .addClass("postcode-checker-div-show");
    $(".postcode-checker-response").empty();
  });

  alies_ChangeLc.ChangeLcSelectWithLocation();
  alies_ChangeLc.ChangeLc_Select();
  alies_CommonFunction.wcmlim_locwid_dd();
  alies_CommonFunction.post_code_checker_common("class_post_code");
  alies_CommonFunction.post_code_checker_common("class_post_code_global");

  $(document).on("click", "#submit_postcode_global", function (e) {
    var val = $(this)
      .closest("div.wcmlim_form_box")
      .find("input[name='post_code_global']")
      .val();
    
    // Get coordinates from cookies if available
    const existingLat = alies_getcookies.getCookie("wcmlim_user_lat");
    const existingLng = alies_getcookies.getCookie("wcmlim_user_lng");
    
    if (val) {
      if (existingLat && existingLng) {
        alies_setLocation.setLocation(val, existingLat, existingLng);
      } else {
        alies_setLocation.setLocation(val);
      }
    } else {
      if (existingLat && existingLng) {
        alies_setLocation.setLocation(null, existingLat, existingLng);
      } else {
        alies_setLocation.setLocation();
      }
    }

  });





  $("input[type=radio][name=select_location]").change(function () {
    var stockQt = $("#select_location")
      .find("option:selected")
      .attr("data-lc-qty");
    var text_qty = document.getElementsByClassName("qty")[0].value;
    const boStatus = $("#backorderAllowed").val();

    if (boStatus != 1) {
      if (stockQt < text_qty) {
        $(".qty").attr({ max: stockQt });
        document.getElementById("lc_qty").value = stockQt;
        document.getElementsByClassName("qty")[0].value = 1;
      } else {
        $(".qty").attr({ max: stockQt });
        if(jQuery('#lc_qty').length > 0){
          document.getElementById("lc_qty").value = stockQt;
        }
      }
    }
  });

  $("#select_location").on("change", function () {
    var addcartid = $(this).data("lc-id");
    var term_key = $(this).val();
    var product_simple = jQuery('.single_add_to_cart_button').val();
    var product_vid = jQuery("input.variation_id").val();
    var prodsaleprice = $(this).find(':selected').data("lc-sale-price");
    var prodcity = $(this).find(':selected').data("lc-city");
    var productprice = productprice ? prodregularprice : prodsaleprice;
    var product_qty = $(".qty").val();
    var prodregularprice = $(this).find(':selected').data("lc-regular-price");
    var prod_backorder = $(this).find(':selected').data("lc-backorder");
    if (localization.isBackorderOn == "on") {
      $("#globMsg").hide();
      $("#losm").hide();
      $.ajax({
        url: localization.ajaxurl,
        type: "post",
        data: {
          action: "wcmlim_backorder4el",
          term_key: term_key,
          addcartid: addcartid,
          prodregularprice: prodregularprice,
          prodsaleprice: prodsaleprice,
          productprice: productprice,
          product_qty: product_qty,
          prodcity: prodcity,
          product_vid: product_vid,
          product_simple: product_simple,
          security: localization.security,
        },
        success(response) {
          if(response ==""){
            $(".single_add_to_cart_button").hide();
            $(".quantity").hide();
          }
          if (response == "show_btn" || prod_backorder == "yes") {
            var quantityInput = document.getElementsByName('quantity')[0];

            $(".single_add_to_cart_button").show();
            $(".single_add_to_cart_button").removeClass("disabled");
            $(".input-text").show();
            $(".quantity").show();
            $(".qty").removeAttr("max");
            $("#losm").hide();
            $(".stock").hide();
            $("#globMsg").hide();

            // Update the existing input
quantityInput.value = quantityInput.value;

          }
          else {
            if (response == "ofs") {
              $(".single_add_to_cart_button").addClass("disabled");
              $("#losm").show();
            }
            if (response == "instk") {
              $(".single_add_to_cart_button").removeClass("disabled");
              $("#losm").hide();
              $(".stock").show();
              $("#globMsg").show();
            } else {
              $("#globMsg").show();
            }
          }
        },
      });
    }
  });
  //trigger change event after 5 second
  setTimeout(function () {
    $("#select_location").trigger("change");
  }, 2000);


  //removed as allowed specific location is default

  $(document).ready(function () {
    //fetch product name of current selected item
    function getProductName(button) {
      return jQuery(button).closest('.product-wrapper').find('h3.wd-entities-title').text().trim();
    }
    //on click of +/-/add to cart trigger action for shop page
    jQuery('.wd-add-btn-replace').on('click', '.plus, .minus,.add_to_cart_button.wcmlim_ajax_add_to_cart', function () {

      var quantityInput = jQuery(this).closest('.wd-add-btn-replace').find('.input-text.qty.text');
      var locationQty = jQuery(this).closest('.wd-add-btn-replace').find('a.add_to_cart_button').data('location_qty');
      var locationName = jQuery(this).closest('.wd-add-btn-replace').find('a.add_to_cart_button').data('selected_location');
      var productName = getProductName(this);

      var enteredQuantity = parseInt(quantityInput.val()); // Get the entered quantity

      quantityInput.attr('max', locationQty, locationName);

      // Check if the entered quantity is less than 1
      if (enteredQuantity < 1) {
        Swal.fire({ "icon": "error", "text": "Quantity cannot be 0." })
        return;
      }

      // Check if the entered quantity exceeds the maximum allowed value
      if (enteredQuantity > locationQty) {
        Swal.fire({ "icon": "error", "text": "Sorry, we do not have enough <strong>" + productName + "</strong> in stock to fulfill your order (" + locationQty + " available) for " + locationName + ". We apologize for any inconvenience caused." })
        return;
      }

    });

    setTimeout(function () {
      if (jQuery(".variations").length > 0) {
        $(".variations").trigger("click");
      }
    }, 2000);
  });

  // hide location dropdwon variation
  alies_CommonFunction.hideDropdown();
  // code -end
});
jQuery(document).ready(function ($) {
  if (wcmlim_public.hideDetailsOnHover) {
    // Apply the CSS to hide the element on hover using jQuery
    $('#wcmlim_select_or_dropdown').hover(
      function () { // Mouse over
        $(this).find('.quantity').hide(); // Corrected class selectors
      },
      function () { // Mouse out
        $(this).find('.quantity').show(); // Corrected class selectors
      }
    );
  }
  /* AST Code for diable the Apply button Starts */
  var zipcode_val = $("#elementIdGlobal").val();
  $("#elementIdGlobal").keyup(function () {
    zipcode_val = $(this).val();
    if (zipcode_val == "") {
      $("#submit_postcode_global").attr("disabled", true);
    } else {
      $("#submit_postcode_global").attr("disabled", false);
    }
  });

 
  /* AST Code for diable the Apply button End */

  var hiddenValue = jQuery('input[name="global_postal_location"]').val();
    
  // Set the retrieved value as the placeholder for the text input
  jQuery('input[name="post_code_global"]').attr('placeholder', hiddenValue);
});


jQuery(document).ready(function($) {
  // Function to force the visibility of our target elements
  function forceUnhide() {
    $('.summary.entry-summary .single_add_to_cart_button, .quantity, .quantity input.qty').each(function() {
      // Only update if the element appears hidden
      if ($(this).css('display') === 'none' || $(this).css('visibility') === 'hidden') {
        $(this).removeAttr('style').css({
          'visibility': 'visible',
          'opacity': 1
        });
      }
    });
  }
  
  // Run on page load
  forceUnhide();
  
  // Reapply when WooCommerce triggers variation events
  $('form.variations_form').on('show_variation reset_data found_variation', function() {
    forceUnhide();
  });
  
  // Fallback: Inject CSS to force these elements visible, without overriding pointer-events
  if ($('#custom-unhide-css').length === 0) {
    $('<style id="custom-unhide-css">')
      .prop('type', 'text/css')
      .html(
        '.summary.entry-summary .single_add_to_cart_button, .quantity, .quantity input.qty { ' +
          'visibility: visible !important; ' +
          'opacity: 1 !important; ' +
        '}'
      )
      .appendTo('head');
  }
});

