<?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/teacher-auth.php';
require_once __DIR__ . '/../includes/teacher-course-context.php';
require_once __DIR__ . '/../includes/grade-engine.php';
$pdo=db();requireTeacher();$teacher=currentTeacher($pdo);if(!$teacher){teacherLogout();redirect('teacher/login.php');}
$teacherId=(int)$teacher['id'];$courseId=(int)($_GET['course_id']??$_POST['course_id']??0);$success=flash('success')??'';$error=flash('error')??'';
$courses=getTeacherCourses($pdo,$teacherId);if($courseId<=0&&$courses)$courseId=(int)$courses[0]['id'];
if($courseId>0&&!teacherOwnsCourse($pdo,$teacherId,$courseId)){http_response_code(403);exit('Access denied.');}
if(isPost()){
 requireCsrf();
 try{
  $studentId=(int)($_POST['student_id']??0);$title=clean($_POST['title']??'');$type=clean($_POST['item_type']??'extra');$score=(float)($_POST['score']??0);$max=(float)($_POST['max_score']??100);$weight=(float)($_POST['weight']??0);$feedback=trim((string)($_POST['feedback']??''));
  if(!teacherCanAccessStudentCourse($pdo,$teacherId,$studentId,$courseId)) throw new RuntimeException('Student is not enrolled in your course.');
  if($title===''||$max<=0) throw new RuntimeException('Complete all grade fields.');
  if(!saveStudentGrade($pdo,$studentId,$courseId,$type,0,$title,$score,$max,$weight,$feedback,$teacherId,null)) throw new RuntimeException('Grade could not be saved.');
  logActivity($pdo,'teacher',$teacherId,'grade_saved',"Saved {$title} for student {$studentId}", $studentId,$courseId);flash('success','Grade saved and final result recalculated.');
 }catch(Throwable $e){flash('error',APP_DEBUG?$e->getMessage():'Grade could not be saved.');}
 redirect('teacher/grades.php?course_id='.$courseId);
}
$students=$courseId>0?safeFetchAll($pdo,"SELECT s.* FROM core_course_students cs INNER JOIN students s ON s.id=cs.student_id WHERE cs.course_id=? AND cs.status IN ('active','completed') ORDER BY s.full_name",[$courseId]):[];
$recent=$courseId>0?safeFetchAll($pdo,"SELECT g.*,s.full_name,gi.title,COALESCE(NULLIF(gi.item_type,''),gi.type) item_type FROM core_grades g INNER JOIN students s ON s.id=g.student_id INNER JOIN core_grade_items gi ON gi.id=g.grade_item_id WHERE g.course_id=? ORDER BY g.updated_at DESC,g.id DESC LIMIT 100",[$courseId]):[];
$finals=[];foreach($students as $s){$finals[(int)$s['id']]=getFinalGrade($pdo,(int)$s['id'],$courseId);}
$types=['exam','quiz','homework','participation','attendance','shadowing','obstacle','vocabulary','project','extra'];
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Teacher Gradebook</title><style>
*{box-sizing:border-box}body{margin:0;background:#f3f6fb;color:#0f172a;font-family:Inter,Arial,sans-serif}.page{max-width:1450px;margin:auto;padding:32px}.top{display:flex;justify-content:space-between;align-items:center;margin-bottom:25px}.top h1{font-size:46px;margin:0}.back{padding:13px 18px;border-radius:14px;background:#ede9fe;color:#5b21b6;text-decoration:none;font-weight:900}.coursebar{display:flex;gap:10px;background:#fff;padding:16px;border-radius:20px;margin-bottom:22px}.coursebar select{max-width:420px}.layout{display:grid;grid-template-columns:400px 1fr;gap:24px}.card{background:#fff;border-radius:28px;padding:25px;box-shadow:0 18px 45px rgba(15,23,42,.07)}label{display:block;font-weight:800;margin:13px 0 7px}input,select,textarea{width:100%;padding:13px;border:1px solid #dbe3ef;border-radius:13px;font:inherit}textarea{min-height:90px}.btn{border:0;border-radius:13px;padding:13px 17px;background:#7c3aed;color:#fff;font-weight:900;cursor:pointer}.full{width:100%;margin-top:18px}.alert{padding:14px 18px;border-radius:14px;margin-bottom:18px;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;margin-bottom:20px}.stat{background:#f8fafc;border-radius:18px;padding:18px}.stat strong{font-size:28px}.table{overflow:auto}table{width:100%;border-collapse:collapse;min-width:900px}th,td{padding:13px;border-top:1px solid #e2e8f0;text-align:left}th{background:#f8fafc}.pill{padding:6px 10px;border-radius:999px;background:#ede9fe;color:#6d28d9;font-weight:800;font-size:12px}@media(max-width:950px){.layout{grid-template-columns:1fr}.page{padding:20px}.top h1{font-size:36px}}
</style></head><body><main class="page"><div class="top"><div><h1>Teacher Gradebook</h1><p><?=e($teacher['full_name']??$teacher['name'])?></p></div><a class="back" href="dashboard.php">Dashboard</a></div><form class="coursebar" 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 course</button></form><?php if($success):?><div class="alert ok"><?=e($success)?></div><?php endif;?><?php if($error):?><div class="alert bad"><?=e($error)?></div><?php endif;?><div class="layout"><section class="card"><h2>Add or update a grade</h2><form method="post"><?=csrfField()?><input type="hidden" name="course_id" value="<?=$courseId?>"><label>Student</label><select name="student_id" required><option value="">Choose student</option><?php foreach($students as $s):?><option value="<?=$s['id']?>"><?=e($s['full_name'].' — '.$s['student_code'])?></option><?php endforeach;?></select><label>Assessment title</label><input name="title" required placeholder="Week 2 homework"><label>Type</label><select name="item_type"><?php foreach($types as $t):?><option value="<?=$t?>"><?=e(ucfirst($t))?></option><?php endforeach;?></select><label>Score</label><input type="number" step="0.01" min="0" name="score" required><label>Maximum score</label><input type="number" step="0.01" min="0.01" name="max_score" value="100" required><label>Weight %</label><input type="number" step="0.01" min="0" max="100" name="weight" value="0"><label>Feedback</label><textarea name="feedback"></textarea><button class="btn full">Save grade</button></form></section><section class="card"><div class="stats"><?php foreach($students as $s):$f=$finals[(int)$s['id']]??[];?><div class="stat"><small><?=e($s['full_name'])?></small><br><strong><?=e(number_format((float)($f['final_percentage']??0),1))?>%</strong> <span class="pill"><?=e($f['grade_letter']??gradeLetter((float)($f['final_percentage']??0)))?></span></div><?php endforeach;?></div><h2>Recent grades</h2><div class="table"><table><thead><tr><th>Student</th><th>Assessment</th><th>Type</th><th>Score</th><th>%</th><th>Feedback</th><th>Updated</th></tr></thead><tbody><?php foreach($recent as $r):?><tr><td><?=e($r['full_name'])?></td><td><?=e($r['title'])?></td><td><span class="pill"><?=e($r['item_type'])?></span></td><td><?=e($r['score'].' / '.$r['max_score'])?></td><td><?=e(number_format((float)$r['percentage'],1))?>%</td><td><?=e($r['feedback']??'-')?></td><td><?=e(formatDateTimeNice($r['updated_at']??$r['created_at']))?></td></tr><?php endforeach;?><?php if(!$recent):?><tr><td colspan="7">No grades have been entered.</td></tr><?php endif;?></tbody></table></div></section></div></main></body></html>
