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

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

$method = $_SERVER['REQUEST_METHOD'];

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

// FIX: Make parameter keys lowercase to avoid case-sensitivity issues
$queryParams = array_change_key_case($_GET, CASE_LOWER);

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

$userId = $queryParams['userid'];

try {
    // The rest of the logic remains the same
    $query = "SELECT wi.id, wi.product_id, wi.variant_id, wi.added_at,
                    p.name, p.base_price, p.brand, p.stock, p.description,
                    pi.url as image_url
             FROM wishlist_items wi
             JOIN wishlists w ON wi.wishlist_id = w.id
             JOIN products p ON wi.product_id = p.id
             LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.position = 0
             WHERE w.user_id = ? 
             ORDER BY wi.added_at DESC";

    $stmt = $db->prepare($query);
    $stmt->bindParam(1, $userId);
    $stmt->execute();

    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    http_response_code(200);
    echo json_encode(['success' => true, 'items' => $items]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to fetch wishlist: ' . $e->getMessage()]);
}