<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();
requireAdmin();

$students = [];

if (tableExists($pdo, 'students')) {

    $students = $pdo->query("
        SELECT
            s.*,
            COALESCE(f.final_percentage,0) AS final_percentage
        FROM students s
        LEFT JOIN core_final_grades f
            ON f.student_id = s.id
        ORDER BY final_percentage DESC
    ")->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Progress</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap" rel="stylesheet">

<style>
body{font-family:Inter,sans-serif;background:#f1f5f9;padding:30px}
.card{background:#fff;padding:30px;border-radius:30px}
table{width:100%;border-collapse:collapse}
th,td{padding:16px;border-top:1px solid #e2e8f0;text-align:left}
th{background:#f8fafc}
.progress{height:16px;background:#e2e8f0;border-radius:999px;overflow:hidden}
.fill{height:100%;background:#2563eb}
</style>
</head>
<body>

<div class="card">

<h1>Student Progress</h1>

<table>

<thead>
<tr>
<th>Student</th>
<th>Level</th>
<th>Progress</th>
<th>Final %</th>
</tr>
</thead>

<tbody>

<?php if($students): ?>

<?php foreach($students as $student): ?>

<?php
$percent = (float)$student['final_percentage'];
?>

<tr>

<td><?php echo e($student['full_name']); ?></td>

<td><?php echo e($student['final_level'] ?? 'N/A'); ?></td>

<td>
<div class="progress">
<div class="fill" style="width:<?php echo $percent; ?>%"></div>
</div>
</td>

<td><?php echo number_format($percent,2); ?>%</td>

</tr>

<?php endforeach; ?>

<?php else: ?>

<tr>
<td colspan="4">No progress data found.</td>
</tr>

<?php endif; ?>

</tbody>

</table>

</div>

</body>
</html>