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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') redirect('admin/dashboard.php');
verify_csrf();

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

if ($action === 'delete') {
    $stmt = db()->prepare('DELETE FROM students WHERE id = ?');
    $stmt->execute([$studentId]);
    flash('success', 'تم حذف حساب الطالب.');
    redirect('admin/dashboard.php');
}

if (!in_array($action, ['approved','rejected','suspended'], true)) {
    flash('danger', 'الإجراء غير صحيح.');
    redirect('admin/dashboard.php');
}

if ($action === 'approved') {
    $stmt = db()->prepare('UPDATE students SET account_status = ?, approved_at = NOW(), approved_by = ? WHERE id = ?');
    $stmt->execute([$action, $_SESSION['admin_id'], $studentId]);
} else {
    $stmt = db()->prepare('UPDATE students SET account_status = ?, approved_at = NULL, approved_by = NULL WHERE id = ?');
    $stmt->execute([$action, $studentId]);
}

flash('success', 'تم تحديث حالة الحساب.');
redirect('admin/dashboard.php');
