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

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

$userId = $_GET['user_id'] ?? null;

if (!$userId) {
    echo json_encode(['error' => 'User ID required']);
    exit;
}

try {
    // Get all cart items for this user with detailed info
    $stmt = $db->prepare("
        SELECT ci.*, p.name as product_name 
        FROM cart_items ci 
        LEFT JOIN products p ON ci.product_id = p.id 
        WHERE ci.user_id = :user_id 
        ORDER BY ci.added_at DESC
    ");
    $stmt->bindParam(':user_id', $userId);
    $stmt->execute();
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Check for duplicates
    $productCounts = [];
    foreach ($items as $item) {
        $key = $item['product_id'] . '_' . ($item['variant_id'] ?? 'null');
        if (!isset($productCounts[$key])) {
            $productCounts[$key] = [];
        }
        $productCounts[$key][] = $item;
    }
    
    $duplicates = [];
    foreach ($productCounts as $key => $itemGroup) {
        if (count($itemGroup) > 1) {
            $duplicates[$key] = $itemGroup;
        }
    }
    
    echo json_encode([
        'user_id' => $userId,
        'total_items' => count($items),
        'items' => $items,
        'duplicates' => $duplicates,
        'has_duplicates' => !empty($duplicates)
    ], JSON_PRETTY_PRINT);
    
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>