<?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;
}

try {
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['item_id'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Item ID is required']);
        exit;
    }

    $itemId = $data['item_id'];

    // Debug: Log the item ID being removed
    error_log("Attempting to remove cart item with ID: " . $itemId);

    // First check if item exists and get full details
    $checkStmt = $db->prepare("SELECT id, user_id, product_id, variant_id, quantity FROM cart_items WHERE id = :id");
    $checkStmt->bindParam(':id', $itemId, PDO::PARAM_STR);
    $checkStmt->execute();
    $existingItem = $checkStmt->fetch(PDO::FETCH_ASSOC);

    if (!$existingItem) {
        error_log("Cart item not found in database: " . $itemId);
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Cart item not found',
            'debug' => ['item_id' => $itemId]
        ]);
        exit;
    }

    error_log("Found cart item: " . json_encode($existingItem));

    // Check for duplicates of the same product for this user
    $duplicateStmt = $db->prepare("
        SELECT id, quantity FROM cart_items 
        WHERE user_id = :user_id AND product_id = :product_id 
        AND (variant_id = :variant_id OR (variant_id IS NULL AND :variant_id IS NULL))
    ");
    $duplicateStmt->bindParam(':user_id', $existingItem['user_id'], PDO::PARAM_STR);
    $duplicateStmt->bindParam(':product_id', $existingItem['product_id'], PDO::PARAM_STR);
    $duplicateStmt->bindParam(':variant_id', $existingItem['variant_id'], PDO::PARAM_STR);
    $duplicateStmt->execute();
    $duplicates = $duplicateStmt->fetchAll(PDO::FETCH_ASSOC);

    error_log("Found " . count($duplicates) . " items for this product: " . json_encode($duplicates));

    // Remove ALL instances of this product for this user (same logic as order placement)
    $stmt = $db->prepare("
        DELETE FROM cart_items 
        WHERE user_id = :user_id AND product_id = :product_id 
        AND (variant_id = :variant_id OR (variant_id IS NULL AND :variant_id IS NULL))
    ");
    $stmt->bindParam(':user_id', $existingItem['user_id'], PDO::PARAM_STR);
    $stmt->bindParam(':product_id', $existingItem['product_id'], PDO::PARAM_STR);
    $stmt->bindParam(':variant_id', $existingItem['variant_id'], PDO::PARAM_STR);
    $stmt->execute();

    $removedCount = $stmt->rowCount();
    
    if ($removedCount > 0) {
        error_log("Successfully removed $removedCount cart item(s) for product: " . $existingItem['product_id']);
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Item removed from cart successfully',
            'removed_count' => $removedCount
        ]);
    } else {
        error_log("Failed to remove cart item: " . $itemId);
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Failed to remove item from cart'
        ]);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal Server Error: ' . $e->getMessage()
    ]);
}
?>