<?php
session_start();

if (!isset($_SESSION["user"]) || empty($_SESSION["user"]["is_admin"])) {
    header("Location: ../Index.php");
    exit;
}

require "../Auth/db.php";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$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.");
}

$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);

if (isset($_POST["update_series"])) {
    $title = trim($_POST["title"] ?? "");
    $tmdbId = trim($_POST["tmdb_id"] ?? "");
    $description = trim($_POST["description"] ?? "");
    $category = trim($_POST["category"] ?? "");
    $youtubeTrailerUrl = trim($_POST["youtube_trailer_url"] ?? "");
    $rating = trim($_POST["rating"] ?? "");
    $releaseYear = trim($_POST["release_year"] ?? "");
    $duration = trim($_POST["duration"] ?? "");

    $bannerPath = $series["banner"];
    $logoPath = $series["logo"];

    if (!empty($_FILES["banner"]["name"])) {
        $uploadDir = "../Uploads/SeriesBanners/";

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileName = time() . "_" . basename($_FILES["banner"]["name"]);
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES["banner"]["tmp_name"], $targetPath)) {
            $bannerPath = "Uploads/SeriesBanners/" . $fileName;
        }
    }

    if (!empty($_FILES["logo"]["name"])) {
        $uploadDir = "../Uploads/SeriesLogos/";

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileName = time() . "_" . basename($_FILES["logo"]["name"]);
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES["logo"]["tmp_name"], $targetPath)) {
            $logoPath = "Uploads/SeriesLogos/" . $fileName;
        }
    }

    $stmt = $pdo->prepare("
        UPDATE media_series
        SET title = ?,
            tmdb_id = ?,
            description = ?,
            logo = ?,
            banner = ?,
            category = ?,
            youtube_trailer_url = ?,
            rating = ?,
            release_year = ?,
            duration = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $title,
        $tmdbId,
        $description,
        $logoPath,
        $bannerPath,
        $category,
        $youtubeTrailerUrl,
        $rating,
        $releaseYear,
        $duration,
        $seriesId
    ]);

    $pdo->prepare("DELETE FROM media_series_episodes WHERE series_id = ?")->execute([$seriesId]);

    if (!empty($_POST["season_number"])) {
        foreach ($_POST["season_number"] as $index => $seasonNumber) {
            $seasonNumber = (int)$seasonNumber;
            $episodeNumber = (int)($_POST["episode_number"][$index] ?? 0);
            $episodeTitle = trim($_POST["episode_title"][$index] ?? "");
            $existingBackground = $_POST["existing_episode_background"][$index] ?? null;
            $episodeBackground = $existingBackground;

            if (!empty($_FILES["episode_background"]["name"][$index])) {
                $uploadDir = "../Uploads/SeriesEpisodes/";

                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }

                $fileName = time() . "_" . $index . "_" . basename($_FILES["episode_background"]["name"][$index]);
                $targetPath = $uploadDir . $fileName;

                if (move_uploaded_file($_FILES["episode_background"]["tmp_name"][$index], $targetPath)) {
                    $episodeBackground = "Uploads/SeriesEpisodes/" . $fileName;
                }
            }

            if ($seasonNumber > 0 && $episodeNumber > 0) {
                $epStmt = $pdo->prepare("
                    INSERT INTO media_series_episodes
                    (series_id, season_number, episode_number, episode_title, episode_background)
                    VALUES (?, ?, ?, ?, ?)
                ");

                $epStmt->execute([
                    $seriesId,
                    $seasonNumber,
                    $episodeNumber,
                    $episodeTitle,
                    $episodeBackground
                ]);
            }
        }
    }

    header("Location: Dashboard.php?tab=db_series");
    exit;
}

$logoPreview = !empty($series["logo"]) ? "../" . $series["logo"] : "../Assets/Logo.png";
$bannerPreview = !empty($series["banner"]) ? "../" . $series["banner"] : "../Assets/Logo.png";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit TV Show - Rewire</title>
<link rel="icon" type="image/png" href="../Assets/Logo.png">
<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;
    padding: 35px;
}

.edit-page {
    max-width: 1300px;
    margin: 0 auto;
}

.top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 28px;
}

.top h1 {
    font-size: 1.8rem;
}

.back-btn {
    color: #00c2ff;
    text-decoration: none;
    font-weight: 800;
}

