<?php
$slCookie = getLocation('wcmlim_selected_location');
$cookie_termId = getLocation('wcmlim_selected_location_termid');
$terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));

// Initialize variables
$location_name = "";
$_location_key = "";
$_location_qty = "";
$_location_termId = "";
$_location_regular_price = "";
$_location_sale_price = "";

// Single loop to handle both finding term ID and getting location data
foreach ($terms as $term => $value) {
    if (empty($cookie_termId) && $slCookie == $term) {
        $cookie_termId = $value->term_id;
    }
    
    if ($cookie_termId == $value->term_id) {
        $location_name = $value->name;
        $_location_key = $value->term_id; // Use term ID instead of loop index
        $_location_qty = get_post_meta($product->get_id(), "wcmlim_stock_at_{$value->term_id}", true);
        $_location_regular_price = get_post_meta($product->get_id(), "wcmlim_regular_price_at_{$value->term_id}", true);
        $_location_sale_price = get_post_meta($product->get_id(), "wcmlim_sale_price_at_{$value->term_id}", true);
        $_location_termId = $value->term_id;
    }
}

// Ensure variables have proper types or defaults
$_location_qty = !empty($_location_qty) ? (int)$_location_qty : "";
$_location_termId = !empty($_location_termId) ? (int)$_location_termId : "";
$_isRedirect = get_option("woocommerce_cart_redirect_after_add");
$_cart_url = wc_get_cart_url();

if ($product->is_type('simple') && !$product->is_downloadable() && !$product->is_virtual())  {
    $_product_id = $product->get_id();
    $_product_sku = $product->get_sku();
    $_product_name = $product->get_name();
    $_product_price = $product->get_price();
    $_product_backorder = $product->backorders_allowed();
    $_manage_stock_enabled = get_post_meta($_product_id, '_manage_stock', true);
    
    if($_manage_stock_enabled == 'no') {
        return $button;
    }

    $check_ajax_add_to_cart = get_option('woocommerce_enable_ajax_add_to_cart');
    if($check_ajax_add_to_cart == "yes") {
        $button_text = __("Add to cart", "woocommerce");
        $button = '<a data-cart-url="' . $_cart_url . '" data-isredirect="' . $_isRedirect . '" data-quantity="1" class="button product_type_simple add_to_cart_button wcmlim_ajax_add_to_cart" data-product_id="' . $_product_id . '" data-product_sku="' . $_product_sku . '" aria-label="Add "' . $_product_name . '" to your cart" data-selected_location="' . $location_name . '" data-location_key="' . $_location_key . '" data-location_qty="' . $_location_qty . '" data-location_termid="' . $_location_termId . '" data-product_price="' . $_product_price . '" data-location_sale_price="' . $_location_sale_price . '" data-location_regular_price="' . $_location_regular_price . '" data-product_backorder="' . $_product_backorder . '" rel="nofollow">' . $button_text . '</a>'; 
        return $button;
    } else {
        if ( $product ) {
            $defaults = array(
                'class' => implode( ' ', array_filter( array(
                    'button',
                    'product_type_' . $product->get_type(),
                    $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
                ) ) ),
            );
        }
        $class = apply_filters( 'woocommerce_loop_add_to_cart_args', $defaults )['class'];
        
        // Common button parameters
        $cart_url = esc_url( $product->add_to_cart_url() );
        $quantity = esc_attr( isset( $quantity ) ? $quantity : 1 );
        $location_params = '&selected_location='.$location_name.'&location_key='.$_location_key.'&location_qty='.$_location_qty.'&location_regular_price='.$_location_regular_price.'&location_sale_price='.$_location_sale_price;
        
        // WC versions before 3.3 did not have the product description aria-label
        if ( version_compare( get_option( 'woocommerce_version' ), '3.3.0', '<' ) ) {
            $button = sprintf( '<a rel="nofollow" href="%s&quantity=%s%s" class="button product_type_simple add_to_cart_button wcmlim_add_to_cart" >Add To Cart</a>',
                $cart_url,
                $quantity,
                $location_params
            );
        } else {
            $button = sprintf( '<a rel="nofollow" href="%s&quantity=%s%s" class="button product_type_simple add_to_cart_button wcmlim_add_to_cart" >Add To Cart</a>',
                $cart_url,
                $quantity,
                $location_params
            );
        }
        
        return $button;     
    }
} else {
    return $button;
}



