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

$studentId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
    ?: filter_input(INPUT_POST, 'student_id', FILTER_VALIDATE_INT);
if (!$studentId) {
    flash('danger', 'رقم الطالب غير صحيح.');
    redirect('admin/dashboard.php');
}

$stmt = db()->prepare('SELECT * FROM students WHERE id = ? LIMIT 1');
$stmt->execute([$studentId]);
$student = $stmt->fetch();
if (!$student) {
    flash('danger', 'الطالب غير موجود.');
    redirect('admin/dashboard.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $videoLimit = max(0, (int) ($_POST['video_limit'] ?? 0));
    $quizLimit = max(0, (int) ($_POST['quiz_limit'] ?? 0));
    $selectedVideoIds = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['video_ids'] ?? [])))));
    $selectedQuizIds = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['quiz_ids'] ?? [])))));

    $allowedVideoIds = [];
    if ($selectedVideoIds) {
        $placeholders = implode(',', array_fill(0, count($selectedVideoIds), '?'));
        $check = db()->prepare("SELECT id FROM videos WHERE grade = ? AND id IN ($placeholders)");
        $check->execute(array_merge([$student['grade']], $selectedVideoIds));
        $allowedVideoIds = array_map('intval', array_column($check->fetchAll(), 'id'));
    }

    $allowedQuizIds = [];
    if ($selectedQuizIds) {
        $placeholders = implode(',', array_fill(0, count($selectedQuizIds), '?'));
        $check = db()->prepare("SELECT id FROM quizzes WHERE grade = ? AND id IN ($placeholders)");
        $check->execute(array_merge([$student['grade']], $selectedQuizIds));
        $allowedQuizIds = array_map('intval', array_column($check->fetchAll(), 'id'));
    }

    db()->beginTransaction();
    try {
        $update = db()->prepare('UPDATE students SET video_limit = ?, quiz_limit = ? WHERE id = ?');
        $update->execute([$videoLimit, $quizLimit, $studentId]);

        $delete = db()->prepare('DELETE FROM student_video_access WHERE student_id = ?');
        $delete->execute([$studentId]);
        if ($allowedVideoIds) {
            $insert = db()->prepare('INSERT INTO student_video_access (student_id, video_id, granted_by) VALUES (?, ?, ?)');
            foreach ($allowedVideoIds as $videoId) {
                $insert->execute([$studentId, $videoId, $_SESSION['admin_id']]);
            }
        }

        $delete = db()->prepare('DELETE FROM student_quiz_access WHERE student_id = ?');
        $delete->execute([$studentId]);
        if ($allowedQuizIds) {
            $insert = db()->prepare('INSERT INTO student_quiz_access (student_id, quiz_id, granted_by) VALUES (?, ?, ?)');
            foreach ($allowedQuizIds as $quizId) {
                $insert->execute([$studentId, $quizId, $_SESSION['admin_id']]);
            }
        }

        db()->commit();
        flash('success', 'تم تحديث الفيديوهات والاختبارات المتاحة للطالب.');
        redirect('admin/student_access.php?id=' . $studentId);
    } catch (Throwable $exception) {
        if (db()->inTransaction()) {
            db()->rollBack();
        }
        throw $exception;
    }
}

$stmt = db()->prepare('SELECT * FROM videos WHERE grade = ? 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'));

$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 = ? 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'));

$pageTitle = 'صلاحيات محتوى الطالب';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="dashboard-head">
    <div>
        <h1>صلاحيات محتوى الطالب</h1>
        <p><?= e($student['full_name']) ?> — <?= e(grade_text($student['grade'])) ?></p>
    </div>
    <a class="btn btn-outline" href="<?= e(url('admin/dashboard.php')) ?>">العودة للطلاب</a>
</div>

