<?php
session_start();
require "Auth/db.php";

if (empty($_SESSION["user"]["id"])) {
    header("Location: Index.php");
    exit;
}

$userId = (int)$_SESSION["user"]["id"];
$id = (int)($_GET["id"] ?? 0);
$type = $_GET["type"] ?? "movie";

if (!$id || !in_array($type, ["movie", "series"], true)) {
    die("Invalid watchlist request.");
}

$stmt = $pdo->prepare("
    SELECT id FROM user_watchlist
    WHERE user_id = ? AND movie_id = ? AND type = ?
    LIMIT 1
");
$stmt->execute([$userId, $id, $type]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);

if ($existing) {
    $stmt = $pdo->prepare("
        DELETE FROM user_watchlist
        WHERE user_id = ? AND movie_id = ? AND type = ?
    ");
    $stmt->execute([$userId, $id, $type]);
} else {
    $stmt = $pdo->prepare("
        INSERT INTO user_watchlist (user_id, movie_id, type, created_at)
        VALUES (?, ?, ?, NOW())
    ");
    $stmt->execute([$userId, $id, $type]);
}

$back = $type === "series"
    ? "Series/Preset.php?id=" . $id
    : "Movies/Preset.php?id=" . $id;

header("Location: " . $back);
exit;