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

$counts = ['pending' => 0, 'approved' => 0, 'rejected' => 0, 'suspended' => 0];
foreach (db()->query('SELECT account_status, COUNT(*) total FROM students GROUP BY account_status') as $row) {
    $counts[$row['account_status']] = (int) $row['total'];
}
$videoCount = (int) db()->query('SELECT COUNT(*) FROM videos')->fetchColumn();
$quizCount = (int) db()->query('SELECT COUNT(*) FROM quizzes')->fetchColumn();

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

$where = [];
$params = [];
if (in_array($status, ['pending','approved','rejected','suspended'], true)) {
    $where[] = 'account_status = ?';
    $params[] = $status;
}
if (in_array($grade, ['first_secondary','second_secondary'], true)) {
    $where[] = 'grade = ?';
    $params[] = $grade;
}
if ($search !== '') {
    $where[] = '(full_name LIKE ? OR phone LIKE ? OR school_name LIKE ?)';
    $like = '%' . $search . '%';
    array_push($params, $like, $like, $like);
}

$sql = 'SELECT * FROM students';
if ($where) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}
$sql .= ' ORDER BY created_at DESC';
$stmt = db()->prepare($sql);
$stmt->execute($params);
$students = $stmt->fetchAll();

$pageTitle = 'لوحة الأدمن';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="dashboard-head">
    <div>
        <h1>لوحة إدارة كودو</h1>
        <p>مرحبًا <?= e($_SESSION['admin_name'] ?? 'أدمن') ?>، تحكم في الطلاب والفيديوهات والاختبارات من مكان واحد.</p>
    </div>
    <div class="actions compact-actions">
        <a class="btn btn-primary" href="<?= e(url('admin/videos.php')) ?>">إدارة الفيديوهات</a>
        <a class="btn btn-primary" href="<?= e(url('admin/quizzes.php')) ?>">إدارة الاختبارات</a>
        <a class="btn btn-outline" href="<?= e(url('admin/logout.php')) ?>">تسجيل الخروج</a>
    </div>
</div>

<div class="stats stats-six">
    <div class="stat"><span>قيد المراجعة</span><strong><?= $counts['pending'] ?></strong></div>
    <div class="stat"><span>مقبول</span><strong><?= $counts['approved'] ?></strong></div>
    <div class="stat"><span>مرفوض</span><strong><?= $counts['rejected'] ?></strong></div>
    <div class="stat"><span>موقوف</span><strong><?= $counts['suspended'] ?></strong></div>
    <div class="stat stat-highlight"><span>الفيديوهات</span><strong><?= $videoCount ?></strong></div>
    <div class="stat stat-highlight"><span>الاختبارات</span><strong><?= $quizCount ?></strong></div>
</div>

<section class="card">
    <form class="filters" method="get">
        <input name="search" value="<?= e($search) ?>" placeholder="بحث بالاسم أو الهاتف أو المدرسة">
        <select name="status">
            <option value="">كل الحالات</option>
            <option value="pending" <?= $status==='pending'?'selected':'' ?>>قيد المراجعة</option>
            <option value="approved" <?= $status==='approved'?'selected':'' ?>>مقبول</option>
            <option value="rejected" <?= $status==='rejected'?'selected':'' ?>>مرفوض</option>
            <option value="suspended" <?= $status==='suspended'?'selected':'' ?>>موقوف</option>
        </select>
        <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>
        <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>
                <th>الإجراءات</th>
            </tr>
            </thead>
            <tbody>
            <?php if (!$students): ?>
                <tr><td colspan="8">لا توجد نتائج.</td></tr>
            <?php endif; ?>
            <?php foreach ($students as $student):
                $statusText = ['pending'=>'قيد المراجعة','approved'=>'مقبول','rejected'=>'مرفوض','suspended'=>'موقوف'][$student['account_status']];
            ?>
                <tr>
                    <td><strong><?= e($student['full_name']) ?></strong><small class="table-subtext"><?= e($student['created_at']) ?></small></td>
                    <td><a href="https://wa.me/<?= e(ltrim($student['phone'], '+')) ?>" target="_blank" rel="noopener"><?= e($student['phone']) ?></a></td>
                    <td><?= e($student['school_name']) ?></td>
                    <td><?= e(grade_text($student['grade'])) ?></td>
                    <td><strong><?= (int) ($student['video_limit'] ?? 0) ?></strong> حسب الترتيب</td>
                    <td><strong><?= (int) ($student['quiz_limit'] ?? 0) ?></strong> حسب الترتيب</td>
                    <td><span class="status status-<?= e($student['account_status']) ?>"><?= e($statusText) ?></span></td>
                    <td>
                        <div class="actions compact-actions table-actions">
                            <a class="btn btn-small btn-primary" href="<?= e(url('admin/student_access.php?id=' . (int) $student['id'])) ?>">المحتوى</a>
                            <?php foreach ([
                                'approved' => ['قبول','btn-success'],
                                'rejected' => ['رفض','btn-warning'],
                                'suspended' => ['إيقاف','btn-outline'],
                            ] as $action => [$label,$class]): ?>
                                <form method="post" action="<?= e(url('admin/student_action.php')) ?>">
                                    <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                                    <input type="hidden" name="student_id" value="<?= (int) $student['id'] ?>">
                                    <input type="hidden" name="action" value="<?= e($action) ?>">
                                    <button class="btn btn-small <?= e($class) ?>" type="submit"><?= e($label) ?></button>
                                </form>
                            <?php endforeach; ?>
                            <form method="post" action="<?= e(url('admin/student_action.php')) ?>" onsubmit="return confirm('هل تريد حذف الطالب نهائيًا؟')">
                                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                                <input type="hidden" name="student_id" value="<?= (int) $student['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'; ?>
