<?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 {
    $db->beginTransaction();
    
    // Find duplicates
    $stmt = $db->prepare("
        SELECT product_id, variant_id, COUNT(*) as count, GROUP_CONCAT(id) as ids
        FROM cart_items 
        WHERE user_id = :user_id 
        GROUP BY product_id, variant_id 
        HAVING COUNT(*) > 1
    ");
    $stmt->bindParam(':user_id', $userId);
    $stmt->execute();
    $duplicates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $cleanedUp = [];
    
    foreach ($duplicates as $duplicate) {
        $ids = explode(',', $duplicate['ids']);
        
        // Keep the first one, remove the rest
        $keepId = array_shift($ids);
        $removeIds = $ids;
        
        if (!empty($removeIds)) {
            $placeholders = str_repeat('?,', count($removeIds) - 1) . '?';
            $deleteStmt = $db->prepare("DELETE FROM cart_items WHERE id IN ($placeholders)");
            $deleteStmt->execute($removeIds);
            
            $cleanedUp[] = [
                'product_id' => $duplicate['product_id'],
                'variant_id' => $duplicate['variant_id'],
                'kept_id' => $keepId,
                'removed_ids' => $removeIds,
                'removed_count' => count($removeIds)
            ];
        }
    }
    
    $db->commit();
    
    // Get final count
    $finalStmt = $db->prepare("SELECT COUNT(*) as count FROM cart_items WHERE user_id = :user_id");
    $finalStmt->bindParam(':user_id', $userId);
    $finalStmt->execute();
    $finalCount = $finalStmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'user_id' => $userId,
        'duplicates_found' => count($duplicates),
        'cleaned_up' => $cleanedUp,
        'final_item_count' => $finalCount['count']
    ], JSON_PRETTY_PRINT);
    
} catch (Exception $e) {
    $db->rollback();
    echo json_encode(['error' => $e->getMessage()]);
}
?>