<?php
global $woocommerce;

$check_cart = get_option('wcmlim_clear_cart');
// Replace direct cookie fetching with getLocation()
$selected_store = getLocation('wcmlim_selected_location') ?: "";
$cookie_termId = getLocation('wcmlim_selected_location_termid') ?: "";
$check_ajax_add_to_cart = get_option('woocommerce_enable_ajax_add_to_cart');

$default_location = get_option('wcmlim_default_location');

if ($default_location == "on") {
  if (!empty($variation_id)) {
    $location_key = get_post_meta($variation_id, "wcmlim_default_location", true);
    $formatted_location = preg_replace('/[^0-9]/', '', $location_key);
  }
  $passed = true;
  return $passed;
}

if (!isset($selected_store) && !isset($cookie_termId)) {
  $default_location = get_option("wcmlim_enable_default_location");

  if ($default_location == "on") {
    $product_to_check = !empty($variation_id) ? $variation_id : $product_id;
    $location_key = get_post_meta($product_to_check, "wcmlim_default_location", true);
    
    if (!empty($location_key)) {
      $formatted_location_key = preg_replace('/[^0-9]/', '', $location_key);
      
      // Get term directly instead of looping through all locations
      if (is_numeric($formatted_location_key)) {
        $term = get_term_by('id', $formatted_location_key, 'locations');
        if ($term) {
          $loc_key = $formatted_location_key;
          $term_id = $term->term_id;
          
          // Set the location cookies
          setLocation("wcmlim_selected_location", $loc_key, 36000);
          setLocation("wcmlim_selected_location_termid", $term_id, 36000);
          
          // Re-fetch cookies using getLocation()
          $selected_store = getLocation('wcmlim_selected_location') ?: "";
          $cookie_termId = getLocation('wcmlim_selected_location_termid') ?: "";
        }
      }
    }
  }
}

if (empty($selected_store) && empty($cookie_termId)) {
  $passed = false;
  $validation_message = "Please select a location.";
  if (($check_ajax_add_to_cart == "no") || (function_exists('is_product'))) {
    wc_add_notice(__($validation_message, 'woocommerce'), 'error');
  }
  return $passed;
}

if (!empty($check_cart) && ($check_cart == "on")) {
  $validation_message = get_option('wcmlim_valid_cart_message') ?: "You can only order from one location! Please clear your cart to add items from another location.";
  
  $items = $woocommerce->cart->get_cart();
  if (!empty($items)) {
    // Get only the first item's location details
    $item = reset($items);
    $location_term_id = $item['select_location']['location_termId'];
    $location_name = $item['select_location']['location_name'];

    if ($location_term_id != $cookie_termId) {
      $passed = false;
      wc_add_notice(__($validation_message, 'woocommerce'), 'error');
    } else {
      $passed = true;
    }
  }
  return $passed;
} else {
  $passed = true;
  return $passed;
}
?>