.panel {
    background: #0b0f12;
    border: 1px solid rgba(0,194,255,0.14);
    border-radius: 18px;
    padding: 28px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 18px;
}

.form-group.full {
    grid-column: span 2;
}

.form-group label {
    display: block;
    color: #8f9aa5;
    font-size: 0.8rem;
    font-weight: 800;
    letter-spacing: 1px;
    margin-bottom: 9px;
}

.form-group input,
.form-group textarea,
.form-group select {
    width: 100%;
    background: #071014;
    border: 1px solid rgba(0,194,255,0.15);
    border-radius: 12px;
    color: white;
    padding: 14px 16px;
    outline: none;
}

.form-group textarea {
    min-height: 140px;
    resize: vertical;
}

.preview-img {
    width: 160px;
    height: 95px;
    object-fit: cover;
    border-radius: 10px;
    border: 1px solid rgba(255,255,255,0.12);
    margin-bottom: 10px;
    background: #111;
}

.logo-preview {
    object-fit: contain;
}

input[type="file"]::file-selector-button {
    background: linear-gradient(135deg,#00c2ff,#0090c7);
    border: none;
    color: white;
    padding: 9px 14px;
    border-radius: 9px;
    margin-right: 12px;
    font-weight: 800;
    cursor: pointer;
}

.episodes-box {
    margin-top: 28px;
    padding: 24px;
    border: 1px solid rgba(0,194,255,0.18);
    border-radius: 18px;
    background: rgba(5,12,15,0.82);
}

.episodes-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
}

.episodes-header h3 {
    font-size: 1.2rem;
}

.add-btn,
.submit-btn {
    background: linear-gradient(135deg,#00c2ff,#0090c7);
    color: white;
    border: none;
    border-radius: 12px;
    padding: 13px 18px;
    font-weight: 800;
    cursor: pointer;
}

.episode-row {
    display: grid;
    grid-template-columns: 110px 110px 1fr 260px 120px;
    gap: 14px;
    align-items: center;
    margin-bottom: 14px;
}

.episode-row input {
    width: 100%;
    height: 48px;
    background: #081117;
    border: 1px solid rgba(0,194,255,0.16);
    border-radius: 12px;
    padding: 0 14px;
    color: white;
    outline: none;
}

.episode-row input[type="file"] {
    padding: 8px;
    font-size: 0.8rem;
}

.delete-btn {
    height: 48px;
    border-radius: 12px;
    border: 1px solid rgba(255,80,80,0.3);
    background: rgba(255,60,60,0.12);
    color: #ff6b6b;
    font-weight: 800;
    cursor: pointer;
}

.submit-btn {
    margin-top: 24px;
    min-width: 160px;
}

.current-bg {
    color: #8f9aa5;
    font-size: 0.75rem;
    margin-top: 5px;
}

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

    .form-group.full {
        grid-column: span 1;
    }

    .episode-row {
        grid-template-columns: 1fr;
    }
}
</style>
</head>

<body>

