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

$stmt = db()->prepare('SELECT full_name, phone, school_name, grade, account_status, video_limit, quiz_limit 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');
}

$studentId = (int) $_SESSION['student_id'];

$stmt = db()->prepare('SELECT * FROM videos WHERE grade = ? AND is_active = 1 ORDER BY sort_order, id');
$stmt->execute([$student['grade']]);
$videos = $stmt->fetchAll();
$stmt = db()->prepare('SELECT video_id FROM student_video_access WHERE student_id = ?');
$stmt->execute([$studentId]);
$manualVideoIds = array_map('intval', array_column($stmt->fetchAll(), 'video_id'));

$unlockedVideoCount = 0;
foreach ($videos as $index => &$video) {
    $position = $index + 1;
    $video['is_unlocked'] = (int) $video['is_free'] === 1
        || $position <= (int) $student['video_limit']
        || in_array((int) $video['id'], $manualVideoIds, true);
    if ($video['is_unlocked']) {
        $unlockedVideoCount++;
    }
}
unset($video);

$stmt = db()->prepare(
    'SELECT q.*, COUNT(qq.id) AS question_count
     FROM quizzes q
     LEFT JOIN quiz_questions qq ON qq.quiz_id = q.id
     WHERE q.grade = ? AND q.is_active = 1
     GROUP BY q.id
     ORDER BY q.sort_order, q.id'
);
$stmt->execute([$student['grade']]);
$quizzes = $stmt->fetchAll();
$stmt = db()->prepare('SELECT quiz_id FROM student_quiz_access WHERE student_id = ?');
$stmt->execute([$studentId]);
$manualQuizIds = array_map('intval', array_column($stmt->fetchAll(), 'quiz_id'));

$stmt = db()->prepare('SELECT quiz_id, MAX(score) AS best_score, MAX(total_questions) AS total_questions, COUNT(*) AS attempt_count FROM quiz_attempts WHERE student_id = ? GROUP BY quiz_id');
$stmt->execute([$studentId]);
$quizHistory = [];
foreach ($stmt->fetchAll() as $row) {
    $quizHistory[(int) $row['quiz_id']] = $row;
}

$unlockedQuizCount = 0;
foreach ($quizzes as $index => &$quiz) {
    $position = $index + 1;
    $quiz['is_unlocked'] = (int) $quiz['is_free'] === 1
        || $position <= (int) ($student['quiz_limit'] ?? 0)
        || in_array((int) $quiz['id'], $manualQuizIds, true);
    $quiz['history'] = $quizHistory[(int) $quiz['id']] ?? null;
    if ($quiz['is_unlocked']) {
        $unlockedQuizCount++;
    }
}
unset($quiz);

$pageTitle = 'محتوى الطالب';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="dashboard-head student-dashboard-head">
    <div>
        <span class="dashboard-kicker">منصة كودو التعليمية</span>
        <h1>أهلًا <?= e($student['full_name']) ?> 👋</h1>
        <p>أنا كودو، وهكون صاحبك في رحلة تعلم البرمجة والذكاء الاصطناعي.</p>
    </div>
    <div class="student-mini-profile">
        <strong><?= e(grade_text($student['grade'])) ?></strong>
        <span><?= e($student['school_name']) ?></span>
    </div>
</div>

<div class="student-stats student-stats-four">
    <div><span>فيديوهات الشرح</span><strong><?= count($videos) ?></strong><small><?= $unlockedVideoCount ?> متاح لك</small></div>
    <div><span>الاختبارات</span><strong><?= count($quizzes) ?></strong><small><?= $unlockedQuizCount ?> متاح لك</small></div>
    <div><span>فيديوهات ضمن اشتراكك</span><strong><?= (int) $student['video_limit'] ?></strong></div>
    <div><span>اختبارات ضمن اشتراكك</span><strong><?= (int) ($student['quiz_limit'] ?? 0) ?></strong></div>
</div>

