<?php
require_once __DIR__ . '/../functions.php';
requireAuth();
header('Content-Type: application/json');

$db = db();
$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $productId = (int)($_POST['product_id'] ?? 0);
    $wishlistId = (int)($_POST['wishlist_id'] ?? 0);
    
    if ($wishlistId) {
        $db->prepare("DELETE FROM wishlists WHERE id = ? AND user_id = ?")->execute([$wishlistId, $userId]);
        echo json_encode(['success' => true, 'action' => 'removed']);
    } elseif ($productId) {
        $existing = $db->prepare("SELECT id FROM wishlists WHERE user_id = ? AND product_id = ?");
        $existing->execute([$userId, $productId]);
        $existingItem = $existing->fetch();
        
        if ($existingItem) {
            $db->prepare("DELETE FROM wishlists WHERE id = ?")->execute([$existingItem['id']]);
            echo json_encode(['success' => true, 'action' => 'removed']);
        } else {
            $db->prepare("INSERT INTO wishlists (user_id, product_id) VALUES (?, ?)")->execute([$userId, $productId]);
            echo json_encode(['success' => true, 'action' => 'added']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
    }
}
