<?php

// Check if stock is managed
$manage_stock = get_post_meta($variation_id > 0 ? $variation_id : $product_id, '_manage_stock', true);
if ($manage_stock == "no") {
    return $cart_item_data;
}

// Get the product
$product = wc_get_product($product_id);
$product_to_check = $variation_id > 0 ? wc_get_product($variation_id) : $product;

// Get basic price information
$productPrice = $product_to_check->get_price();
$sProductPrice = wc_price($productPrice);

// Get locations
$ExL = get_option("wcmlim_exclude_locations_from_frontend");
if (!empty($ExL)) {
    $stores = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'exclude' => $ExL));
} else {
    $stores = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
}

// Configuration options
$_isrspon = get_option("wcmlim_enable_price");
$check_ajax_add_to_cart = get_option('woocommerce_enable_ajax_add_to_cart');

// Helper function to find store by key or term ID
$find_store = function($key = null, $term_id = null) use ($stores) {
    if ($key !== null) {
        foreach ($stores as $index => $store) {
            if ($index == $key) {
                return ['store' => $store, 'key' => $index];
            }
        }
    } elseif ($term_id !== null) {
        foreach ($stores as $index => $store) {
            if ($store->term_id == $term_id) {
                return ['store' => $store, 'key' => $index];
            }
        }
    }
    return null;
};

// Helper function to get location price data
$get_location_price = function($store_term_id) use ($_isrspon, $product_to_check, $sProductPrice) {
    if ($_isrspon != "on") {
        return null;
    }
    
    $location_regular_price = get_post_meta($product_to_check->get_id(), "wcmlim_regular_price_at_{$store_term_id}", true);
    $location_sale_price = get_post_meta($product_to_check->get_id(), "wcmlim_sale_price_at_{$store_term_id}", true);
    
    if (!empty($location_sale_price)) {
        return $location_sale_price;
    } elseif (!empty($location_regular_price)) {
        return $location_regular_price;
    }
    
    return strip_tags(html_entity_decode($sProductPrice));
};

// Initialize location data
$location_data = array(
    'location_name' => '',
    'location_key' => '',
    'location_termId' => '',
    'location_qty' => ''
);

// Handle composite products separately
if ($product->is_type('composite')) {
    if (isset($cart_item_data['select_location'])) {
        // Get cookie data
        $selected_store = getLocation('wcmlim_selected_location');
        $cookie_termId = getLocation('wcmlim_selected_location_termid');
        
        $store_info = null;
        if (!empty($selected_store)) {
            $store_info = $find_store($selected_store, null);
        } elseif (!empty($cookie_termId)) {
            $store_info = $find_store(null, $cookie_termId);
        }
        
        if ($store_info) {
            $cart_item_data['select_location'] = array(
                'location_name'   => $store_info['store']->name,
                'location_key'    => $store_info['key'],
                'location_termId' => $store_info['store']->term_id
            );
        }
    }
    
    return $cart_item_data;
}

// For all other product types, collect location data from all possible sources
$store_info = null;
$location_cart_price = null;

// 1. Check for POST data first (highest priority)
if (isset($_POST['select_location'])) {
    $location_key = $_POST['select_location'];
    $store_info = $find_store($location_key, null);
    
    if ($store_info) {
        $location_data['location_name'] = $store_info['store']->name;
        $location_data['location_key'] = $store_info['key'];
        $location_data['location_termId'] = $store_info['store']->term_id;
        $location_data['location_qty'] = isset($_POST['location_qty']) ? $_POST['location_qty'] : 
            get_post_meta($product_to_check->get_id(), "wcmlim_stock_at_{$store_info['store']->term_id}", true);
        
        // Save the selected location in cookie
        $this->set_location_cookie($store_info['key']);
        
        // Handle prices if enabled
        if ($_isrspon == "on") {
            if (!empty($_POST['location_regular_price']) && $_POST['location_sale_price'] == 'undefined') {
                $location_data['location_cart_price'] = strip_tags($_POST['location_regular_price']);
            } elseif (isset($_POST['location_sale_price']) && $_POST['location_sale_price'] !== 'undefined') {
                $location_data['location_cart_price'] = strip_tags($_POST['location_sale_price']);
            } else {
                $location_data['location_cart_price'] = strip_tags(html_entity_decode($sProductPrice));
            }
        }
    }
}
// 2. If no POST data, check for data in cookies (second priority)
else {
    $selected_store = getLocation('wcmlim_selected_location');
    $cookie_termId = getLocation('wcmlim_selected_location_termid');
    
    // If we have no location information at all, return original cart data
    if (empty($selected_store) && empty($cookie_termId)) {
        return $cart_item_data;
    }
    
    if (!empty($selected_store)) {
        $store_info = $find_store($selected_store, null);
    } elseif (!empty($cookie_termId)) {
        $store_info = $find_store(null, $cookie_termId);
        // Save the selected location in cookie to maintain consistency
        if ($store_info) {
            $this->set_location_cookie($store_info['key']);
        }
    }
    
    if ($store_info) {
        $location_data['location_name'] = $store_info['store']->name;
        $location_data['location_key'] = $store_info['key'];
        $location_data['location_termId'] = $store_info['store']->term_id;
        $location_data['location_qty'] = get_post_meta($product_to_check->get_id(), "wcmlim_stock_at_{$store_info['store']->term_id}", true);
        
        // Get prices if enabled
        if ($_isrspon == "on") {
            $location_data['location_cart_price'] = $get_location_price($store_info['store']->term_id);
        }
    }
}

// 3. If we have valid location data, add it to the cart item
if (!empty($location_data['location_name']) && !empty($location_data['location_termId'])) {
    $cart_item_data['select_location'] = $location_data;
}

return $cart_item_data;