<section class="lessons-section">
    <div class="section-title-row">
        <div>
            <span class="dashboard-kicker">محتوى صفك</span>
            <h2>فيديوهات الشرح</h2>
        </div>
        <span class="section-note">الفيديوهات بعلامة القفل تحتاج تفعيلًا من الإدارة.</span>
    </div>

    <?php if (!$videos): ?>
        <div class="card empty-state student-empty">
            <img src="<?= e(url('assets/images/kodo-logo.png')) ?>" alt="كودو">
            <div><h2>الفيديوهات قادمة قريبًا</h2><p>لم تتم إضافة فيديوهات لهذا الصف حتى الآن.</p></div>
        </div>
    <?php else: ?>
        <div class="lessons-grid">
            <?php foreach ($videos as $video): $unlocked = (bool) $video['is_unlocked']; ?>
                <article class="lesson-card <?= $unlocked ? 'is-unlocked' : 'is-locked' ?>">
                    <div class="lesson-thumb">
                        <img src="<?= e(youtube_thumbnail_url($video['youtube_id'])) ?>" alt="<?= e($video['title']) ?>">
                        <span class="lesson-number"><?= (int) $video['sort_order'] ?></span>
                        <?php if ((int) $video['is_free'] === 1): ?><span class="lesson-free-badge">مجاني</span><?php endif; ?>
                        <span class="lesson-state-icon"><?= $unlocked ? '▶' : '🔒' ?></span>
                    </div>
                    <div class="lesson-content">
                        <span class="lesson-meta"><?= e(grade_text($video['grade'])) ?></span>
                        <h3><?= e($video['title']) ?></h3>
                        <?php if (!empty($video['description'])): ?><p><?= e($video['description']) ?></p><?php endif; ?>
                        <?php if ($unlocked): ?>
                            <a class="btn btn-primary lesson-button" href="<?= e(url('student/watch.php?id=' . (int) $video['id'])) ?>">مشاهدة الدرس</a>
                        <?php else: ?>
                            <button class="btn btn-locked lesson-button" type="button" disabled>غير متاح ضمن اشتراكك</button>
                        <?php endif; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>

<section class="lessons-section quizzes-section">
    <div class="section-title-row">
        <div>
            <span class="dashboard-kicker">اختبر فهمك</span>
            <h2>الاختبارات والأسئلة</h2>
        </div>
        <span class="section-note">الإجابات الصحيحة تظهر بعد إنهاء الاختبار.</span>
    </div>

    <?php if (!$quizzes): ?>
        <div class="card empty-state student-empty">
            <img src="<?= e(url('assets/images/kodo-logo.png')) ?>" alt="كودو">
            <div><h2>الاختبارات قادمة قريبًا</h2><p>لم تتم إضافة اختبارات لهذا الصف حتى الآن.</p></div>
        </div>
    <?php else: ?>
        <div class="quiz-grid">
            <?php foreach ($quizzes as $quiz):
                $unlocked = (bool) $quiz['is_unlocked'];
                $hasQuestions = (int) $quiz['question_count'] > 0;
                $history = $quiz['history'];
            ?>
                <article class="quiz-card <?= $unlocked ? 'is-unlocked' : 'is-locked' ?>">
                    <div class="quiz-card-top">
                        <span class="quiz-number"><?= (int) $quiz['sort_order'] ?></span>
                        <span class="quiz-icon">?</span>
                        <?php if ((int) $quiz['is_free'] === 1): ?><span class="lesson-free-badge">مجاني</span><?php endif; ?>
                        <?php if (!$unlocked): ?><span class="quiz-lock">🔒</span><?php endif; ?>
                    </div>
                    <div class="quiz-card-content">
                        <span class="lesson-meta"><?= (int) $quiz['question_count'] ?> سؤال اختيار من متعدد</span>
                        <h3><?= e($quiz['title']) ?></h3>
                        <p><?= !empty($quiz['description']) ? e($quiz['description']) : 'اختر الإجابة الصحيحة، ثم شاهد النتيجة والتصحيح في النهاية.' ?></p>
                        <?php if ($history): ?>
                            <div class="quiz-best-result">أفضل نتيجة: <strong><?= (int) $history['best_score'] ?> / <?= (int) $history['total_questions'] ?></strong></div>
                        <?php endif; ?>
                        <?php if ($unlocked && $hasQuestions): ?>
                            <a class="btn btn-primary lesson-button" href="<?= e(url('student/quiz.php?id=' . (int) $quiz['id'])) ?>"><?= $history ? 'إعادة الاختبار' : 'ابدأ الاختبار' ?></a>
                        <?php elseif ($unlocked): ?>
                            <button class="btn btn-locked lesson-button" type="button" disabled>الأسئلة لم تُضف بعد</button>
                        <?php else: ?>
                            <button class="btn btn-locked lesson-button" type="button" disabled>غير متاح ضمن اشتراكك</button>
                        <?php endif; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
