<?php
require('connection.inc.php');
require('security.php');
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'login_required']);
    exit;
}

$user_id = $_SESSION['user_id'];
$product_id = intval($_POST['product_id'] ?? 0);

// Check if product already in wishlist
$stmt = $conn->prepare("SELECT id FROM wishlist WHERE user_id = ? AND product_id = ?");
$stmt->bind_param("ii", $user_id, $product_id);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // Exists: Remove from wishlist
    $stmt->bind_result($wishlist_id);
    $stmt->fetch();
    $stmt->close();

    $del_stmt = $conn->prepare("DELETE FROM wishlist WHERE id = ?");
    $del_stmt->bind_param("i", $wishlist_id);
    $del_stmt->execute();

    echo json_encode(['status' => 'removed']);
} else {
    // Not in wishlist: Add
    $stmt->close();

    $add_stmt = $conn->prepare("INSERT INTO wishlist (user_id, product_id, created_at) VALUES (?, ?, NOW())");
    $add_stmt->bind_param("ii", $user_id, $product_id);
    $add_stmt->execute();

    echo json_encode(['status' => 'added']);
}
?>
