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

$queryParams = array_change_key_case($_GET, CASE_LOWER);

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

if (!isset($queryParams['id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Item ID is required']);
    exit();
}

$userId = trim($queryParams['userid']);
$itemId = trim($queryParams['id']);

// Log the received parameters for debugging
error_log("Remove request received - User ID: '$userId', Item ID: '$itemId'");

try {
    // First, let's check what wishlist items exist for this user
    $userItemsQuery = "SELECT wi.id, wi.product_id, wi.wishlist_id, w.user_id 
                       FROM wishlist_items wi
                       JOIN wishlists w ON wi.wishlist_id = w.id
                       WHERE w.user_id = ?";
    $userItemsStmt = $db->prepare($userItemsQuery);
    $userItemsStmt->bindParam(1, $userId);
    $userItemsStmt->execute();
    $userItems = $userItemsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    error_log("User $userId has " . count($userItems) . " wishlist items: " . json_encode($userItems));
    
    // Now check if the specific item exists
    $checkQuery = "SELECT wi.id, wi.wishlist_id, w.user_id 
                   FROM wishlist_items wi
                   JOIN wishlists w ON wi.wishlist_id = w.id
                   WHERE wi.id = ?";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bindParam(1, $itemId);
    $checkStmt->execute();
    
    if ($checkStmt->rowCount() === 0) {
        error_log("Wishlist item not found with ID: $itemId");
        http_response_code(404);
        echo json_encode([
            'success' => false, 
            'message' => 'Wishlist item not found',
            'debug' => [
                'requested_item_id' => $itemId,
                'user_id' => $userId,
                'available_items' => array_column($userItems, 'id')
            ]
        ]);
        exit();
    }
    
    $itemData = $checkStmt->fetch(PDO::FETCH_ASSOC);
    error_log("Found item data: " . json_encode($itemData));
    
    // Check if user IDs match (handle both string and numeric comparison)
    if (strval($itemData['user_id']) !== strval($userId)) {
        error_log("User ID mismatch - Item belongs to: '{$itemData['user_id']}', Request from: '$userId'");
        http_response_code(403);
        echo json_encode([
            'success' => false, 
            'message' => 'Item does not belong to the user',
            'debug' => [
                'item_user_id' => $itemData['user_id'],
                'request_user_id' => $userId
            ]
        ]);
        exit();
    }

    // Proceed with deletion
    $deleteQuery = "DELETE FROM wishlist_items WHERE id = ?";
    $stmt = $db->prepare($deleteQuery);
    $stmt->bindParam(1, $itemId);

    if ($stmt->execute()) {
        if ($stmt->rowCount() > 0) {
            error_log("Successfully removed item $itemId for user $userId");
            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Item removed from wishlist']);
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'No rows affected during deletion']);
        }
    } else {
        throw new Exception('Failed to execute delete query');
    }
} catch (Exception $e) {
    error_log("Remove error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error: ' . $e->getMessage()]);
}