<?php
/**
 * API endpoint to clear all items from a user's cart.
 * Method: DELETE
 * URL Param: ?user_id=<user_id> OR ?userId=<userId>
 */
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/cors.php';
require_once '../config/database.php';

function sendJsonResponse($statusCode, $success, $message) {
    http_response_code($statusCode);
    echo json_encode(['success' => $success, 'message' => $message]);
    exit;
}

try {
    if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'DELETE') {
        header('Allow: DELETE');
        sendJsonResponse(405, false, 'Method Not Allowed. Please use DELETE.');
    }

    // Check for both 'userId' and 'user_id' from the URL
    $userId = $_GET['userId'] ?? $_GET['user_id'] ?? null;
    
    if (!$userId) {
        sendJsonResponse(400, false, 'A User ID is required.');
    }

    $database = new Database();
    // FIX: Changed 'a->getConnection()' to '$database->getConnection()'
    $db = $database->getConnection(); 

    // Use prepared statements with PARAM_STR for the UUID
    $stmt = $db->prepare("DELETE FROM cart_items WHERE user_id = :user_id");
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $stmt->execute();

    $rowCount = $stmt->rowCount();
    if ($rowCount > 0) {
        sendJsonResponse(200, true, "Cart cleared successfully. {$rowCount} item(s) were removed.");
    } else {
        sendJsonResponse(200, true, 'Cart was already empty for this user.');
    }

} catch (PDOException $e) {
    sendJsonResponse(500, false, 'Database Error: ' . $e->getMessage());
} catch (Exception $e) {
    sendJsonResponse(500, false, 'Internal Server Error: ' . $e->getMessage());
}
?>