<?php
global $woocommerce;

$new_location_id = isset($_POST['new_location_id']) ? intval($_POST['new_location_id']) : 0;
$product_to_add = isset($_POST['product_data']) ? $_POST['product_data'] : array();
$remove_unavailable = isset($_POST['remove_unavailable']) ? $_POST['remove_unavailable'] : false;
$unavailable_products = isset($_POST['unavailable_products']) ? json_decode(stripslashes($_POST['unavailable_products']), true) : array();

error_log('WCMLIM Update Cart Location - Parameters: location_id=' . $new_location_id . 
    ', remove_unavailable=' . ($remove_unavailable ? 'true' : 'false') . 
    ', unavailable_products=' . print_r($unavailable_products, true));


if (!$new_location_id) {
    error_log('Invalid location ID provided');
    echo json_encode(array(
        'status' => 'error', 
        'message' => 'Invalid location ID'
    ));
    wp_die();
}

// Get the new location name
$new_location = get_term($new_location_id);
if (!$new_location || is_wp_error($new_location)) {
    error_log('Invalid location term: ' . print_r($new_location, true));
    echo json_encode(array(
        'status' => 'error', 
        'message' => 'Invalid location'
    ));
    wp_die();
}

error_log('New location found: ' . $new_location->name);

error_log('New location found: ' . $new_location->name);

// Update all cart items to the new location or remove unavailable ones
$cart_updated = false;
$removed_products = array();

// Create a list of unavailable product IDs for easy lookup
$unavailable_product_ids = array();
if (!empty($unavailable_products)) {
    foreach ($unavailable_products as $unavailable_product) {
        $unavailable_product_ids[] = $unavailable_product['id'];
    }
}

foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
    $product_id = $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'];
    $manage_stock = get_post_meta($product_id, '_manage_stock', true);
    
    error_log("Processing cart item - Product ID: $product_id, Manage Stock: $manage_stock");
    
    if ($manage_stock == 'yes') {
        // Check if this product should be removed (unavailable at new location)
        if ($remove_unavailable && in_array($product_id, $unavailable_product_ids)) {
            error_log("Removing unavailable product: $product_id");
            $woocommerce->cart->remove_cart_item($cart_item_key);
            $removed_products[] = get_the_title($product_id);
            $cart_updated = true;
            continue;
        }
        
        // Update the location data for this cart item
        $cart_item['select_location']['location_termId'] = $new_location_id;
        $cart_item['select_location']['location_name'] = $new_location->name;
        
        // Get stock quantity at new location
        $stock_at_new_location = get_post_meta($product_id, "wcmlim_stock_at_{$new_location_id}", true);
        $cart_item['select_location']['location_qty'] = intval($stock_at_new_location);
        
        error_log("Updated location for product $product_id - Stock at new location: $stock_at_new_location");
        
        // Update price if location-based pricing is enabled
        $enable_price = get_option("wcmlim_enable_price");
        if ($enable_price == "on") {
            $location_regular_price = get_post_meta($product_id, "wcmlim_regular_price_at_{$new_location_id}", true);
            $location_sale_price = get_post_meta($product_id, "wcmlim_sale_price_at_{$new_location_id}", true);
            
            if (!empty($location_sale_price)) {
                $cart_item['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($location_sale_price)));
            } elseif (!empty($location_regular_price)) {
                $cart_item['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($location_regular_price)));
            }
            
            error_log("Updated pricing for product $product_id");
        }
        
        // Update the cart item
        $woocommerce->cart->cart_contents[$cart_item_key] = $cart_item;
        $cart_updated = true;
    }
}

// Set the cart as updated
$woocommerce->cart->set_session();

// Now add the new product if provided
if (!empty($product_to_add)) {
    $product_id = intval($product_to_add['product_id']);
    $quantity = intval($product_to_add['quantity']);
    
    
    // Prepare location data for the new product
    $_location_data = array();
    $_location_data['select_location']['location_name'] = $new_location->name;
    $_location_data['select_location']['location_key'] = 0; // This might need to be set based on your requirements
    $_location_data['select_location']['location_qty'] = get_post_meta($product_id, "wcmlim_stock_at_{$new_location_id}", true);
    $_location_data['select_location']['location_termId'] = $new_location_id;
    
    // Set price data if location-based pricing is enabled
    $enable_price = get_option("wcmlim_enable_price");
    if ($enable_price == "on") {
        $location_regular_price = get_post_meta($product_id, "wcmlim_regular_price_at_{$new_location_id}", true);
        $location_sale_price = get_post_meta($product_id, "wcmlim_sale_price_at_{$new_location_id}", true);
        
        if (!empty($location_sale_price)) {
            $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($location_sale_price)));
        } elseif (!empty($location_regular_price)) {
            $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($location_regular_price)));
        } else {
            // Fallback to regular product price
            $product = wc_get_product($product_id);
            $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($product->get_price())));
        }
    }
    
    // Add the new product to cart
    $add_result = WC()->cart->add_to_cart($product_id, $quantity, 0, array(), $_location_data);

}

if ($cart_updated) {
    $woocommerce->cart->set_session();
    
    $response = array(
        'status' => 'success',
        'message' => 'Cart updated successfully',
        'new_location' => $new_location->name,
        'cart_count' => $woocommerce->cart->get_cart_contents_count()
    );
    
    // Add information about removed products if any
    if (!empty($removed_products)) {
        $response['removed_products'] = $removed_products;
        $response['removed_count'] = count($removed_products);
        $response['message'] = sprintf(
            '%d product(s) were removed from your cart as they are not available at the selected location.',
            count($removed_products)
        );
    }
    
    error_log("Cart location update successful - Response: " . json_encode($response));
    echo json_encode($response);
} else {
    error_log("No cart updates needed");
    echo json_encode(array(
        'status' => 'success',
        'message' => 'No cart updates needed',
        'new_location' => $new_location->name,
        'cart_count' => $woocommerce->cart->get_cart_contents_count()
    ));
}

wp_die();