<?php
session_start();

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

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

if (isset($_POST["update_movie"])) {
    $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"] ?? "");

    $playerEmbedUrl = !empty($tmdbId)
        ? "https://www.vidking.net/embed/movie/" . $tmdbId
        : "";

    $logoPath = $movie["logo"];
    $bannerPath = $movie["banner"] ?? null;

    if (!empty($_FILES["logo"]["name"])) {
        $uploadDir = "../Uploads/MovieLogos/";
        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/MovieLogos/" . $fileName;
        }
    }

    if (!empty($_FILES["banner"]["name"])) {
        $uploadDir = "../Uploads/MovieBanners/";
        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/MovieBanners/" . $fileName;
        }
    }

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

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

    header("Location: Dashboard.php?tab=db_movies");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Movie - Rewire Admin</title>
<link rel="icon" type="image/png" href="../Assets/Logo.png">

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

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

.edit-wrap {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    padding: 55px 25px;
}

.edit-card {
    width: 100%;
    max-width: 900px;
    background: #071014;
    border: 1px solid rgba(0,194,255,0.15);
    border-radius: 18px;
    padding: 30px;
}

.back-link {
    color: #00c2ff;
    text-decoration: none;
    font-weight: 800;
    display: inline-block;
    margin-bottom: 25px;
}

h1 {
    margin-bottom: 25px;
}

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

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

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

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

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

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

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

select option {
    background: #050505;
    color: white;
}

.save-btn {
    margin-top: 24px;
    height: 52px;
    padding: 0 24px;
    border: none;
    border-radius: 12px;
    background: linear-gradient(135deg,#00c2ff,#0090c7);
    color: white;
    font-weight: 900;
    cursor: pointer;
}
</style>
</head>

<body>

<div class="edit-wrap">
    <div class="edit-card">

        <a href="Dashboard.php?tab=db_movies" class="back-link">← Back To Movie DB</a>

        <h1>Edit Movie</h1>

        <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($movie["title"]); ?>" required>
                </div>

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

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

                <div class="form-group">
                    <label>Logo</label>
                    <input type="file" name="logo" accept="image/*">
                </div>

                <div class="form-group">
                    <label>Banner</label>
                    <input type="file" name="banner" accept="image/*">
                </div>

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

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

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

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

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

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

            </div>

            <button type="submit" name="update_movie" class="save-btn">
                Save Changes
            </button>
        </form>

    </div>
</div>

</body>
</html>