<?php
header('Content-Type: application/json');
require_once '../includes/init.php'; // Use the central init file

$response = ['status' => 'error', 'message' => 'An unknown error occurred.'];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'];
    $item_id = filter_input(INPUT_POST, 'item_id', FILTER_VALIDATE_INT);
    $item_type = in_array($_POST['item_type'], ['tour', 'hotel']) ? $_POST['item_type'] : null;
    $action = $_POST['action'] ?? '';

    if ($item_id && $item_type) {
        if ($action === 'add') {
            $stmt = $conn->prepare("INSERT IGNORE INTO wishlist (user_id, item_id, item_type) VALUES (?, ?, ?)");
            $stmt->bind_param("iis", $user_id, $item_id, $item_type);
            if ($stmt->execute()) {
                $response = ['status' => 'success', 'newState' => 'added'];
            }
        } elseif ($action === 'remove') {
            $stmt = $conn->prepare("DELETE FROM wishlist WHERE user_id = ? AND item_id = ? AND item_type = ?");
            $stmt->bind_param("iis", $user_id, $item_id, $item_type);
            if ($stmt->execute()) {
                $response = ['status' => 'success', 'newState' => 'removed'];
            }
        }
    } else {
        $response['message'] = 'Invalid item data.';
    }
}

echo json_encode($response);
