<?php 

$selected_store = getLocation('wcmlim_selected_location') ?: "";
$cookie_termId = getLocation('wcmlim_selected_location_termid') ?: "";
$product = wc_get_product( $product_id );

// Early return if location not selected
if (empty($selected_store) && empty($cookie_termId)) {
    if ($product-> is_virtual('yes')) {
    } else {
        wc_add_notice(__("Please select a location before adding to cart", 'wcmlim'), 'error');
        return false;
    }
} 
if ($product-> is_virtual('yes')) {
    return true; // Virtual products don't require location selection
}
// Get term ID directly from cookie if available, otherwise find it in locations
$term_id = $cookie_termId;
if (empty($term_id) && !empty($selected_store)) {
    $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    foreach ($locations as $key => $term) {
        if ($key == $selected_store) {
            $term_id = $term->term_id;
            break; // Exit loop once found
        }
    }
}

$cart = WC()->cart;

/**
 * Check if stock is available for the given product/variation at a specific location
 * 
 * @param int $product_id The product or variation ID
 * @param int $location_id The location term ID
 * @param int $request_qty Quantity being requested
 * @param int $cart_qty Existing quantity in cart (0 if not in cart)
 * @return bool Whether stock is available
 */
function is_stock_available($product_id, $location_id, $request_qty, $cart_qty = 0) {
    $stock_meta_key = 'wcmlim_stock_at_' . $location_id;
    $available_quantity = get_post_meta($product_id, $stock_meta_key, true) ?: 0;
    $current_available_quantity = $available_quantity - $cart_qty;
    
    // Check if backorders are allowed
    $backorder_meta_key = 'wcmlim_allow_backorder_at_' . $location_id;
    $get_backorder = get_post_meta($product_id, $backorder_meta_key, true) ?: "No";
    
    // If backorders allowed, stock check passes
    if ($get_backorder != "No") {
        return true;
    }
    
    // If no stock or not enough stock, fail
    if ($available_quantity == 0 || empty($available_quantity) || $request_qty > $current_available_quantity) {
        return false;
    }
    
    return true;
}

// Handle variation product
if (!empty($variation_id)) {
    // Check if variation exists
    if (get_post_status($variation_id) !== 'publish') {
        wc_add_notice(__("The selected variation is not available.", 'wcmlim'), 'error');
        return false;
    }
    
    // Check if manage stock is enabled for the variation
    $manage_stock_variation = get_post_meta($variation_id, '_manage_stock', true);
    if (!$manage_stock_variation) {
        return true; // Stock not managed, allow adding to cart
    }
    
    // Check cart for matching variation and location
    if (!$cart->is_empty()) {
        foreach ($cart->get_cart() as $cart_item) {
            $cart_variation_id = $cart_item['variation_id'];
            $location_term_id = $cart_item['select_location']['location_termId'];
            
            // Only check stock if this item matches our variation and location
            if ($location_term_id == $term_id && $cart_variation_id == $variation_id) {
                if (!is_stock_available($variation_id, $term_id, $request_quantity, $cart_item['quantity'])) {
                    wc_add_notice(__("We don't have enough stock to fulfill your request.", 'wcmlim'), 'error');
                    return false;
                }
                
                // We found and validated this variation+location in cart, so we can return
                return true;
            }
        }
    }
    
    // Check stock for new cart addition
    if (!is_stock_available($variation_id, $term_id, $request_quantity, 0)) {
        wc_add_notice(__("We don't have enough stock to fulfill your request", 'wcmlim'), 'error');
        return false;
    }
} 
// Handle main product (no variation)
else {
    $manage_stock_product = get_post_meta($product_id, '_manage_stock', true);
    if (!$manage_stock_product) {
        return true; // Stock not managed, allow adding to cart
    }
    
    // Check cart for matching product and location
    if (!$cart->is_empty()) {
        foreach ($cart->get_cart() as $cart_item) {
            if ($product_id == $cart_item['product_id']) {
                $location_term_id = $cart_item['select_location']['location_termId'];
                
                if ($location_term_id == $term_id) {
                    if (!is_stock_available($product_id, $term_id, $request_quantity, $cart_item['quantity'])) {
                        wc_add_notice(__("We don't have enough stock to fulfill your request.", 'wcmlim'), 'error');
                        return false;
                    }
                    
                    // We found and validated this product+location in cart, so we can return
                    return true;
                }
            }
        }
    }
    
    // Check stock for new cart addition
    if (!is_stock_available($product_id, $term_id, $request_quantity, 0)) {
        wc_add_notice(__("We don't have enough stock to fulfill your request", 'wcmlim'), 'error');
        return false;
    }
}

// If we reached here, stock is available
return true;
?>

