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

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

$username = $_SESSION["user"]["username"] ?? "Guest";
$avatar = "../Assets/Logo.png";

if (!empty($_SESSION["user"]["avatar"]) && !empty($_SESSION["user"]["discord_id"])) {
    $avatar = "https://cdn.discordapp.com/avatars/" .
        $_SESSION["user"]["discord_id"] . "/" .
        $_SESSION["user"]["avatar"] . ".png";
}

$seriesId = $_GET["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("TV Show Not Found.");
}

function youtubeEmbedUrl($url) {
    if (!$url) return "";

    preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&?]+)/', $url, $matches);

    if (empty($matches[1])) return "";

    $id = $matches[1];

    return "https://www.youtube.com/embed/" . $id .
        "?autoplay=1&mute=1&controls=0&loop=1&playlist=" . $id .
        "&playsinline=1&modestbranding=1&rel=0";
}

$trailerEmbed = youtubeEmbedUrl($series["youtube_trailer_url"] ?? "");

$fallbackBg = !empty($series["banner"])
    ? "../" . $series["banner"]
    : "../Assets/Logo.png";

$logoPath = !empty($series["logo"])
    ? "../" . $series["logo"]
    : "../Assets/Logo.png";

$isInWatchlist = false;

if (!empty($_SESSION["user"]["id"])) {
    $watchStmt = $pdo->prepare("
        SELECT id
        FROM user_watchlist
        WHERE user_id = ? AND movie_id = ? AND type = 'series'
        LIMIT 1
    ");
    $watchStmt->execute([$_SESSION["user"]["id"], $series["id"]]);
    $isInWatchlist = (bool)$watchStmt->fetch();
}

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

$seasons = [];

foreach ($episodes as $episode) {
    $seasons[$episode["season_number"]][] = $episode;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($series["title"]); ?> - Rewire</title>
<link rel="icon" type="image/png" href="../Assets/Logo.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="https://unpkg.com/lucide@latest"></script>

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

body{
    background:#050505;
    color:white;
    overflow-x:hidden;
}

/* HEADER */
.header{
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:82px;
    z-index:50;
    background:linear-gradient(to bottom, rgba(0,0,0,0.85), transparent);
}

.header-inner{
    height:100%;
    padding:0 35px;
    display:flex;
    align-items:center;
    justify-content:space-between;
}

.home-btn{
    color:#ccc;
    display:flex;
    align-items:center;
    justify-content:center;
    text-decoration:none;
    transition:0.25s ease;
}

.home-btn i{
    width:22px;
    height:22px;
}

.home-btn:hover{
    color:#00c2ff;
    transform:scale(1.08);
}

.logo img{
    height:58px;
}

/* HERO */
.movie-hero{
    position:relative;
    min-height:78vh;
    display:flex;
    align-items:flex-end;
    padding:150px 70px 90px;
    overflow:hidden;
}

.trailer-bg{
    position:absolute;
    inset:0;
    z-index:0;
    overflow:hidden;
    background-size:cover;
    background-position:center;
}

.trailer-bg iframe{
    position:absolute;
    top:50%;
    left:50%;
    width:120vw;
    height:67.5vw;
    min-width:177.77vh;
    min-height:100vh;
    transform:translate(-50%,-50%);
    pointer-events:none;
}

.hero-overlay{
    position:absolute;
    inset:0;
    z-index:1;
    background:
        linear-gradient(to bottom, rgba(5,5,5,0.15), rgba(5,5,5,0.75) 78%, #050505 100%),
        linear-gradient(to right, rgba(5,5,5,0.92), rgba(5,5,5,0.45) 42%, rgba(5,5,5,0.1));
}

.movie-info{
    position:relative;
    z-index:2;
    width:100%;
    max-width:620px;
}

.title-logo{
    max-width:260px;
    max-height:130px;
    object-fit:contain;
    margin-bottom:22px;
}

.movie-meta{
    display:flex;
    align-items:center;
    flex-wrap:wrap;
    gap:14px;
    color:#c8d0d8;
    font-size:0.95rem;
    margin-bottom:18px;
}

.movie-meta span{
    display:flex;
    align-items:center;
    line-height:1;
}

.movie-meta .star{
    color:#00c2ff;
    font-weight:900;
}

.description{
    color:#e0e0e0;
    line-height:1.7;
    font-size:1rem;
    margin-bottom:28px;
}

.hero-buttons{
    display:flex;
    align-items:center;
    gap:14px;
}

.play-btn,
.circle-btn{
    height:50px;
    border:none;
    border-radius:999px;
    font-weight:800;
    cursor:pointer;
    transition:0.25s ease;
    text-decoration:none;
}

.play-btn{
    padding:0 28px;
    background:white;
    color:black;
    display:flex;
    align-items:center;
    gap:10px;
}

.circle-btn{
    width:50px;
    background:rgba(255,255,255,0.1);
    color:white;
    border:1px solid rgba(255,255,255,0.18);
    display:flex;
    align-items:center;
    justify-content:center;
}

.play-btn:hover,
.circle-btn:hover{
    transform:translateY(-2px) scale(1.04);
}

.watchlist-btn i{
    width:24px;
    height:24px;
    transition:0.25s ease;
}

.watchlist-btn.added{
    background:rgba(255,59,59,0.16);
    border-color:rgba(255,59,59,0.45);
    color:#ff6b6b;
}

.watchlist-btn:hover i{
    transform:rotate(90deg) scale(1.1);
}

/* SECTIONS */
.movie-section{
    max-width:1400px;
    margin:0 auto;
    padding:35px 70px 70px;
}

.section-title{
    display:flex;
    align-items:center;
    gap:10px;
    font-size:1.45rem;
    margin-bottom:24px;
}

.section-title::before{
    content:"";
    width:4px;
    height:24px;
    background:#00c2ff;
}

.category-grid{
    display:flex;
    flex-wrap:wrap;
    gap:12px;
    margin-bottom:45px;
}

.category-chip{
    padding:11px 18px;
    border-radius:999px;
    background:#071014;
    border:1px solid rgba(0,194,255,0.18);
    color:#c8d0d8;
    font-weight:800;
}

@media(max-width:900px){
    .movie-hero{
        padding:130px 25px 70px;
    }

    .movie-section{
        padding:30px 25px 50px;
    }
}

.episode-controls {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.episode-controls select,
.episode-search {
    height: 42px;
    background: #080a0d;
    border: 1px solid rgba(255,255,255,0.12);
    border-radius: 12px;
    color: white;
}

.episode-controls select {
    padding: 0 18px;
    min-width: 150px;
}

.episode-search {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0 14px;
    width: 320px;
}

.episode-search input {
    flex: 1;
    background: transparent;
    border: none;
    outline: none;
    color: white;
}

.episode-search i {
    width: 18px;
    color: #8f9aa5;
}

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

.episode-card {
    display: flex;
    align-items: center;
    gap: 16px;
    min-height: 105px;
    padding: 12px;
    background: rgba(8,10,13,0.8);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 14px;
    text-decoration: none;
    color: white;
    transition: 0.25s ease;
}

.episode-card:hover {
    background: rgba(255,255,255,0.05);
    border-color: rgba(0,194,255,0.25);
}

.episode-thumb {
    width: 160px;
    height: 90px;
    border-radius: 9px;
    background-size: cover;
    background-position: center;
    position: relative;
    flex-shrink: 0;
}

.episode-thumb span {
    position: absolute;
    left: 8px;
    bottom: 8px;
    width: 22px;
    height: 22px;
    border-radius: 5px;
    background: rgba(5,5,5,0.85);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.75rem;
    font-weight: 900;
}

.episode-info h3 {
    font-size: 1rem;
    margin-bottom: 8px;
}

.episode-info p {
    color: #9fb3d1;
    font-size: 0.88rem;
}

.episode-controls select{
    height:42px;
    min-width:150px;
    padding:0 18px;

    background:#080a0d;
    color:white;

    border:1px solid rgba(255,255,255,0.12);
    border-radius:12px;

    outline:none;
    cursor:pointer;

    appearance:none;
    -webkit-appearance:none;
    -moz-appearance:none;

    transition:0.25s ease;

    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' fill='white' viewBox='0 0 24 24'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
    background-repeat:no-repeat;
    background-position:right 14px center;
    background-size:18px;
}

.episode-controls select:hover{
    border-color:rgba(0,194,255,0.35);
    background-color:#0b1015;
}

.episode-controls select:focus{
    border-color:#00c2ff;
    box-shadow:0 0 0 3px rgba(0,194,255,0.15);
}

.episode-controls select option{
    background:#080a0d;
    color:white;
}
</style>
</head>

<body>
<?php include "../Preloader.php"; ?>
<header class="header">
    <div class="header-inner">
        <a href="../Index.php" class="logo">
            <img src="../Assets/Logo.png" alt="Rewire Logo">
        </a>
    </div>
</header>

<section class="movie-hero">

    <div
        class="trailer-bg"
        style="<?php echo empty($trailerEmbed) ? "background-image:url('" . htmlspecialchars($fallbackBg) . "')" : ""; ?>"
    >
        <?php if (!empty($trailerEmbed)): ?>
            <iframe
                src="<?php echo htmlspecialchars($trailerEmbed); ?>"
                frameborder="0"
                allow="autoplay; encrypted-media"
                allowfullscreen>
            </iframe>
        <?php endif; ?>
    </div>

    <div class="hero-overlay"></div>

    <div class="movie-info">

        <img src="<?php echo htmlspecialchars($logoPath); ?>" class="title-logo">

        <div class="movie-meta">
            <span class="star">★&nbsp;<?php echo htmlspecialchars($series["rating"] ?? "N/A"); ?></span>
            <span><?php echo htmlspecialchars($series["release_year"] ?? "Unknown"); ?></span>
            <span>TV Show</span>

            <?php if (!empty($series["duration"])): ?>
                <span>Duration - <?php echo htmlspecialchars($series["duration"]); ?></span>
            <?php endif; ?>
        </div>

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

        <div class="hero-buttons">
            <a href="Player.php?id=<?php echo $series["id"]; ?>" class="play-btn">
                <i data-lucide="play"></i>
                Play
            </a>

            <a
                class="circle-btn watchlist-btn <?php echo $isInWatchlist ? 'added' : ''; ?>"
                href="../WatchlistToggle.php?id=<?php echo $series["id"]; ?>&type=series"
                title="<?php echo $isInWatchlist ? 'Remove from Watchlist' : 'Add To Watchlist'; ?>"
            >
                <i data-lucide="<?php echo $isInWatchlist ? 'x' : 'plus'; ?>"></i>
            </a>
        </div>
    </div>
</section>

<section class="movie-section">
    <h2 class="section-title">Categories</h2>
    <div class="category-grid">
        <div class="category-chip">
            <?php echo htmlspecialchars($series["category"] ?? "Uncategorized"); ?>
        </div>
    </div>

    <?php if (!empty($episodes)): ?>
        <h2 class="section-title">Episodes</h2>
    
        <div class="episode-controls">
            <select id="seasonSelect" onchange="filterEpisodes()">
                <?php foreach (array_keys($seasons) as $seasonNumber): ?>
                    <option value="<?php echo $seasonNumber; ?>">
                        Season <?php echo $seasonNumber; ?>
                    </option>
                <?php endforeach; ?>
            </select>
    
            <div class="episode-search">
                <i data-lucide="search"></i>
                <input type="text" id="episodeSearch" placeholder="Search episode..." oninput="filterEpisodes()">
            </div>
        </div>
    
        <div class="episodes-list">
            <?php foreach ($episodes as $episode): ?>
                <?php
                    $episodeBg = !empty($episode["episode_background"])
                        ? "../" . $episode["episode_background"]
                        : $fallbackBg;
                ?>
    
                <a
                    href="Player.php?id=<?php echo $series["id"]; ?>&season=<?php echo $episode["season_number"]; ?>&episode=<?php echo $episode["episode_number"]; ?>"
                    class="episode-card"
                    data-season="<?php echo $episode["season_number"]; ?>"
                    data-title="<?php echo strtolower(htmlspecialchars($episode["episode_title"] ?? "")); ?>"
                >
                    <div class="episode-thumb" style="background-image:url('<?php echo htmlspecialchars($episodeBg); ?>')">
                        <span><?php echo htmlspecialchars($episode["episode_number"]); ?></span>
                    </div>
    
                    <div class="episode-info">
                        <h3><?php echo htmlspecialchars($episode["episode_title"] ?: "Episode " . $episode["episode_number"]); ?></h3>
                        <p>
                            Season <?php echo htmlspecialchars($episode["season_number"]); ?>
                            · Episode <?php echo htmlspecialchars($episode["episode_number"]); ?>
                        </p>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>

<script>
lucide.createIcons();

function filterEpisodes() {
    const selectedSeason = document.getElementById("seasonSelect").value;
    const searchTerm = document.getElementById("episodeSearch").value.toLowerCase().trim();

    document.querySelectorAll(".episode-card").forEach(card => {
        const seasonMatch = card.dataset.season === selectedSeason;
        const titleMatch = card.dataset.title.includes(searchTerm);

        card.style.display = seasonMatch && titleMatch ? "flex" : "none";
    });
}

filterEpisodes();
</script>
<script src="../Security.js"></script>
</body>
</html>