<section class="card access-card">
    <form method="post">
        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="student_id" value="<?= (int) $studentId ?>">

        <div class="content-access-block">
            <div class="section-title-row">
                <div><span class="dashboard-kicker">دروس الشرح</span><h2>صلاحيات الفيديوهات</h2></div>
            </div>
            <div class="access-summary">
                <div>
                    <label for="video_limit">فتح أول عدد من الفيديوهات حسب الترتيب</label>
                    <input id="video_limit" type="number" min="0" name="video_limit" value="<?= (int) $student['video_limit'] ?>">
                    <small class="field-help">الفيديوهات المجانية متاحة دائمًا، مهما كان العدد.</small>
                </div>
                <div class="access-note">يمكنك فتح فيديوهات أخرى يدويًا من القائمة، حتى لو ترتيبها بعد العدد المحدد.</div>
            </div>
            <div class="video-access-list">
                <?php if (!$videos): ?><div class="empty-state">لا توجد فيديوهات لهذا الصف.</div><?php endif; ?>
                <?php foreach ($videos as $index => $video): $withinLimit = ($index + 1) <= (int) $student['video_limit']; ?>
                    <label class="video-access-item <?= (int) $video['is_active'] !== 1 ? 'is-disabled' : '' ?>">
                        <input type="checkbox" name="video_ids[]" value="<?= (int) $video['id'] ?>" <?= in_array((int) $video['id'], $manualVideoIds, true) ? 'checked' : '' ?>>
                        <img src="<?= e(youtube_thumbnail_url($video['youtube_id'])) ?>" alt="">
                        <span class="video-access-copy">
                            <strong><?= (int) $video['sort_order'] ?>. <?= e($video['title']) ?></strong>
                            <span><?= (int) $video['is_free'] === 1 ? 'مجاني' : 'مدفوع' ?><?= $withinLimit ? ' • داخل العدد المفتوح' : '' ?><?= (int) $video['is_active'] !== 1 ? ' • مخفي' : '' ?></span>
                        </span>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="content-access-block quiz-access-block">
            <div class="section-title-row">
                <div><span class="dashboard-kicker">تدريب وتقييم</span><h2>صلاحيات الاختبارات</h2></div>
            </div>
            <div class="access-summary">
                <div>
                    <label for="quiz_limit">فتح أول عدد من الاختبارات حسب الترتيب</label>
                    <input id="quiz_limit" type="number" min="0" name="quiz_limit" value="<?= (int) ($student['quiz_limit'] ?? 0) ?>">
                    <small class="field-help">الاختبارات المجانية متاحة دائمًا، مهما كان العدد.</small>
                </div>
                <div class="access-note">يمكنك فتح اختبارات إضافية محددة يدويًا، بنفس طريقة الفيديوهات.</div>
            </div>
            <div class="quiz-access-list">
                <?php if (!$quizzes): ?><div class="empty-state">لا توجد اختبارات لهذا الصف.</div><?php endif; ?>
                <?php foreach ($quizzes as $index => $quiz): $withinLimit = ($index + 1) <= (int) ($student['quiz_limit'] ?? 0); ?>
                    <label class="quiz-access-item <?= (int) $quiz['is_active'] !== 1 ? 'is-disabled' : '' ?>">
                        <input type="checkbox" name="quiz_ids[]" value="<?= (int) $quiz['id'] ?>" <?= in_array((int) $quiz['id'], $manualQuizIds, true) ? 'checked' : '' ?>>
                        <span class="quiz-access-icon">?</span>
                        <span class="video-access-copy">
                            <strong><?= (int) $quiz['sort_order'] ?>. <?= e($quiz['title']) ?></strong>
                            <span><?= (int) $quiz['question_count'] ?> سؤال • <?= (int) $quiz['is_free'] === 1 ? 'مجاني' : 'مدفوع' ?><?= $withinLimit ? ' • داخل العدد المفتوح' : '' ?><?= (int) $quiz['is_active'] !== 1 ? ' • مخفي' : '' ?></span>
                        </span>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <button class="btn btn-primary" type="submit">حفظ صلاحيات المحتوى</button>
    </form>
</section>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
