<?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/security.php';require_once __DIR__ . '/../includes/admin-auth.php';require_once __DIR__ . '/../includes/grade-engine.php';
$pdo=db();requireAdmin();$courseId=(int)($_GET['course_id']??$_POST['course_id']??0);$courses=safeFetchAll($pdo,'SELECT * FROM core_courses ORDER BY id DESC');if($courseId<=0&&$courses)$courseId=(int)$courses[0]['id'];
if(isPost()){requireCsrf();$action=(string)($_POST['action']??'recalculate');$studentId=(int)($_POST['student_id']??0);if($action==='recalculate_all'){$ids=safeFetchAll($pdo,'SELECT student_id FROM core_course_students WHERE course_id=?',[$courseId]);foreach($ids as $id)recalculateFinalGrade($pdo,(int)$id['student_id'],$courseId);flash('success','All final grades recalculated.');}elseif($studentId>0){recalculateFinalGrade($pdo,$studentId,$courseId);if($action==='finalize')mustExecute($pdo,"UPDATE core_final_grades SET status='finalized',finalized_at=NOW(),updated_at=NOW() WHERE student_id=? AND course_id=?",[$studentId,$courseId]);flash('success','Final grade updated.');}redirect('admin/final-grades.php?course_id='.$courseId);}
$rows=$courseId>0?safeFetchAll($pdo,"SELECT s.id student_id,s.full_name,s.student_code,fg.* FROM core_course_students cs INNER JOIN students s ON s.id=cs.student_id LEFT JOIN core_final_grades fg ON fg.student_id=s.id AND fg.course_id=cs.course_id WHERE cs.course_id=? ORDER BY s.full_name",[$courseId]):[];
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Final Grades</title><style>body{font-family:Inter,Arial,sans-serif;background:#f3f6fb;color:#0f172a;margin:0}.page{max-width:1400px;margin:auto;padding:32px}.top,.toolbar{display:flex;justify-content:space-between;align-items:center;gap:14px;margin-bottom:22px}.top h1{font-size:46px;margin:0}.card{background:#fff;border-radius:28px;padding:24px;box-shadow:0 18px 45px rgba(15,23,42,.07);overflow:auto}.btn{border:0;border-radius:13px;padding:12px 15px;background:#2563eb;color:#fff;text-decoration:none;font-weight:900;cursor:pointer}.green{background:#16a34a}.toolbar select{padding:12px;border:1px solid #dbe3ef;border-radius:13px;min-width:320px}.alert{padding:14px 18px;background:#dcfce7;color:#166534;border-radius:14px;margin-bottom:18px;font-weight:800}table{width:100%;border-collapse:collapse;min-width:1000px}th,td{padding:13px;border-top:1px solid #e2e8f0;text-align:left}th{background:#f8fafc}.pill{padding:6px 10px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-weight:800;font-size:12px}.actions{display:flex;gap:6px}.actions form{display:inline}.actions .btn{padding:8px 10px}@media(max-width:700px){.page{padding:20px}.top,.toolbar{align-items:flex-start;flex-direction:column}.top h1{font-size:36px}}</style></head><body><main class="page"><div class="top"><div><h1>Final Grades</h1><p>Recalculate and finalize official course results.</p></div><a class="btn" href="dashboard.php">Dashboard</a></div><?php if($m=flash('success')):?><div class="alert"><?=e($m)?></div><?php endif;?><div class="toolbar"><form method="get"><select name="course_id"><?php foreach($courses as $c):?><option value="<?=$c['id']?>" <?=selected($courseId,$c['id'])?>><?=e($c['title'].' — '.$c['course_code'])?></option><?php endforeach;?></select><button class="btn">Open</button></form><form method="post"><?=csrfField()?><input type="hidden" name="action" value="recalculate_all"><input type="hidden" name="course_id" value="<?=$courseId?>"><button class="btn green">Recalculate all</button></form></div><section class="card"><table><thead><tr><th>Student</th><th>Final</th><th>Letter</th><th>GPA</th><th>Status</th><th>Components</th><th>Actions</th></tr></thead><tbody><?php foreach($rows as $r):$pct=(float)($r['final_percentage']??0);?><tr><td><strong><?=e($r['full_name'])?></strong><br><small><?=e($r['student_code'])?></small></td><td><strong><?=e(number_format($pct,1))?>%</strong></td><td><span class="pill"><?=e($r['grade_letter']??gradeLetter($pct))?></span></td><td><?=e(number_format((float)($r['gpa']??gradeGpa($pct)),2))?></td><td><?=e($r['status']??'draft')?> / <?=e($r['pass_status']??getPassStatus($pct))?></td><td>Exam <?=e(number_format((float)($r['exams_score']??0),1))?> · Homework <?=e(number_format((float)($r['homework_score']??0),1))?> · Attendance <?=e(number_format((float)($r['attendance_score']??0),1))?></td><td><div class="actions"><?php foreach([['recalculate','Recalculate',''],['finalize','Finalize','green']] as [$a,$label,$class]):?><form method="post"><?=csrfField()?><input type="hidden" name="action" value="<?=$a?>"><input type="hidden" name="course_id" value="<?=$courseId?>"><input type="hidden" name="student_id" value="<?=$r['student_id']?>"><button class="btn <?=$class?>"><?=$label?></button></form><?php endforeach;?></div></td></tr><?php endforeach;?><?php if(!$rows):?><tr><td colspan="7">No students are enrolled.</td></tr><?php endif;?></tbody></table></section></main></body></html>
