<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401); // Unauthorized
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit();
}

try {
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 0;
    
    if ($product_id <= 0 || $quantity < 0) {
        throw new Exception('Invalid product ID or quantity');
    }
    
    // For quantity updates (not removal), verify the item exists in the user's cart
    if ($quantity > 0) {
        $stmt = $pdo->prepare("SELECT id FROM cart WHERE user_id = ? AND product_id = ?");
        $stmt->execute([$_SESSION['user_id'], $product_id]);
        $cart_item = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$cart_item) {
            throw new Exception('Item not found in your cart');
        }
    }
    
    // Update cart item in database
    if ($quantity == 0) {
        // Remove item from cart
        removeCartItem($pdo, $_SESSION['user_id'], $product_id);
    } else {
        // Update item quantity
        updateCartItemQuantity($pdo, $_SESSION['user_id'], $product_id, $quantity);
    }
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Cart updated successfully',
        'product_id' => $product_id,
        'quantity' => $quantity
    ]);
    
} catch (Exception $e) {
    error_log("Cart update error: " . $e->getMessage());
    http_response_code(500); // Internal Server Error
    echo json_encode(['success' => false, 'message' => 'Error updating cart: ' . $e->getMessage()]);
}

exit();
?>