<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/config.php';require_once __DIR__ . '/../includes/db.php';require_once __DIR__ . '/../includes/functions.php';require_once __DIR__ . '/../includes/student-auth.php';
$pdo=db();
try{
 if(!isPost()||!isStudentLoggedIn())throw new RuntimeException('Unauthorized.');
 requireCsrf();$student=currentStudent($pdo);if(!$student)throw new RuntimeException('Unauthorized.');
 $examId=(int)($_POST['exam_id']??0);$code=strtoupper(trim((string)($_POST['exam_code']??'')));if($examId<=0)throw new RuntimeException('Exam is required.');
 $exam=safeFetch($pdo,"SELECT e.* FROM core_exams e INNER JOIN core_course_students cs ON cs.course_id=e.course_id AND cs.student_id=? AND cs.status IN ('active','approved','completed') WHERE e.id=? LIMIT 1",[(int)$student['id'],$examId]);
 if(!$exam)throw new RuntimeException('Exam not found or enrollment is inactive.');
 if((int)($exam['require_exam_code']??0)===1 && !hash_equals(strtoupper((string)($exam['exam_code']??'')),$code))throw new RuntimeException('Invalid exam code.');
 if(!in_array((string)($exam['status']??''),['open','active','published'],true))throw new RuntimeException('This exam is not open.');
 echo json_encode(['success'=>true,'message'=>'Exam code verified.','redirect'=>'../student/exams.php?view=lobby&course_id='.(int)$exam['course_id'].'&exam_id='.(int)$exam['id']],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}catch(Throwable $e){http_response_code(422);echo json_encode(['success'=>false,'message'=>$e->getMessage()],JSON_UNESCAPED_UNICODE);}
