<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';require_once __DIR__.'/../lib/practical_exams.php';require_once __DIR__.'/../lib/transcripts.php';require_once __DIR__.'/../lib/system_settings.php';
try{
 if(($_SERVER['REQUEST_METHOD']??'GET')==='GET'){
  $token=(string)($_GET['token']??'');if(!transcript_token_valid($token))reply(404,['message'=>'Transcript verification link is invalid.']);
  $q=db()->prepare('SELECT id,issued_at,student_user_id,snapshot_json FROM practical_transcripts WHERE token_hash=?');$q->execute([hash('sha256',$token)]);$t=$q->fetch();if(!$t)reply(404,['message'=>'Transcript verification link was not found.']);$snapshot=json_decode($t['snapshot_json'],true,512,JSON_THROW_ON_ERROR);
  $ids=array_column($snapshot['results'],'exam_id');if(!$ids)reply(410,['message'=>'This transcript has no verifiable results.']);$q=db()->prepare('SELECT exam_id,revision,published_at FROM practical_exam_results WHERE student_user_id=? AND exam_id IN ('.implode(',',array_fill(0,count($ids),'?')).')');$q->execute(array_merge([(int)$t['student_user_id']],$ids));if(!transcript_sources_match($snapshot,$q->fetchAll()))reply(410,['message'=>'This transcript has been superseded or its results are awaiting republication. Ask the student or university to issue a new transcript.']);
  reply(200,['transcript'=>$snapshot,'reference'=>'RVU-PR-'.str_pad((string)$t['id'],7,'0',STR_PAD_LEFT),'issued_at'=>$t['issued_at'],'verified'=>true,'public_url'=>(string)(platform_settings()['public_url']??'')]);
 }
 if(($_SERVER['REQUEST_METHOD']??'')!=='POST')reply(405,['message'=>'Use GET or POST.']);$user=require_auth();$data=post_data(10000);$exam=practical_exam_get($user,(int)($data['exam_id']??0));$student=$user['role']==='student'?(int)$user['id']:(int)($data['student_user_id']??0);
 rate_limit('transcript-issue',(string)$user['id'],60,3600);
 $q=db()->prepare('SELECT student_user_id FROM practical_exam_results WHERE exam_id=? AND student_user_id=? AND published_at IS NOT NULL');$q->execute([$exam['id'],$student]);if(!$q->fetch())reply(404,['message'=>'Publish the student result before issuing a transcript.']);
 $db=db();$db->beginTransaction();try{
  [$where,$args]=practical_exam_scope($user);$sql='SELECT e.id exam_id,e.title,e.academic_period,e.course_id,e.campus_id,c.course_name,c.course_code,ca.campus_name,r.level_one,r.level_two,r.final_exam,r.revision,r.published_at FROM practical_exam_results r JOIN practical_exams e ON e.id=r.exam_id JOIN courses c ON c.id=e.course_id JOIN campuses ca ON ca.id=e.campus_id WHERE r.student_user_id=? AND e.academic_period=? AND r.published_at IS NOT NULL AND '.$where.' ORDER BY c.course_code,e.id';$q=$db->prepare($sql);$q->execute(array_merge([$student,$exam['academic_period']],$args));$results=$q->fetchAll();if(!$results)throw new InvalidArgumentException('No published results are available.');foreach($results as &$r)$r=array_merge($r,practical_exam_grade($r));unset($r);
  $q=$db->prepare("SELECT COALESCE(NULLIF(u.full_name,''),u.username) full_name,s.student_number,d.department_name,ca.campus_name,s.year_of_study FROM users u JOIN students s ON s.user_id=u.id JOIN departments d ON d.id=s.department_id JOIN campuses ca ON ca.id=s.campus_id WHERE u.id=?");$q->execute([$student]);$profile=$q->fetch();if(!$profile)throw new InvalidArgumentException('Student profile is unavailable.');
  $snapshot=['student'=>$profile,'academic_period'=>$exam['academic_period'],'results'=>$results,'scope'=>$user['role']==='hod'?'Published practical examinations within the issuing HOD’s department and campus.':'Published practical examinations available at issue for this academic period.','timezone'=>'Africa/Lusaka'];$token=bin2hex(random_bytes(32));$db->prepare('INSERT INTO practical_transcripts(token_hash,student_user_id,issued_by,snapshot_json) VALUES(?,?,?,?)')->execute([hash('sha256',$token),$student,$user['id'],json_encode($snapshot,JSON_THROW_ON_ERROR)]);$id=$db->lastInsertId();audit_event((int)$user['id'],$user['role'],'practical_transcript',$id,'issue_transcript','Issued published practical results transcript');$db->commit();
 }catch(Throwable $e){if($db->inTransaction())$db->rollBack();throw $e;}
 $base=trim((string)(platform_settings()['public_url']??''));reply(201,['token'=>$token,'path'=>app_path().'/shared/views/transcript.php?token='.$token,'public_url'=>$base]);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('Transcript: '.$e->getMessage());reply(503,['message'=>'Transcript service is unavailable. Check the practical transcript migration and database connection.']);}
