<?php
require_once '../config/cors.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'DELETE') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed'
    ]);
    exit();
}

// Get user ID from query parameters (same as other wishlist endpoints)
$queryParams = array_change_key_case($_GET, CASE_LOWER);

if (!isset($queryParams['userid'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'User ID is required']);
    exit();
}

$userId = $queryParams['userid'];

try {
    // Clear all wishlist items for the user
    $deleteQuery = "DELETE wi FROM wishlist_items wi
                    JOIN wishlists w ON wi.wishlist_id = w.id
                    WHERE w.user_id = ?";
    $stmt = $db->prepare($deleteQuery);
    $stmt->bindParam(1, $userId);

    if ($stmt->execute()) {
        $rowCount = $stmt->rowCount();
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => $rowCount > 0 ? "Wishlist cleared successfully. {$rowCount} item(s) were removed." : 'Wishlist was already empty.'
        ]);
    } else {
        throw new Exception('Failed to clear wishlist');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error: ' . $e->getMessage()
    ]);
}