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

$id = $_GET["id"] ?? null;

if (!$id) {
    die("Missing movie ID.");
}

$stmt = $pdo->prepare("SELECT * FROM media_movies WHERE id = ?");
$stmt->execute([$id]);
$movie = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$movie) {
    die("Movie not found.");
}

$embedUrl = $movie["player_embed_url"] ?? "";

if (empty($embedUrl) && !empty($movie["tmdb_id"])) {
    $embedUrl = "https://www.vidking.net/embed/movie/" . $movie["tmdb_id"];
}

if (!$embedUrl) {
    die("No Player Source Added For This Movie.");
}

if (!empty($_SESSION["user"]["id"]) && !empty($id)) {
    $historyStmt = $pdo->prepare("
        INSERT INTO user_history (user_id, movie_id, type, watched_at)
        VALUES (?, ?, 'movie', NOW())
        ON DUPLICATE KEY UPDATE watched_at = NOW()
    ");

    $historyStmt->execute([
        $_SESSION["user"]["id"],
        $id
    ]);
}
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo htmlspecialchars($movie["title"]); ?> - Rewire</title>
<link rel="icon" type="image/png" href="../Assets/Logo.png">

<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #000;
    overflow: hidden;
}

.player {
    width: 100vw;
    height: 100vh;
}

.player iframe {
    width: 100%;
    height: 100%;
    border: none;
}
</style>
</head>

<body>

<div class="player">
    <iframe
        src="<?php echo htmlspecialchars($embedUrl); ?>"
        allowfullscreen
        allow="autoplay; encrypted-media">
    </iframe>
</div>
<script src="../Security.js"></script>
</body>
</html>