<?php
declare(strict_types=1);
require_once __DIR__.'/../lib/project_grading.php';
$user=require_auth();project_filter($user);
try{
 $method=$_SERVER['REQUEST_METHOD']??'GET';$action=$_GET['action']??'list';
 if($method==='POST'&&$action==='upload'){
  if(!hash_equals($_SESSION['csrf_token'],$_SERVER['HTTP_X_CSRF_TOKEN']??''))reply(403,['message'=>'Your form session expired. Refresh and try again.']);
  if($user['role']!=='student')reply(403,['message'=>'Only students can submit projects.']);rate_limit('student-project-upload',(string)$user['id'],10,3600);
  $student=project_student($user);$title=text_field($_POST,'title',160);$description=text_field($_POST,'description',5000);$course=(int)($_POST['course_id']??0);$tech=json_decode($_POST['technologies']??'[]',true);if(!$title||!is_array($tech)||count($tech)<1||count($tech)>20)throw new InvalidArgumentException('Enter a title and select 1–20 languages or frameworks.');foreach($tech as $t)if(!is_string($t)||strlen($t)>60||trim($t)==='')throw new InvalidArgumentException('Invalid language or framework.');
  if(empty($GLOBALS['graduation_mode'])){$s=db()->prepare('SELECT id FROM courses WHERE id=? AND department_id=? AND is_active=1');$s->execute([$course,$student['department_id']]);if(!$s->fetch())throw new InvalidArgumentException('Select an active course in your department.');}else{$course=null;}
  $f=$_FILES['archive']??null;if(!$f||$f['error']!==UPLOAD_ERR_OK)throw new InvalidArgumentException('Upload failed. Select an archive and check the server upload limits.');if($f['size']<1||$f['size']>PROJECT_ARCHIVE_LIMIT)throw new InvalidArgumentException('Choose a ZIP or RAR archive up to 25 MB.');$name=basename(str_replace('\\','/',$f['name']));$ext=strtolower(pathinfo($name,PATHINFO_EXTENSION));$sig=file_get_contents($f['tmp_name'],false,null,0,8);if(!in_array($ext,['zip','rar'],true)||($ext==='zip'&&!str_starts_with($sig,"PK\x03\x04")&&!str_starts_with($sig,"PK\x05\x06"))||($ext==='rar'&&!str_starts_with($sig,"Rar!\x1a\x07")))throw new InvalidArgumentException('The file must be a valid ZIP or RAR archive.');
  $key=bin2hex(random_bytes(24));$root=project_root(['storage_key'=>$key]);if(!mkdir($root,0700)||!mkdir($root.'/blobs',0700)||!move_uploaded_file($f['tmp_name'],$root.'/original'))throw new RuntimeException('Unable to store submission.');
  $graduation=!empty($GLOBALS['graduation_mode']);if($graduation)db()->beginTransaction();
  try{$s=db()->prepare('INSERT INTO student_projects (student_user_id,course_id,department_id,campus_id,title,description,technologies,archive_name,archive_type,storage_key) VALUES (?,?,?,?,?,?,?,?,?,?)');$s->execute([$user['id'],$course,$student['department_id'],$student['campus_id'],$title,$description,json_encode(array_values(array_unique($tech))),substr($name,0,255),$ext,$key]);$id=db()->lastInsertId();if($graduation){graduation_upload_link($id,$user);db()->commit();}}catch(Throwable $e){if($graduation&&db()->inTransaction())db()->rollBack();unlink($root.'/original');rmdir($root.'/blobs');rmdir($root);throw $e;}
  reply(201,['message'=>'Project submitted successfully.','id'=>$id]);
 }
 if($method==='GET'&&$action==='list'){
  [$where,$args]=project_filter($user);$s=db()->prepare('SELECT p.id,p.title,p.description,p.technologies,p.archive_name,p.archive_type,p.created_at,' . "COALESCE(NULLIF(NULLIF(TRIM(u.full_name),'null'),''),u.username)" . ' AS full_name,c.course_name,d.department_name FROM student_projects p JOIN users u ON u.id=p.student_user_id JOIN courses c ON c.id=p.course_id JOIN departments d ON d.id=p.department_id WHERE '.$where.' ORDER BY p.id DESC LIMIT 200');$s->execute($args);$projects=$s->fetchAll();$gradeMap=student_project_grade_map(array_column($projects,'id'));foreach($projects as &$item)$item['grade']=$gradeMap[(int)$item['id']]??null;unset($item);$courses=[];
  if($user['role']==='student'){$st=project_student($user);$q=db()->prepare('SELECT id,course_name FROM courses WHERE department_id=? AND is_active=1 ORDER BY course_name');$q->execute([$st['department_id']]);$courses=$q->fetchAll();}
  reply(200,['projects'=>$projects,'courses'=>$courses,'can_submit'=>$user['role']==='student','capabilities'=>['zip'=>class_exists('ZipArchive'),'rar'=>class_exists('RarArchive')],'limit'=>200]);
 }
 $data=$method==='POST'?post_data(6500000):$_GET;$p=project_get($user,(int)($data['id']??0));$root=project_root($p);
 if($method==='GET'&&$action==='project'){unset($p['storage_key']);reply(200,['project'=>$p,'grade'=>student_project_grade((int)$p['id']),'can_grade'=>in_array($user['role'],['admin','staff','hod'],true)]);}
 if($method==='GET'&&$action==='grade')reply(200,['grade'=>student_project_grade((int)$p['id']),'can_grade'=>in_array($user['role'],['admin','staff','hod'],true)]);
 if($method==='POST'&&$action==='grade'){
  if(!in_array($user['role'],['admin','staff','hod'],true))reply(403,['message'=>'Only authorised HODs and administrators can grade projects.']);
  $score=student_project_score($data['score']??null);$feedback=text_field($data,'feedback',5000);$lock=project_lock($root);
  try{$m=project_manifest($root);if((int)($data['revision']??-1)!==(int)$m['revision'])reply(409,['message'=>'Project files changed. Refresh and review the latest version before grading.']);
   db()->beginTransaction();try{$q=db()->prepare('SELECT id FROM student_projects WHERE id=? FOR UPDATE');$q->execute([$p['id']]);$existing=student_project_grade((int)$p['id']);if((int)($data['version']??0)!==(int)($existing['version']??0)){db()->rollBack();reply(409,['message'=>'Another marker updated this grade. Reopen the grade form before publishing.']);}$version=(int)($existing['version']??0)+1;
    $q=db()->prepare('INSERT INTO student_project_grades(project_id,score,feedback,graded_by,graded_revision,version) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE score=VALUES(score),feedback=VALUES(feedback),graded_by=VALUES(graded_by),graded_revision=VALUES(graded_revision),version=VALUES(version),graded_at=CURRENT_TIMESTAMP');$q->execute([$p['id'],$score,$feedback,$user['id'],$m['revision'],$version]);
    $q=db()->prepare('INSERT INTO student_project_grade_history(project_id,score,feedback,graded_by,graded_revision,version) VALUES (?,?,?,?,?,?)');$q->execute([$p['id'],$score,$feedback,$user['id'],$m['revision'],$version]);
    $band=student_project_band($score);$q=db()->prepare("INSERT INTO notifications(recipient_user_id,kind,title,message,link,created_by) VALUES (?,'project_grade',?,?,?,?)");$q->execute([$p['student_user_id'],'Project grade published',$p['title'].': '.$score.'% · '.$band['letter'].' ('.$band['outcome'].'). '.$feedback,app_path().'/shared/views/modules/student-projects.php?project='.$p['id'].'&grade=1',$user['id']]);db()->commit();
   }catch(Throwable $e){if(db()->inTransaction())db()->rollBack();throw $e;}
  }finally{flock($lock,LOCK_UN);fclose($lock);}reply(200,['grade'=>student_project_grade((int)$p['id']),'message'=>'Grade published. The student has been notified.']);
 }

 if($method==='GET'&&$action==='original'){header('Content-Type: application/octet-stream');header("Content-Disposition: attachment; filename=\"project-original.".$p['archive_type']."\"; filename*=UTF-8''".rawurlencode($p['archive_name']));header('X-Content-Type-Options: nosniff');header('Cache-Control: no-store');readfile($root.'/original');exit;}
 if($method==='POST'&&$action==='extract')reply(200,project_listing(project_extract($p,$user)));
 $m=project_manifest($root);
 if($method==='GET'&&$action==='tree')reply(200,project_listing($m));
 if($method==='GET'&&$action==='export'){
  if(!$m['revision'])throw new InvalidArgumentException('Extract the project first.');if(!class_exists('ZipArchive'))throw new InvalidArgumentException('Enable PHP ZIP to export projects.');$temp=tempnam($root,'export-');$z=new ZipArchive();if($z->open($temp,ZipArchive::OVERWRITE)!==true)throw new RuntimeException('Export unavailable.');try{foreach($m['files'] as $path=>$f){if($f['directory'])$z->addEmptyDir($path);else $z->addFile($root.'/blobs/'.$f['blob'],$path);}if(!$z->close())throw new RuntimeException('Export failed.');header('Content-Type: application/zip');header('Content-Disposition: attachment; filename="project-'.$p['id'].'-edited.zip"');header('X-Content-Type-Options: nosniff');header('Cache-Control: no-store');readfile($temp);}finally{unlink($temp);}exit;
 }
 $path=project_path((string)($data['path']??''));$f=$m['files'][$path]??null;if(!$f||$f['directory'])reply(404,['message'=>'File not found.']);
 if($method==='GET'&&$action==='download'){header('Content-Type: application/octet-stream');header("Content-Disposition: attachment; filename=\"project-file\"; filename*=UTF-8''".rawurlencode(basename($path)));header('X-Content-Type-Options: nosniff');header('Cache-Control: no-store');readfile($root.'/blobs/'.$f['blob']);exit;}
 if($method==='GET'&&$action==='file'){
  if($f['size']>1048576)reply(200,['editable'=>false,'message'=>'Files above 1 MB can be downloaded but cannot be edited here.']);$text=file_get_contents($root.'/blobs/'.$f['blob']);if(str_contains($text,"\0")||!preg_match('//u',$text))reply(200,['editable'=>false,'message'=>'Binary or non-UTF-8 file. Download it to open locally.']);reply(200,['readonly'=>!empty($GLOBALS['graduation_mode'])&&($user['role']!=='student'||graduation_file_locked((int)$p['id'])),'editable'=>true,'content'=>$text,'hash'=>$f['blob'],'revision'=>$m['revision']]);
 }
 if($method==='POST'&&$action==='save'){
  $content=$data['content']??null;if(!is_string($content)||strlen($content)>1048576||str_contains($content,"\0")||!preg_match('//u',$content))throw new InvalidArgumentException('Use UTF-8 text up to 1 MB.');$lock=project_lock($root);try{if(!empty($GLOBALS['graduation_mode']))graduation_assert_editable($p,$user);$m=project_manifest($root);$current=$m['files'][$path]??null;if(!$current||$current['directory'])reply(404,['message'=>'File not found.']);if(!hash_equals($current['blob'],(string)($data['hash']??'')))reply(409,['message'=>'This file changed since you opened it. Reopen the file to load the latest version before saving.']);$total=array_sum(array_column($m['files'],'size'))-$current['size']+strlen($content);if($total>PROJECT_TOTAL_LIMIT)throw new InvalidArgumentException('Project exceeds 100 MB.');$hash=project_blob($root,$content);$m['files'][$path]=['directory'=>false,'size'=>strlen($content),'blob'=>$hash];$m['revision']++;$m['updated_at']=gmdate('c');$m['updated_by']=(int)$user['id'];project_write_manifest($root,$m);}finally{flock($lock,LOCK_UN);fclose($lock);}reply(200,['hash'=>$hash,'revision'=>$m['revision'],'message'=>'Changes saved.']);
 }
 reply(405,['message'=>'Unsupported action.']);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('SLPS student projects: '.get_class($e).' '.$e->getMessage());reply(503,['message'=>'Students Projects is unavailable. Ask your administrator to apply the student projects migration and check private storage permissions.']);}
