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

require "../Auth/db.php";

$seriesId = $_GET["id"] ?? null;
$episodeId = $_GET["episode_id"] ?? null;

if (!$seriesId) {
    die("Missing series ID.");
}

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

if (!$series) {
    die("Series not found.");
}

if ($episodeId) {
    $epStmt = $pdo->prepare("
        SELECT *
        FROM media_series_episodes
        WHERE id = ? AND series_id = ?
        LIMIT 1
    ");
    $epStmt->execute([$episodeId, $seriesId]);
} else {
    $epStmt = $pdo->prepare("
        SELECT *
        FROM media_series_episodes
        WHERE series_id = ?
        ORDER BY season_number ASC, episode_number ASC
        LIMIT 1
    ");
    $epStmt->execute([$seriesId]);
}

$currentEpisode = $epStmt->fetch(PDO::FETCH_ASSOC);

if (!$currentEpisode) {
    die("No episodes found for this series.");
}

$episodesStmt = $pdo->prepare("
    SELECT *
    FROM media_series_episodes
    WHERE series_id = ?
    ORDER BY season_number ASC, episode_number ASC
");
$episodesStmt->execute([$seriesId]);
$episodes = $episodesStmt->fetchAll(PDO::FETCH_ASSOC);

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

    $historyStmt->execute([
        $_SESSION["user"]["id"],
        $seriesId
    ]);
}

if (empty($series["tmdb_id"])) {
    die("Missing TMDB ID for this series.");
}

$embedUrl =
    "https://www.vidking.net/embed/tv/" .
    urlencode($series["tmdb_id"]) . "/" .
    urlencode($currentEpisode["season_number"]) . "/" .
    urlencode($currentEpisode["episode_number"]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($series["title"]); ?> - Player</title>
<link rel="icon" type="image/png" href="../Assets/Logo.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
}

body {
    background: #050505;
    color: white;
}

.player-page {
    min-height: 100vh;
    display: grid;
    grid-template-columns: 1fr 340px;
}

.player-wrap {
    background: #000;
    height: 100vh;
}

.player-wrap iframe {
    width: 100%;
    height: 100%;
    border: none;
}

.sidebar {
    height: 100vh;
    overflow-y: auto;
    background: #0b0f12;
    border-left: 1px solid rgba(255,255,255,0.08);
    padding: 22px;
}

.back-btn {
    display: inline-flex;
    margin-bottom: 20px;
    color: #00c2ff;
    text-decoration: none;
    font-weight: 800;
}

.series-title {
    font-size: 1.3rem;
    font-weight: 900;
    margin-bottom: 6px;
}

.current-ep {
    color: #8f9aa5;
    font-size: 0.9rem;
    margin-bottom: 22px;
}

.episode-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.episode-card {
    display: block;
    padding: 13px 14px;
    border-radius: 12px;
    background: #071014;
    border: 1px solid rgba(0,194,255,0.12);
    color: white;
    text-decoration: none;
    transition: 0.25s ease;
}

.episode-card:hover,
.episode-card.active {
    background: rgba(0,194,255,0.14);
    border-color: rgba(0,194,255,0.45);
}

.episode-card strong {
    display: block;
    font-size: 0.9rem;
}

.episode-card span {
    display: block;
    margin-top: 4px;
    color: #8f9aa5;
    font-size: 0.78rem;
}

@media (max-width: 900px) {
    .player-page {
        grid-template-columns: 1fr;
    }

    .player-wrap {
        height: 60vh;
    }

    .sidebar {
        height: auto;
        border-left: none;
        border-top: 1px solid rgba(255,255,255,0.08);
    }
}
</style>
</head>

<body>

<div class="player-page">

    <div class="player-wrap">
        <iframe
            src="<?php echo htmlspecialchars($embedUrl); ?>"
            allowfullscreen
            allow="autoplay; fullscreen; encrypted-media">
        </iframe>
    </div>

    <aside class="sidebar">
        <a href="Preset.php?id=<?php echo htmlspecialchars($series["id"]); ?>" class="back-btn">
            ← Back
        </a>

        <div class="series-title">
            <?php echo htmlspecialchars($series["title"]); ?>
        </div>

        <div class="current-ep">
            Season <?php echo htmlspecialchars($currentEpisode["season_number"]); ?>,
            Episode <?php echo htmlspecialchars($currentEpisode["episode_number"]); ?>
        </div>

        <div class="episode-list">
            <?php foreach ($episodes as $ep): ?>
                <a
                    class="episode-card <?php echo $ep["id"] == $currentEpisode["id"] ? 'active' : ''; ?>"
                    href="Player.php?id=<?php echo $series["id"]; ?>&episode_id=<?php echo $ep["id"]; ?>"
                >
                    <strong>
                        S<?php echo htmlspecialchars($ep["season_number"]); ?>
                        E<?php echo htmlspecialchars($ep["episode_number"]); ?>
                    </strong>

                    <span>
                        <?php echo htmlspecialchars($ep["episode_title"] ?? "Episode"); ?>
                    </span>
                </a>
            <?php endforeach; ?>
        </div>
    </aside>

</div>
<script src="../Security.js"></script>
</body>
</html>