<?php
$slCookie = getLocation('wcmlim_selected_location');
$cookie_termId = getLocation('wcmlim_selected_location_termid');


global $woocommerce; 
$reserr = '0';
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$variation_id = isset($_POST['variation_id']) && !empty($_POST['variation_id']) ? absint($_POST['variation_id']) : 0;
$product_location_termid = isset($_POST['product_location_termid']) ? $_POST['product_location_termid'] : $cookie_termId;
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);

error_log('WCMLIM Add to Cart - Product ID: ' . $product_id . ', Variation ID: ' . $variation_id);

// Simplify manage stock check
$manage_stock = get_post_meta($product_id, '_manage_stock', true);
if ($manage_stock == "true" || $manage_stock == "yes" || $manage_stock == "1") {
    update_post_meta($product_id, '_manage_stock', 'yes');
    $manage_stock = "yes";
}

// Early validation checks for location and stock management
if ($manage_stock == "yes" && empty($product_location_termid)) {
    echo '3';
    wp_die();
}

if ($manage_stock != "yes" && !empty($product_location_termid)) {
    echo '2';
    wp_die();
}

// Get stock at location
$__stock_at_location = get_post_meta($product_id, "wcmlim_stock_at_{$product_location_termid}", true);

$allow_backorder = get_post_meta($product_id, "wcmlim_allow_backorder_at_{$product_location_termid}", true);

$product_backorder = get_post_meta($product_id, '_backorders', true);

if ($manage_stock == "yes" && $__stock_at_location <= 0 && ($allow_backorder == 'No' || $allow_backorder == 'no') ) {
    echo '2';
    wp_die();
}

// Combine cart checks - both calculate cart quantity and check location consistency
$cart_qty = 0;
$isClearCart = get_option('wcmlim_clear_cart');
$ispurchaselocation = get_option('wcmlim_clear_cart');
$cart_has_items = false;
$cart_location_conflicts = false;
$unavailable_products = array();

if ($manage_stock == "yes" || ( $isClearCart == 'on' && $ispurchaselocation != 'on') || ( $isClearCart == 'on' && $ispurchaselocation == 'on') ) {
    foreach ($woocommerce->cart->get_cart() as $item => $items) {
        $product_ids = $items['variation_id'] ? $items['variation_id'] : $items['product_id'];
        $cart_has_items = true;
        
        // Calculate quantity for current product
        if ($product_ids == $product_id) {
            $cart_qty += $items['quantity'];
        }
        
        // Check location consistency if clear cart is enabled
        if (( $isClearCart == 'on' && $ispurchaselocation != 'on')) {
            $item_manage_stock = get_post_meta($product_ids, '_manage_stock', true);
            
            if ($item_manage_stock == 'yes') {
                $cart_location_id = isset($items['select_location']['location_termId']) ? $items['select_location']['location_termId'] : 0;
                
                if ($cart_location_id != $product_location_termid) {
                    $reserr = '1';
                    echo $reserr;
                    wp_die();
                }
            }
        }
        
        // NEW: Enhanced location handling for purchase_one_location feature
        if (( $isClearCart == 'on' && $ispurchaselocation == 'on')) {
            $item_manage_stock = get_post_meta($product_ids, '_manage_stock', true);
            
            if ($item_manage_stock == 'yes') {
                $cart_location_id = isset($items['select_location']['location_termId']) ? $items['select_location']['location_termId'] : 0;
                
                if ($cart_location_id != $product_location_termid) {
                    $cart_location_conflicts = true;
                    
                    // Check if this product is available at the new location
                    $stock_at_new_location = get_post_meta($product_ids, "wcmlim_stock_at_{$product_location_termid}", true);
                    if ($stock_at_new_location <= 0) {
                        $unavailable_products[] = array(
                            'id' => $product_ids,
                            'name' => get_the_title($product_ids),
                            'quantity' => $items['quantity']
                        );
                    }
                }
            }
        }
    }
}

// NEW: Handle purchase_one_location conflicts
if ($cart_location_conflicts && $isClearCart == 'on' && $ispurchaselocation == 'on') {
    if (!empty($unavailable_products)) {
        // Some products are not available at new location - offer cart clear
        $response_data = array(
            'status' => 'unavailable_products',
            'unavailable_products' => $unavailable_products,
            'new_location_name' => get_term($product_location_termid)->name
        );
        echo json_encode($response_data);
        wp_die();
    } else {
        // All products are available at new location - offer location change
        $current_location_name = '';
        foreach ($woocommerce->cart->get_cart() as $item => $items) {
            if (isset($items['select_location']['location_termId'])) {
                $current_location_name = get_term($items['select_location']['location_termId'])->name;
                break;
            }
        }
        
        $response_data = array(
            'status' => 'location_change',
            'current_location' => $current_location_name,
            'new_location_name' => get_term($product_location_termid)->name,
            'new_location_id' => $product_location_termid
        );
        echo json_encode($response_data);
        wp_die();
    }
}

