<?php
global $result;
$location_id = $location_id;
$prepare_shipping_cost_text = '';
$currency_symbol = get_woocommerce_currency_symbol();

// Replace direct cookie access with getLocation()
$nearByAddress = getLocation('wcmlim_nearby_location');
$nearByAddress = str_replace(' ', '+', $nearByAddress);

if(empty($nearByAddress)) {
  $shipping_address = WC()->customer->get_shipping_address();
  $country = WC()->customer->get_shipping_country();
  $state   = WC()->customer->get_shipping_state();
  $postcode = WC()->customer->get_shipping_postcode();
  $city     = WC()->customer->get_shipping_city();
  //remove comma from city
  $city = str_replace(',', '', $city);
  $state = str_replace(',', '', $state);
} else {
  $address = $this->getAddress($nearByAddress);
  $country  = $address['country'];
  $state    = $address['state'];
  $postcode = $address['postal_code'];
  $city     = $address['city'];
}

if ($postcode && !WC_Validation::is_postcode($postcode, $country)) {
  throw new Exception(__('Please enter a valid postcode / ZIP.', 'woocommerce'));
} elseif ($postcode) {
  $postcode = wc_format_postcode($postcode, $country);
}

if ($country) {
  WC()->customer->set_location($country, $state, $postcode, $city);
  WC()->customer->set_shipping_location($country, $state, $postcode, $city);
  WC()->customer->set_shipping_address_1($city); 
} else {
  WC()->customer->set_to_base();
  WC()->customer->set_shipping_to_base();
}

WC()->customer->save();
WC()->customer->set_calculated_shipping(true);

do_action('woocommerce_calculated_shipping');

// Load and calculate shipping in one step
WC()->shipping->load_shipping_methods();
WC()->shipping->reset_shipping();
WC()->shipping->calculate_shipping(WC()->cart->get_shipping_packages());
$packages = WC()->shipping->get_packages();

// Get the shipping method for this location once outside the loop
$wcmlim_shipping_method = get_term_meta($location_id, 'wcmlim_shipping_method', true);

// Process packages more efficiently
if (!empty($packages)) {
  $result = [];
  foreach ($packages as $package) {
    if (!empty($package['rates'])) {
      foreach ($package['rates'] as $value) {
        $instance_id = $value->instance_id;
        // Check if instance_id exists in shipping method or if shipping method is empty
        if (empty($wcmlim_shipping_method) || in_array($instance_id, $wcmlim_shipping_method)) {
          $result[$value->cost] = "<li>" . $value->label . " <span> - " . $currency_symbol . " " . $value->cost . "</span></li>";
        }
      }
    }
  }
}

// Prepare shipping cost text if results exist
if (!empty($result) && is_array($result)) {
  ksort($result);
  $shipping_array_count = count($result);
  
  if ($shipping_array_count > 1) {
    // Get first and last elements after sorting without looping through all
    $costs = array_keys($result);
    $min_cost = $costs[0];
    $max_cost = $costs[$shipping_array_count - 1];
    $prepare_shipping_cost_text = $currency_symbol . $min_cost . '-' . $currency_symbol . $max_cost;
  } else {
    // Just get the first key for a single item
    $prepare_shipping_cost_text = $currency_symbol . key($result);
  }
}

return $prepare_shipping_cost_text;
die();