<?php
// update-cart-ajax.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';

header('Content-Type: application/json');

// Enable error logging for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Log the request
error_log("=== update-cart-ajax.php called ===");
error_log("POST data: " . print_r($_POST, true));

// Get the key and quantity
$key = $_POST['key'] ?? '';
$qty = intval($_POST['qty'] ?? 0);

// Validate
if (empty($key)) {
    error_log("Error: Empty key");
    echo json_encode(['success' => false, 'message' => 'Invalid cart item']);
    exit;
}

if (!isset($_SESSION['cart'])) {
    error_log("Error: Cart session not found");
    echo json_encode(['success' => false, 'message' => 'Cart is empty']);
    exit;
}

if (!isset($_SESSION['cart'][$key])) {
    error_log("Error: Item not found - key: " . $key);
    error_log("Available keys: " . print_r(array_keys($_SESSION['cart']), true));
    echo json_encode(['success' => false, 'message' => 'Item not found in cart']);
    exit;
}

// Update the cart
try {
    if ($qty <= 0) {
        unset($_SESSION['cart'][$key]);
        error_log("Removed item from cart");
    } else {
        $_SESSION['cart'][$key]['quantity'] = $qty;
        error_log("Updated quantity to: " . $qty);
    }
    
    // Calculate cart count
    $cart_count = 0;
    foreach ($_SESSION['cart'] as $item) {
        $cart_count += $item['quantity'];
    }
    
    echo json_encode([
        'success' => true,
        'cart_count' => $cart_count,
        'cart_total' => getCartTotal()
    ]);
    
} catch (Exception $e) {
    error_log("Exception: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>