<?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 {
    echo "<h2>Cart Removal Test for User: $userId</h2>";
    
    // Get current cart items
    $stmt = $db->prepare("SELECT * FROM cart_items WHERE user_id = :user_id ORDER BY added_at DESC");
    $stmt->bindParam(':user_id', $userId);
    $stmt->execute();
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h3>Current Cart Items (" . count($items) . "):</h3>";
    echo "<pre>" . json_encode($items, JSON_PRETTY_PRINT) . "</pre>";
    
    if (count($items) > 0) {
        $itemToRemove = $items[0];
        echo "<h3>Testing removal of item: " . $itemToRemove['id'] . "</h3>";
        
        // Simulate the removal API call
        $removeStmt = $db->prepare("DELETE FROM cart_items WHERE id = :id");
        $removeStmt->bindParam(':id', $itemToRemove['id']);
        $removeStmt->execute();
        
        echo "<p>Rows affected: " . $removeStmt->rowCount() . "</p>";
        
        // Check if item still exists
        $checkStmt = $db->prepare("SELECT COUNT(*) as count FROM cart_items WHERE id = :id");
        $checkStmt->bindParam(':id', $itemToRemove['id']);
        $checkStmt->execute();
        $checkResult = $checkStmt->fetch(PDO::FETCH_ASSOC);
        
        echo "<p>Item still exists: " . ($checkResult['count'] > 0 ? 'YES' : 'NO') . "</p>";
        
        // Get remaining items
        $remainingStmt = $db->prepare("SELECT * FROM cart_items WHERE user_id = :user_id");
        $remainingStmt->bindParam(':user_id', $userId);
        $remainingStmt->execute();
        $remaining = $remainingStmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "<h3>Remaining Items (" . count($remaining) . "):</h3>";
        echo "<pre>" . json_encode($remaining, JSON_PRETTY_PRINT) . "</pre>";
    } else {
        echo "<p>No items to test removal</p>";
    }
    
} catch (Exception $e) {
    echo "<p>Error: " . $e->getMessage() . "</p>";
}
?>