// Add current quantity to cart quantity total
$cart_qty += $quantity;

// Check backorder status
 
if (($allow_backorder == 'No' || $allow_backorder == 'no') && $manage_stock == "yes") {
    if ($cart_qty > $__stock_at_location) {
        echo '4';
        wp_die();
    }
}

// Product data
$product_status = get_post_status($product_id);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_price = isset($_POST['product_price']) ? $_POST['product_price'] : "";
$_isrspon = get_option("wcmlim_enable_price");

// Location data with fallback handling
$product_location = isset($_POST['product_location']) ? $_POST['product_location'] : "";
$product_location_key = isset($_POST['product_location_key']) ? $_POST['product_location_key'] : "";
$product_location_qty = isset($_POST['product_location_qty']) ? $_POST['product_location_qty'] : "";
$product_location_regular_price = isset($_POST['product_location_regular_price']) ? $_POST['product_location_regular_price'] : "";
$product_location_sale_price = isset($_POST['product_location_sale_price']) ? $_POST['product_location_sale_price'] : "undefined";

// Enhanced fallback for missing location data (common in single product pages)
if (empty($product_location_key) && !empty($product_location_termid)) {
    // Try to get location key from term ID
    $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    foreach($locations as $key => $term) {
        if ($term->term_id == $product_location_termid) {
            $product_location_key = $key;
            if (empty($product_location)) {
                $product_location = $term->name;
            }
            break;
        }
    }
}

// Get location-specific data if missing
if (!empty($product_location_termid) && (empty($product_location_qty) || empty($product_location_regular_price))) {
    $stock_at_location = get_post_meta($product_id, "wcmlim_stock_at_{$product_location_termid}", true);
    $regular_price_at_location = get_post_meta($product_id, "wcmlim_regular_price_at_{$product_location_termid}", true);
    $sale_price_at_location = get_post_meta($product_id, "wcmlim_sale_price_at_{$product_location_termid}", true);
    
    if (empty($product_location_qty)) {
        $product_location_qty = $stock_at_location;
    }
    if (empty($product_location_regular_price)) {
        $product_location_regular_price = $regular_price_at_location;
    }
    if (empty($product_location_sale_price) || $product_location_sale_price === 'undefined') {
        $product_location_sale_price = $sale_price_at_location;
    }
}

// Enhanced debug logging for single product page values
error_log('WCMLIM Add to Cart - POST data: ' . print_r($_POST, true));
error_log('WCMLIM Add to Cart - Location data extracted: location=' . $product_location . 
    ', key=' . $product_location_key . 
    ', qty=' . $product_location_qty . 
    ', termid=' . $product_location_termid . 
    ', regular_price=' . $product_location_regular_price . 
    ', sale_price=' . $product_location_sale_price);

// Specific location check
$_location_termid = getLocation('wcmlim_selected_location_termid');
$allow_specific_location = get_post_meta($product_id, 'wcmlim_allow_specific_location_at_' . $_location_termid, true);

if ($allow_specific_location != 'Yes' && get_option('wcmlim_enable_specific_location') == "on") {
    echo '2';
    wp_die();
}

if ($passed_validation && 'publish' === $product_status) {
    // Prepare location data
    $_location_data = array();
    $_location_data['select_location']['location_name'] = $product_location;
    $_location_data['select_location']['location_key'] = (int)$product_location_key;
    $_location_data['select_location']['location_qty'] = (int)$product_location_qty;
    $_location_data['select_location']['location_termId'] = (int)$product_location_termid;
    
    if ($_isrspon == "on") {
        if (!empty($product_location_regular_price) && empty($product_location_sale_price)) {
            $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($product_location_regular_price)));
        } elseif (!empty($product_location_sale_price)) {
            $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($product_location_sale_price)));
        } else {
            $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($product_price)));
        }
    }
    
    // Add to cart with variation support
    $cart_item_key = WC()->cart->add_to_cart($product_id, $quantity, $variation_id, array(), $_location_data);
    
    if ($cart_item_key) {
        error_log('WCMLIM Add to Cart - Successfully added to cart. Cart item key: ' . $cart_item_key);
        WC_AJAX::get_refreshed_fragments();
    } else {
        error_log('WCMLIM Add to Cart - Failed to add product to cart');
    }
}

wp_die();
