<?php
// admin_panel/pages/registration_video.php

// 1. Load dependencies and authenticate (no output yet)
require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../config/database.php';
requireLogin();

// 2. Handle POST before any HTML is generated
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $video_url = trim($_POST['video_url'] ?? '');
    $stmt = $pdo->prepare("
        INSERT INTO settings (`key`, `value`)
        VALUES ('registration_video_url', ?)
        ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)
    ");
    $stmt->execute([$video_url]);
    setFlash('success', 'Registration video URL updated.');

    // Redirect to the same page – safe because nothing has been output yet
    header('Location: registration_video.php');
    exit;
}

// 3. Fetch the current URL (still no HTML)
$stmt = $pdo->query("SELECT `value` FROM settings WHERE `key` = 'registration_video_url'");
$current = $stmt->fetchColumn() ?: '';

// 4. Now include the HTML layout (this starts output)
require_once '../includes/header.php';
?>

<h1 class="h2 mb-4">Registration Video</h1>

<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="card shadow-sm">
    <div class="card-body">
        <form method="POST">
            <div class="mb-3">
                <label class="form-label">Video URL (full link)</label>
                <input type="url" name="video_url" class="form-control"
                       value="<?= htmlspecialchars($current) ?>"
                       placeholder="https://www.youtube.com/watch?v=XXXXXXXXXXX" required>
                <div class="form-text">
                    Enter a direct MP4 video URL or a YouTube link (e.g. https://youtu.be/... or https://www.youtube.com/watch?v=...).<br>
                    The registration screen will automatically play the video.
                </div>
            </div>
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-save"></i> Save
            </button>
        </form>
    </div>
</div>

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