<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_student();

$videoId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$videoId) {
    flash('danger', 'الفيديو غير صحيح.');
    redirect('student/dashboard.php');
}

$stmt = db()->prepare('SELECT * FROM students WHERE id = ? LIMIT 1');
$stmt->execute([$_SESSION['student_id']]);
$student = $stmt->fetch();
if (!$student || $student['account_status'] !== 'approved') {
    unset($_SESSION['student_id']);
    flash('warning', 'لا يمكن الدخول إلى الحساب حاليًا.');
    redirect('login.php');
}

$stmt = db()->prepare('SELECT * FROM videos WHERE id = ? AND grade = ? AND is_active = 1 LIMIT 1');
$stmt->execute([$videoId, $student['grade']]);
$video = $stmt->fetch();
if (!$video) {
    flash('danger', 'الفيديو غير موجود أو غير متاح لصفك.');
    redirect('student/dashboard.php');
}

if (!student_has_video_access((int) $_SESSION['student_id'], $student, $video)) {
    flash('warning', 'هذا الفيديو غير متاح ضمن اشتراكك الحالي.');
    redirect('student/dashboard.php');
}

$pageTitle = $video['title'];
require_once __DIR__ . '/../includes/header.php';
?>
<div class="dashboard-head watch-heading">
    <div>
        <span class="dashboard-kicker">الدرس رقم <?= (int) $video['sort_order'] ?></span>
        <h1><?= e($video['title']) ?></h1>
        <p><?= e(grade_text($video['grade'])) ?></p>
    </div>
    <a class="btn btn-outline" href="<?= e(url('student/dashboard.php')) ?>">العودة لكل الدروس</a>
</div>

<section class="watch-card">
    <div class="video-player">
        <iframe
            src="<?= e(youtube_embed_url($video['youtube_id'])) ?>"
            title="<?= e($video['title']) ?>"
            loading="lazy"
            referrerpolicy="strict-origin-when-cross-origin"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowfullscreen></iframe>
    </div>
    <?php if (!empty($video['description'])): ?>
        <div class="watch-description">
            <h2>عن الدرس</h2>
            <p><?= nl2br(e($video['description'])) ?></p>
        </div>
    <?php endif; ?>
</section>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
