<?php
header('Content-Type: application/json');
session_start();
require_once '../includes/db.php';

$response = ['success' => false, 'loggedIn' => false, 'action' => ''];

if (!isset($_SESSION['user_id'])) {
    echo json_encode($response);
    exit();
}
$response['loggedIn'] = true;
$user_id = $_SESSION['user_id'];

$input = json_decode(file_get_contents('php://input'), true);
$item_id = filter_var($input['item_id'] ?? 0, FILTER_VALIDATE_INT);
$item_type = $input['item_type'] ?? '';

if (!$item_id || !in_array($item_type, ['tour', 'service', 'hotel'])) {
    $response['message'] = 'Invalid item.';
    echo json_encode($response);
    exit();
}

// Check if the item is already in the wishlist
$stmt_check = $conn->prepare("SELECT id FROM wishlist_items WHERE user_id = ? AND item_id = ? AND item_type = ?");
$stmt_check->bind_param("iis", $user_id, $item_id, $item_type);
$stmt_check->execute();
$existing = $stmt_check->get_result()->fetch_assoc();
$stmt_check->close();

if ($existing) {
    // Item exists, so remove it
    $stmt_delete = $conn->prepare("DELETE FROM wishlist_items WHERE id = ?");
    $stmt_delete->bind_param("i", $existing['id']);
    if ($stmt_delete->execute()) {
        $response['success'] = true;
        $response['action'] = 'removed';
    }
    $stmt_delete->close();
} else {
    // Item does not exist, so add it
    $stmt_insert = $conn->prepare("INSERT INTO wishlist_items (user_id, item_id, item_type) VALUES (?, ?, ?)");
    $stmt_insert->bind_param("iis", $user_id, $item_id, $item_type);
    if ($stmt_insert->execute()) {
        $response['success'] = true;
        $response['action'] = 'added';
    }
    $stmt_insert->close();
}

echo json_encode($response);
?>
