<?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/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');}
$type=(string)($_GET['type']??$_POST['submission_type']??'homework');if(!in_array($type,['homework','shadowing','obstacle'],true))$type='homework';$error='';$success=flash('success')?:'';
function teacherSubmission(PDO $pdo,int $teacherId,string $type,int $id): ?array {
 if($type==='homework') return safeFetch($pdo,"SELECT hs.id,hs.student_id,h.id AS item_id,h.course_id,h.title,h.max_points AS max_score FROM core_homework_submissions hs INNER JOIN core_homework h ON h.id=hs.homework_id INNER JOIN core_courses c ON c.id=h.course_id WHERE hs.id=? AND c.teacher_id=? LIMIT 1",[$id,$teacherId]);
 if($type==='shadowing') return safeFetch($pdo,"SELECT ss.id,ss.student_id,sh.id AS item_id,sh.course_id,sh.title,sh.points AS max_score FROM core_shadowing_submissions ss INNER JOIN core_shadowing sh ON sh.id=COALESCE(NULLIF(ss.lesson_id,0),NULLIF(ss.task_id,0)) INNER JOIN core_courses c ON c.id=sh.course_id WHERE ss.id=? AND c.teacher_id=? LIMIT 1",[$id,$teacherId]);
 return safeFetch($pdo,"SELECT os.id,os.student_id,st.id AS item_id,o.course_id,st.title,st.points AS max_score FROM core_obstacle_submissions os INNER JOIN core_obstacle_steps st ON st.id=os.step_id INNER JOIN core_obstacles o ON o.id=st.obstacle_id INNER JOIN core_courses c ON c.id=o.course_id WHERE os.id=? AND c.teacher_id=? LIMIT 1",[$id,$teacherId]);
}
if(isPost()){requireCsrf();$id=(int)($_POST['submission_id']??0);$status=(string)($_POST['status']??'');$note=trim((string)($_POST['teacher_note']??''));$score=(float)($_POST['score']??0);$row=teacherSubmission($pdo,(int)$teacher['id'],$type,$id);$allowed=$type==='homework'?['reviewed','rejected']:['approved','needs_correction','rejected'];if(!$row||!in_array($status,$allowed,true))$error='Invalid submission or review status.';else{$max=max(0.01,(float)($row['max_score']??5));if($score<0||$score>$max)$error='The score must be between 0 and '.$max.'.';else{try{$table=['homework'=>'core_homework_submissions','shadowing'=>'core_shadowing_submissions','obstacle'=>'core_obstacle_submissions'][$type];$stmt=$pdo->prepare("UPDATE {$table} SET status=?,teacher_note=?,score=?,reviewed_at=NOW(),reviewed_by=? WHERE id=?");$stmt->execute([$status,$note?:null,$score,(int)$teacher['id'],$id]);$accepted=in_array($status,['reviewed','approved'],true);saveStudentGrade($pdo,(int)$row['student_id'],(int)$row['course_id'],$type,(int)$row['item_id'],(string)$row['title'],$accepted?$score:0,$max,0,$note?:null,(int)$teacher['id'],null);logActivity($pdo,'teacher',(int)$teacher['id'],'Submission reviewed',ucfirst($type).' submission '.$id.' set to '.$status,null,(int)$row['course_id']);flash('success','Submission reviewed and the gradebook was recalculated.');redirect('teacher/submissions.php?type='.$type);}catch(Throwable $e){error_log('[SMI review submission] '.$e->getMessage());$error=APP_DEBUG?$e->getMessage():'The review could not be saved.';}}}}
if($type==='homework'){$rows=safeFetchAll($pdo,"SELECT hs.*,s.full_name,s.student_code,h.title AS task_title,h.max_points AS max_score,h.course_id,COALESCE(hs.submission_url,hs.file_path) AS evidence FROM core_homework_submissions hs INNER JOIN students s ON s.id=hs.student_id INNER JOIN core_homework h ON h.id=hs.homework_id INNER JOIN core_courses c ON c.id=h.course_id WHERE c.teacher_id=? ORDER BY hs.submitted_at DESC",[(int)$teacher['id']]);}
elseif($type==='shadowing'){$rows=safeFetchAll($pdo,"SELECT ss.*,s.full_name,s.student_code,sh.title AS task_title,sh.points AS max_score,sh.course_id,COALESCE(ss.recording_link,ss.recording_url) AS evidence FROM core_shadowing_submissions ss INNER JOIN students s ON s.id=ss.student_id INNER JOIN core_shadowing sh ON sh.id=COALESCE(NULLIF(ss.lesson_id,0),NULLIF(ss.task_id,0)) INNER JOIN core_courses c ON c.id=sh.course_id WHERE c.teacher_id=? ORDER BY ss.submitted_at DESC",[(int)$teacher['id']]);}
else{$rows=safeFetchAll($pdo,"SELECT os.*,s.full_name,s.student_code,st.title AS task_title,st.points AS max_score,o.course_id,os.submission_url AS evidence FROM core_obstacle_submissions os INNER JOIN students s ON s.id=os.student_id INNER JOIN core_obstacle_steps st ON st.id=os.step_id INNER JOIN core_obstacles o ON o.id=st.obstacle_id INNER JOIN core_courses c ON c.id=o.course_id WHERE c.teacher_id=? ORDER BY os.submitted_at DESC",[(int)$teacher['id']]);}
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Submissions · SMI</title><style>:root{font-family:Inter,Arial,sans-serif;background:#f3f6fb;color:#0f172a}*{box-sizing:border-box}body{margin:0}.page{max-width:1400px;margin:auto;padding:30px}.top{display:flex;justify-content:space-between;align-items:center}.top h1{font-size:44px;margin:0}.btn{border:0;border-radius:13px;padding:11px 15px;background:#2563eb;color:#fff;text-decoration:none;font-weight:850;cursor:pointer}.tabs{display:flex;gap:10px;margin:22px 0}.tabs a{padding:11px 15px;background:white;border-radius:13px;text-decoration:none;color:#334155;font-weight:850}.tabs .active{background:#2563eb;color:white}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(350px,1fr));gap:18px}.card{background:white;padding:21px;border-radius:24px;box-shadow:0 15px 42px rgba(15,23,42,.07)}.meta{color:#64748b;font-size:13px}.evidence{display:block;margin:12px 0;color:#1d4ed8;overflow-wrap:anywhere}.review{display:grid;grid-template-columns:1fr 110px;gap:9px;margin-top:14px}.review textarea{grid-column:1/-1;min-height:70px}.review select,.review input,.review textarea{width:100%;padding:10px;border:1px solid #dbe3ef;border-radius:11px;font:inherit}.alert{padding:14px 18px;border-radius:14px;margin:16px 0;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.pill{display:inline-block;padding:5px 9px;background:#eff6ff;color:#1d4ed8;border-radius:999px;font-size:12px;font-weight:850}.empty{background:white;padding:45px;border-radius:24px;text-align:center;color:#64748b}@media(max-width:650px){.page{padding:18px}.top h1{font-size:34px}}</style></head><body><main class="page"><div class="top"><div><h1>Submission review</h1><p>Review work only from courses assigned to your teacher account.</p></div><a class="btn" href="dashboard.php">Dashboard</a></div><nav class="tabs"><?php foreach(['homework','shadowing','obstacle'] as $t):?><a class="<?=$type===$t?'active':''?>" href="?type=<?=$t?>"><?=ucfirst($t)?></a><?php endforeach;?></nav><?php if($success):?><div class="alert ok"><?=e($success)?></div><?php endif;?><?php if($error):?><div class="alert bad"><?=e($error)?></div><?php endif;?><?php if($rows):?><section class="grid"><?php foreach($rows as $r):$max=max(.01,(float)($r['max_score']??5));?><article class="card"><span class="pill"><?=e($r['status'])?></span><h3><?=e($r['task_title'])?></h3><div class="meta"><?=e($r['full_name'])?> · <?=e($r['student_code'])?> · <?=e(formatDateTimeNice($r['submitted_at']))?></div><?php if(!empty($r['submission_text'])):?><p><?=nl2br(e($r['submission_text']))?></p><?php endif;?><?php if(!empty($r['student_note'])):?><p><?=nl2br(e($r['student_note']))?></p><?php endif;?><?php if(!empty($r['evidence'])):?><a class="evidence" target="_blank" rel="noopener" href="<?=e(str_starts_with((string)$r['evidence'],'uploads/')?'../'.$r['evidence']:$r['evidence'])?>">Open submitted evidence</a><?php endif;?><form class="review" method="post"><?=csrfField()?><input type="hidden" name="submission_type" value="<?=$type?>"><input type="hidden" name="submission_id" value="<?=$r['id']?>"><select name="status"><?php foreach(($type==='homework'?['reviewed','rejected']:['approved','needs_correction','rejected']) as $st):?><option value="<?=$st?>" <?=selected($r['status'],$st)?>><?=ucwords(str_replace('_',' ',$st))?></option><?php endforeach;?></select><input type="number" name="score" min="0" max="<?=$max?>" step="0.01" value="<?=e($r['score']??0)?>"><textarea name="teacher_note" placeholder="Feedback for the student"><?=e($r['teacher_note']??'')?></textarea><button class="btn">Save review</button></form></article><?php endforeach;?></section><?php else:?><div class="empty">No <?=e($type)?> submissions found.</div><?php endif;?></main></body></html>
