<?php
/**
 * AJAX handler for clearing cart and adding product
 * Used when products in cart are unavailable at the new location
 */

// Clear the entire cart first
WC()->cart->empty_cart();

// Get product data from POST
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$product_location_termid = isset($_POST['product_location_termid']) ? $_POST['product_location_termid'] : "";

// Prepare location data
$_location_data = array();
$_location_data['select_location']['location_name'] = isset($_POST['product_location']) ? $_POST['product_location'] : "";
$_location_data['select_location']['location_key'] = isset($_POST['product_location_key']) ? (int)$_POST['product_location_key'] : 0;
$_location_data['select_location']['location_qty'] = isset($_POST['product_location_qty']) ? (int)$_POST['product_location_qty'] : 0;
$_location_data['select_location']['location_termId'] = (int)$product_location_termid;

// Handle pricing if enabled
$_isrspon = get_option("wcmlim_enable_price");
if ($_isrspon == "on") {
    $regular_price = isset($_POST['product_location_regular_price']) ? $_POST['product_location_regular_price'] : "";
    $sale_price = isset($_POST['product_location_sale_price']) ? $_POST['product_location_sale_price'] : "";
    
    if (!empty($regular_price) && (empty($sale_price) || $sale_price === 'undefined')) {
        $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($regular_price)));
    } elseif (!empty($sale_price) && $sale_price !== 'undefined') {
        $_location_data['select_location']['location_cart_price'] = strip_tags(html_entity_decode(wc_price($sale_price)));
    }
}

// Validate product and add to cart
$product_status = get_post_status($product_id);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);

if ($passed_validation && 'publish' === $product_status) {
    $cart_item_key = WC()->cart->add_to_cart($product_id, $quantity, 0, array(), $_location_data);
    
    if ($cart_item_key) {
        echo 'success';
    } else {
        echo 'error';
    }
} else {
    echo 'error';
}

wp_die();
?>