<?php
global $product;

// Initially get set location with wcmlim_selected_location_termid
$setLocation = getLocation('wcmlim_selected_location_termid');

// Check if product is simple or not
if ($product->get_type() == 'simple') {
    
    // Get linked locations for this product
    $linked_locations = wp_get_object_terms($product->get_id(), 'locations', array('fields' => 'ids'));
    
    // If setLocation is set, check if it's in linked locations array
    if (isset($setLocation) && !empty($setLocation)) {
        
        // If setLocation is not in linked location array then show not available status
        if (!in_array($setLocation, $linked_locations)) {
            echo '<span class="locsoldout">' . __('Not Available', 'woocommerce') . '</span>';
        } else {
            // Check stock for that location in meta
            $locationQty = get_post_meta($product->get_id(), "wcmlim_stock_at_{$setLocation}", true);
            
            // Check if backorders are enabled for the product and for this specific location
            $product_backorders = $product->get_backorders();
            $location_backorders = get_post_meta($product->get_id(), "wcmlim_allow_backorder_at_{$setLocation}", true);
            
            // If both product and location backorders are active, don't show out of stock
            // If either one is not active, check stock and show out of stock if stock <= 0

            if (!($product_backorders !== 'no' && $location_backorders === 'Yes')) {
                // Either product backorders or location backorders (or both) are not active
                if (empty($locationQty) || $locationQty <= 0) {
                    echo '<span class="locsoldout">' . __('Out of stock', 'woocommerce') . '</span>';
                }
            }
            // If both backorders are active, do nothing (let WooCommerce handle default display)
        }
    }
}