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

$grade = (string) ($_GET['grade'] ?? '');
$status = (string) ($_GET['status'] ?? '');
$search = trim((string) ($_GET['search'] ?? ''));

$where = [];
$params = [];
if (in_array($grade, ['first_secondary', 'second_secondary'], true)) {
    $where[] = 'q.grade = ?';
    $params[] = $grade;
}
if ($status === 'active') {
    $where[] = 'q.is_active = 1';
} elseif ($status === 'hidden') {
    $where[] = 'q.is_active = 0';
}
if ($search !== '') {
    $where[] = '(q.title LIKE ? OR q.description LIKE ?)';
    $like = '%' . $search . '%';
    array_push($params, $like, $like);
}

$sql = 'SELECT q.*, COUNT(qq.id) AS question_count
        FROM quizzes q
        LEFT JOIN quiz_questions qq ON qq.quiz_id = q.id';
if ($where) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}
$sql .= ' GROUP BY q.id ORDER BY q.grade, q.sort_order, q.id';
$stmt = db()->prepare($sql);
$stmt->execute($params);
$quizzes = $stmt->fetchAll();

$pageTitle = 'إدارة الاختبارات';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="dashboard-head">
    <div>
        <h1>إدارة الاختبارات</h1>
        <p>أنشئ اختبارات اختيار من متعدد وحدد المجاني والمخصص للمشتركين.</p>
    </div>
    <div class="actions compact-actions">
        <a class="btn btn-primary" href="<?= e(url('admin/quiz_form.php')) ?>">إضافة اختبار</a>
        <a class="btn btn-outline" href="<?= e(url('admin/dashboard.php')) ?>">لوحة الطلاب</a>
    </div>
</div>

<section class="card">
    <form class="filters" method="get">
        <input name="search" value="<?= e($search) ?>" placeholder="بحث بعنوان الاختبار">
        <select name="grade">
            <option value="">كل الصفوف</option>
            <option value="first_secondary" <?= $grade === 'first_secondary' ? 'selected' : '' ?>>الصف الأول الثانوي</option>
            <option value="second_secondary" <?= $grade === 'second_secondary' ? 'selected' : '' ?>>الصف الثاني الثانوي</option>
        </select>
        <select name="status">
            <option value="">كل الحالات</option>
            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>منشور</option>
            <option value="hidden" <?= $status === 'hidden' ? 'selected' : '' ?>>مخفي</option>
        </select>
        <button class="btn btn-primary" type="submit">تصفية</button>
    </form>

    <div class="table-wrap">
        <table>
            <thead>
            <tr>
                <th>الاختبار</th>
                <th>الصف</th>
                <th>الترتيب</th>
                <th>الأسئلة</th>
                <th>الإتاحة</th>
                <th>الحالة</th>
                <th>الإجراءات</th>
            </tr>
            </thead>
            <tbody>
            <?php if (!$quizzes): ?>
                <tr><td colspan="7">لا توجد اختبارات حتى الآن.</td></tr>
            <?php endif; ?>
            <?php foreach ($quizzes as $quiz): ?>
                <tr>
                    <td>
                        <strong><?= e($quiz['title']) ?></strong>
                        <?php if (!empty($quiz['description'])): ?>
                            <small class="table-subtext"><?= e(mb_strimwidth($quiz['description'], 0, 95, '...')) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?= e(grade_text($quiz['grade'])) ?></td>
                    <td><?= (int) $quiz['sort_order'] ?></td>
                    <td><strong><?= (int) $quiz['question_count'] ?></strong> سؤال</td>
                    <td><span class="status <?= (int) $quiz['is_free'] === 1 ? 'status-approved' : 'status-pending' ?>"><?= (int) $quiz['is_free'] === 1 ? 'مجاني' : 'للمشتركين' ?></span></td>
                    <td><span class="status <?= (int) $quiz['is_active'] === 1 ? 'status-approved' : 'status-suspended' ?>"><?= (int) $quiz['is_active'] === 1 ? 'منشور' : 'مخفي' ?></span></td>
                    <td>
                        <div class="actions compact-actions table-actions quiz-table-actions">
                            <a class="btn btn-small btn-primary" href="<?= e(url('admin/quiz_questions.php?quiz_id=' . (int) $quiz['id'])) ?>">الأسئلة</a>
                            <a class="btn btn-small btn-outline" href="<?= e(url('admin/quiz_form.php?id=' . (int) $quiz['id'])) ?>">تعديل</a>
                            <form method="post" action="<?= e(url('admin/quiz_action.php')) ?>">
                                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                                <input type="hidden" name="quiz_id" value="<?= (int) $quiz['id'] ?>">
                                <input type="hidden" name="action" value="toggle">
                                <button class="btn btn-small btn-warning" type="submit"><?= (int) $quiz['is_active'] === 1 ? 'إخفاء' : 'نشر' ?></button>
                            </form>
                            <form method="post" action="<?= e(url('admin/quiz_action.php')) ?>" onsubmit="return confirm('سيتم حذف الاختبار وكل أسئلته ونتائجه. هل أنت متأكد؟')">
                                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                                <input type="hidden" name="quiz_id" value="<?= (int) $quiz['id'] ?>">
                                <input type="hidden" name="action" value="delete">
                                <button class="btn btn-small btn-danger" type="submit">حذف</button>
                            </form>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
