<?php
declare(strict_types=1);
require_once __DIR__.'/student_projects.php';
function graduation_installed(): bool {static $ready=null;if($ready!==null)return $ready;try{db()->query('SELECT project_id FROM graduation_submissions LIMIT 0');return $ready=true;}catch(Throwable $e){return $ready=false;}}
// Check the publishing schema, not just the presence of one graduation table.
function graduation_schema_issues(array $columns): array {
 $issues=[];foreach(['graduation_requirements'=>['id','department_id','course_id','requirements','requirements_delta','deadline','created_by'],'graduation_requirement_years'=>['requirement_id','year_of_study'],'graduation_submissions'=>['project_id','requirement_id'],'graduation_reviews'=>['project_id','action'],'student_projects'=>['course_id']] as $table=>$fields){foreach($fields as $field)if(!isset($columns[$table][$field]))$issues[]=$table.'.'.$field;}
 foreach(['graduation_requirements','student_projects'] as $table)if(isset($columns[$table]['course_id'])&&$columns[$table]['course_id']!=='YES')$issues[]=$table.'.course_id must allow NULL';return $issues;
}
function graduation_check_schema(): array {
 $q=db()->query("SELECT TABLE_NAME,COLUMN_NAME,IS_NULLABLE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME IN ('graduation_requirements','graduation_requirement_years','graduation_submissions','graduation_reviews','student_projects')");$columns=[];foreach($q->fetchAll() as $row)$columns[$row['TABLE_NAME']][$row['COLUMN_NAME']]=$row['IS_NULLABLE'];return graduation_schema_issues($columns);
}
function graduation_error_message(Throwable $e,string $reference): string {
 $code=(int)$e->getCode();if(in_array($code,[1054,1146,1048,1364],true))return 'A database table or column does not match this version. Import database/migrations/20261017_graduation_complete_repair.sql into the database used by SLPS. Reference: '.$reference;
 if($code===1406)return 'A project field is too long for the installed database column. Contact the system administrator. Reference: '.$reference;
 if(in_array($code,[1205,1213],true))return 'The project is busy. Please try publishing again. Reference: '.$reference;
 return 'The project could not be published or updated. Your entered text is still available. Ask the administrator to check the PHP error log for reference '.$reference.'.';
}
function graduation_deletion_installed(): bool {static $ready=null;if($ready!==null)return $ready;try{db()->query('SELECT entity_id FROM graduation_deleted_items LIMIT 0');return $ready=true;}catch(Throwable $e){return $ready=false;}}
function graduation_visible(string $alias='r'): string {return graduation_deletion_installed()?"NOT EXISTS(SELECT 1 FROM graduation_deleted_items x WHERE x.entity_type='requirement' AND x.entity_id=".$alias.'.id)':'1=1';}
function graduation_can_delete(array $user,int $creator): bool {return in_array($user['role'],['staff','admin'],true)||($user['role']==='hod'&&(int)$user['id']===$creator);}
function graduation_scope(array $user,string $alias='r'): array {
 if(in_array($user['role'],['staff','admin'],true))return ['1=1',[]];
 if($user['role']==='hod')return ['EXISTS(SELECT 1 FROM hod_assignments h WHERE h.user_id=? AND h.department_id='.$alias.'.department_id)',[$user['id']]];
 if($user['role']==='student')return ['EXISTS(SELECT 1 FROM students s JOIN graduation_requirement_years y ON y.year_of_study=s.year_of_study AND y.requirement_id='.$alias.'.id WHERE s.user_id=? AND s.department_id='.$alias.'.department_id)',[$user['id']]];
 throw new InvalidArgumentException('This account cannot access graduation projects.');
}
function graduation_requirement(array $user,int $id): array {
 [$where,$args]=graduation_scope($user);$q=db()->prepare('SELECT r.*,c.course_name,d.department_name FROM graduation_requirements r LEFT JOIN courses c ON c.id=r.course_id JOIN departments d ON d.id=r.department_id WHERE r.id=? AND '.graduation_visible().' AND '.$where);$q->execute(array_merge([$id],$args));$r=$q->fetch();if(!$r)throw new InvalidArgumentException('Requirement not found for your department and year.');return $r;
}
function graduation_block(array $user,array $r): ?string {
 if($user['role']!=='student')return 'Instructor view';if(strtotime($r['deadline'].' UTC')<time())return 'Submission deadline has passed.';
 $q=db()->prepare('SELECT status FROM graduation_submissions s WHERE requirement_id=? AND student_user_id=?'.(graduation_deletion_installed()?" AND NOT EXISTS(SELECT 1 FROM graduation_deleted_items x WHERE x.entity_type='submission' AND x.entity_id=s.project_id)":'').' ORDER BY attempt DESC LIMIT 1');$q->execute([$r['id'],$user['id']]);$state=$q->fetchColumn();if($state&&$state!=='rejected')return 'A submission is already '.str_replace('_',' ',$state).'.';
 for($stage=1;$stage<(int)$r['stage'];$stage++){$q=db()->prepare("SELECT 1 FROM graduation_submissions s JOIN graduation_requirements p ON p.id=s.requirement_id WHERE s.student_user_id=? AND p.department_id=? AND p.academic_period=? AND p.stage=? AND s.status='approved' AND ".graduation_visible('p').(graduation_deletion_installed()?" AND NOT EXISTS(SELECT 1 FROM graduation_deleted_items x WHERE x.entity_type='submission' AND x.entity_id=s.project_id)":'')." LIMIT 1");$q->execute([$user['id'],$r['department_id'],$r['academic_period'],$stage]);if(!$q->fetchColumn())return 'Complete and receive approval for project '.$stage.' first.';}return null;
}
function graduation_upload_link(int $projectId,array $user): void {
 $id=(int)($_POST['requirement_id']??0);$q=db()->prepare('SELECT id FROM graduation_requirements WHERE id=? FOR UPDATE');$q->execute([$id]);$q->fetch();$r=graduation_requirement($user,$id);$blocked=graduation_block($user,$r);if($blocked)throw new InvalidArgumentException($blocked);
 $q=db()->prepare('SELECT COALESCE(MAX(attempt),0)+1 FROM graduation_submissions WHERE requirement_id=? AND student_user_id=?');$q->execute([$id,$user['id']]);$attempt=(int)$q->fetchColumn();db()->prepare('INSERT INTO graduation_submissions(project_id,requirement_id,student_user_id,attempt) VALUES(?,?,?,?)')->execute([$projectId,$id,$user['id'],$attempt]);
 db()->prepare("INSERT INTO notifications(recipient_user_id,kind,title,message,link,created_by) VALUES(?,'graduation',?,?,?,?)")->execute([$r['created_by'],'Graduation project submitted',$user['full_name'].' submitted '.$r['title'].'.',app_path().'/shared/views/modules/way-to-graduate.php?project='.$projectId,$user['id']]);
}
function graduation_assert_editable(array $p,array $user): void {
 if($user['role']!=='student'||(int)$p['student_user_id']!==(int)$user['id'])throw new InvalidArgumentException('Instructors review student files without modifying their source.');
 $q=db()->prepare('SELECT g.status,r.deadline FROM graduation_submissions g JOIN graduation_requirements r ON r.id=g.requirement_id WHERE g.project_id=?');$q->execute([$p['id']]);$state=$q->fetch();if($state&&strtotime($state['deadline'].' UTC')<time())throw new InvalidArgumentException('The submission deadline has passed; editing is closed.');if(!$state||$state['status']!=='submitted')throw new InvalidArgumentException('This attempt is locked after verification. Rejected projects must be resubmitted as a new archive.');
}
function graduation_transition(string $status,string $action,string $reason): string {
 if(strlen(trim($reason))<10||strlen($reason)>5000)throw new InvalidArgumentException('Enter a clear reason or defence record of 10–5000 characters.');
 if($action==='verify'&&$status==='submitted')return 'verified';
 if(in_array($action,['defence_pass','defence_fail'],true)&&$status==='verified')return $action==='defence_pass'?'defended_pass':'defended_fail';
 if($action==='approve'&&$status==='defended_pass')return 'approved';
 if($action==='reject'&&in_array($status,['submitted','verified','defended_pass','defended_fail'],true))return 'rejected';
 throw new InvalidArgumentException('This action is not available at the current stage. Verify the files, record a successful defence, then approve.');
}
function graduation_file_locked(int $id): bool {$q=db()->prepare('SELECT status FROM graduation_submissions WHERE project_id=?');$q->execute([$id]);return $q->fetchColumn()!=='submitted';}
function graduation_datetime(mixed $value,bool $future): DateTimeImmutable {
 if(!is_string($value)||!preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/D',$value))throw new InvalidArgumentException('Choose a valid date and time.');
 try{$date=new DateTimeImmutable($value);}catch(Throwable $e){throw new InvalidArgumentException('Invalid date and time.');}
 $errors=DateTimeImmutable::getLastErrors();if($errors&&($errors['warning_count']||$errors['error_count']))throw new InvalidArgumentException('Invalid calendar date.');
 if($future&&$date<=new DateTimeImmutable('now'))throw new InvalidArgumentException('Choose a future deadline.');
 if(!$future&&$date>new DateTimeImmutable('now'))throw new InvalidArgumentException('Record a completed defence, not a future appointment.');return $date->setTimezone(new DateTimeZone('UTC'));
}