<div class="edit-page">
    <div class="top">
        <h1>Edit TV Show</h1>
        <a href="Dashboard.php?tab=db_series" class="back-btn">Back To DB TV Shows</a>
    </div>

    <div class="panel">
        <form method="POST" enctype="multipart/form-data">
            <div class="form-grid">
                <div class="form-group">
                    <label>Title</label>
                    <input type="text" name="title" value="<?php echo htmlspecialchars($series["title"] ?? ""); ?>" required>
                </div>

                <div class="form-group">
                    <label>TMDB ID</label>
                    <input type="text" name="tmdb_id" value="<?php echo htmlspecialchars($series["tmdb_id"] ?? ""); ?>" required>
                </div>

                <div class="form-group">
                    <label>YouTube Trailer Link</label>
                    <input type="text" name="youtube_trailer_url" value="<?php echo htmlspecialchars($series["youtube_trailer_url"] ?? ""); ?>">
                </div>

                <div class="form-group">
                    <label>Rating</label>
                    <input type="text" name="rating" value="<?php echo htmlspecialchars($series["rating"] ?? ""); ?>">
                </div>

                <div class="form-group">
                    <label>Release Year</label>
                    <input type="text" name="release_year" value="<?php echo htmlspecialchars($series["release_year"] ?? ""); ?>">
                </div>

                <div class="form-group">
                    <label>Duration</label>
                    <input type="text" name="duration" value="<?php echo htmlspecialchars($series["duration"] ?? ""); ?>">
                </div>

                <div class="form-group full">
                    <label>Description</label>
                    <textarea name="description"><?php echo htmlspecialchars($series["description"] ?? ""); ?></textarea>
                </div>

                <div class="form-group">
                    <label>Current Logo</label>
                    <img src="<?php echo htmlspecialchars($logoPreview); ?>" class="preview-img logo-preview">
                    <input type="file" name="logo" accept="image/*">
                </div>

                <div class="form-group">
                    <label>Current Banner</label>
                    <img src="<?php echo htmlspecialchars($bannerPreview); ?>" class="preview-img">
                    <input type="file" name="banner" accept="image/*">
                </div>

                <div class="form-group">
                    <label>Category</label>
                    <select name="category">
                        <?php
                            $categories = [
                                "",
                                "Action",
                                "Adventure",
                                "Animation",
                                "Comedy",
                                "Crime",
                                "Documentary",
                                "Drama",
                                "Family",
                                "Fantasy",
                                "History",
                                "Horror",
                                "Mystery",
                                "Romance",
                                "Sci-Fi",
                                "Thriller",
                                "War"
                            ];
                        ?>

                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo ($series["category"] ?? "") === $cat ? "selected" : ""; ?>>
                                <?php echo $cat === "" ? "Select Category" : htmlspecialchars($cat); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="episodes-box">
                <div class="episodes-header">
                    <h3>Episodes</h3>
                    <button type="button" class="add-btn" onclick="addEpisodeRow()">Add Episode</button>
                </div>

                <div id="episodeRows">
                    <?php if (!empty($episodes)): ?>
                        <?php foreach ($episodes as $ep): ?>
                            <div class="episode-row">
                                <input type="number" name="season_number[]" placeholder="Season" min="1" value="<?php echo htmlspecialchars($ep["season_number"]); ?>" required>

                                <input type="number" name="episode_number[]" placeholder="Episode" min="1" value="<?php echo htmlspecialchars($ep["episode_number"]); ?>" required>

                                <input type="text" name="episode_title[]" placeholder="Episode title" value="<?php echo htmlspecialchars($ep["episode_title"] ?? ""); ?>">

                                <div>
                                    <input type="hidden" name="existing_episode_background[]" value="<?php echo htmlspecialchars($ep["episode_background"] ?? ""); ?>">
                                    <input type="file" name="episode_background[]" accept="image/*">

                                    <?php if (!empty($ep["episode_background"])): ?>
                                        <div class="current-bg">Current background saved</div>
                                    <?php endif; ?>
                                </div>

                                <button type="button" class="delete-btn" onclick="removeEpisodeRow(this)">Delete</button>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="episode-row">
                            <input type="number" name="season_number[]" placeholder="Season" min="1" required>
                            <input type="number" name="episode_number[]" placeholder="Episode" min="1" required>
                            <input type="text" name="episode_title[]" placeholder="Episode title">

                            <div>
                                <input type="hidden" name="existing_episode_background[]" value="">
                                <input type="file" name="episode_background[]" accept="image/*">
                            </div>

                            <button type="button" class="delete-btn" onclick="removeEpisodeRow(this)">Delete</button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <button type="submit" name="update_series" class="submit-btn">Save Changes</button>
        </form>
    </div>
</div>

<script>
lucide.createIcons();

function addEpisodeRow() {
    const episodeRows = document.getElementById("episodeRows");

    const row = document.createElement("div");
    row.className = "episode-row";

    row.innerHTML = `
        <input type="number" name="season_number[]" placeholder="Season" min="1" required>
        <input type="number" name="episode_number[]" placeholder="Episode" min="1" required>
        <input type="text" name="episode_title[]" placeholder="Episode title">

        <div>
            <input type="hidden" name="existing_episode_background[]" value="">
            <input type="file" name="episode_background[]" accept="image/*">
        </div>

        <button type="button" class="delete-btn" onclick="removeEpisodeRow(this)">Delete</button>
    `;

    episodeRows.appendChild(row);
}

function removeEpisodeRow(button) {
    const rows = document.querySelectorAll(".episode-row");

    if (rows.length <= 1) {
        alert("You need at least one episode row.");
        return;
    }

    button.closest(".episode-row").remove();
}
</script>

</body>
</html>