<?php
include '../config/config.php';
include '../includes/auth.php'; // Ensure admin only

$episode_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Fetch Episode Details
$stmt = $pdo->prepare("SELECT e.*, d.title as drama_title FROM episodes e JOIN dramas d ON e.drama_id = d.id WHERE e.id = ?");
$stmt->execute([$episode_id]);
$episode = $stmt->fetch();

if (!$episode) { die("Episode not found."); }

// Handle Update Logic
if (isset($_POST['update_episode'])) {
    $ep_number = $_POST['ep_number'];
    $iframe = $_POST['iframe_code'];

    $update = $pdo->prepare("UPDATE episodes SET ep_number = ?, iframe_code = ? WHERE id = ?");
    if ($update->execute([$ep_number, $iframe, $episode_id])) {
        header("Location: view_episodes.php?id=" . $episode['drama_id'] . "&updated=1");
        exit();
    }
}

include '../includes/header.php';
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h3 class="text-white">Edit Episode: <?= $episode['drama_title'] ?></h3>
                <a href="view_episodes.php?id=<?= $episode['drama_id'] ?>" class="btn btn-outline-secondary btn-sm">Back</a>
            </div>

            <div class="card bg-dark border-secondary shadow-sm">
                <form class="card-body p-4" method="POST">
                    <div class="mb-3">
                        <label class="small text-white-50">Episode Number</label>
                        <input type="number" name="ep_number" class="form-control bg-black text-white border-secondary" value="<?= $episode['ep_number'] ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="small text-white-50">Iframe Code (Video Player)</label>
                        <textarea name="iframe_code" class="form-control bg-black text-white border-secondary" rows="6" required><?= htmlspecialchars($episode['iframe_code']) ?></textarea>
                    </div>
                    <div class="ratio ratio-16x9 mb-4 bg-black rounded border border-secondary">
                        <?= $episode['iframe_code'] ?>
                    </div>
                    <button type="submit" name="update_episode" class="btn btn-danger w-100 fw-bold">Update Episode Details</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>