<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';
const PROJECT_ARCHIVE_LIMIT=26214400;
const PROJECT_TOTAL_LIMIT=104857600;
const PROJECT_FILE_LIMIT=10485760;
function project_path(string $path): string {
 if($path===''||strlen($path)>500||!preg_match('//u',$path)||preg_match('~[\\\\\x00-\x1f\x7f:*?"<>|]~',$path)||str_starts_with($path,'/'))throw new InvalidArgumentException('Archive contains an unsafe file path.');
 $path=rtrim($path,'/');$parts=explode('/',$path);if(count($parts)>25)throw new InvalidArgumentException('Folder nesting exceeds 25 levels.');
 foreach($parts as $part)if($part===''||$part==='.'||$part==='..'||strlen($part)>200)throw new InvalidArgumentException('Invalid file or folder name.');return $path;
}
function project_student(array $user): array {
 $s=db()->prepare('SELECT department_id,campus_id FROM students WHERE user_id=?');$s->execute([$user['id']]);$r=$s->fetch();if(!$r)reply(403,['message'=>'Your student account needs a department and campus assignment.']);return $r;
}
function project_filter(array $user): array {
 $graduation=!empty($GLOBALS['graduation_mode']);$installed=function_exists('graduation_installed')?graduation_installed():false;
 if(!$installed){require_once __DIR__.'/graduation.php';$installed=graduation_installed();}
 $kind=$installed?($graduation?'EXISTS':'NOT EXISTS').'(SELECT 1 FROM graduation_submissions gs WHERE gs.project_id=p.id)':'1=1';
 if($graduation&&graduation_deletion_installed())$kind.=" AND NOT EXISTS(SELECT 1 FROM graduation_deleted_items x WHERE (x.entity_type='submission' AND x.entity_id=p.id) OR (x.entity_type='requirement' AND x.entity_id=(SELECT g.requirement_id FROM graduation_submissions g WHERE g.project_id=p.id)))";
 if(in_array($user['role'],['admin','staff'],true))return [$kind,[]];
 if($user['role']==='student')return [$kind.' AND p.student_user_id=?',[$user['id']]];
 if($user['role']==='hod')return [$kind.' AND EXISTS (SELECT 1 FROM hod_assignments h WHERE h.user_id=? AND h.department_id=p.department_id'.($graduation?'':' AND h.campus_id=p.campus_id').')',[$user['id']]];
 reply(403,['message'=>'This project workspace is unavailable for your account.']);
}
function project_get(array $user,int $id): array {
 [$where,$args]=project_filter($user);$s=db()->prepare('SELECT p.*,COALESCE(NULLIF(NULLIF(TRIM(u.full_name),\'null\'),\'\'),u.username) AS full_name,c.course_name FROM student_projects p JOIN users u ON u.id=p.student_user_id LEFT JOIN courses c ON c.id=p.course_id WHERE p.id=? AND '.$where);$s->execute(array_merge([$id],$args));$r=$s->fetch();if(!$r)reply(404,['message'=>'Project not found.']);return $r;
}
function project_root(array $p): string {
 // Keep project archives inside the application by default; explicit existing storage remains supported.
 $app=realpath(__DIR__.'/../..');
 $configured=trim(env_value('SLPS_PROJECT_STORAGE'));
 $shared=trim(env_value('SLPS_PRIVATE_STORAGE'));
 $base=$configured!==''?$configured:($shared!==''?$shared:$app.'/storage/private');
 $base=rtrim($base,'/\\');
 if(!is_dir($base)&&!mkdir($base,0700,true)&&!is_dir($base))throw new RuntimeException('Storage unavailable.');
 $real=realpath($base);$web=realpath($_SERVER['DOCUMENT_ROOT']??'')?:$app;
 $within=static function(string $path,string $parent): bool { $path=strtolower(str_replace('\\','/',$path));$parent=rtrim(strtolower(str_replace('\\','/',$parent)),'/');return $path===$parent||str_starts_with($path,$parent.'/'); };
 if($within($real,$web)||$within($real,$app)){
  // Only the bundled, server-protected directory may be used inside a public root.
  if(strtolower(str_replace('\\','/',$real))!==strtolower(str_replace('\\','/',$app.'/storage/private')))throw new RuntimeException('Use the protected storage/private directory for in-project storage.');
  $rules=is_file($real.'/.htaccess')?file_get_contents($real.'/.htaccess'):'';
  if(!str_contains($rules,'Require all denied'))throw new RuntimeException('Private storage protection is missing. Restore storage/private/.htaccess.');
 }
 $root=$real.'/student-projects';
 if(!is_dir($root)&&!mkdir($root,0700,true)&&!is_dir($root))throw new RuntimeException('Storage unavailable.');
 return $root.'/'.$p['storage_key'];
}
function project_manifest(string $root): array {if(!is_file($root.'/manifest.json'))return ['revision'=>0,'files'=>[],'updated_at'=>null,'updated_by'=>null];return json_decode(file_get_contents($root.'/manifest.json'),true,512,JSON_THROW_ON_ERROR);}
function project_write_manifest(string $root,array $m): void {$temp=$root.'/manifest-'.bin2hex(random_bytes(8));if(file_put_contents($temp,json_encode($m,JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE),LOCK_EX)===false||!rename($temp,$root.'/manifest.json'))throw new RuntimeException('Unable to save project.');}
function project_lock(string $root){$h=fopen($root.'/lock','c');if(!$h||!flock($h,LOCK_EX))throw new RuntimeException('Project is busy.');return $h;}
function project_blob(string $root,string $text): string {$hash=hash('sha256',$text);if(!is_file($root.'/blobs/'.$hash)&&file_put_contents($root.'/blobs/'.$hash,$text,LOCK_EX)===false)throw new RuntimeException('Unable to save file.');return $hash;}
function project_extract(array $p,array $user): array {
 $root=project_root($p);$lock=project_lock($root);try{$m=project_manifest($root);if($m['revision']>0)return $m;
 $files=[];$seen=[];$total=0;$count=0;
 $add=function(string $name,bool $dir,int $size,$stream,?string $crc=null)use(&$files,&$seen,&$total,&$count,$root){
  try{$path=project_path($name);$key=strtolower($path);if(isset($seen[$key]))throw new InvalidArgumentException('Duplicate archive paths are not supported.');$seen[$key]=true;if(++$count>3000)throw new InvalidArgumentException('Archive exceeds 3,000 entries.');
  if($size<0||$size>PROJECT_FILE_LIMIT||($total+=$size)>PROJECT_TOTAL_LIMIT)throw new InvalidArgumentException('Archive exceeds extraction limits: 10 MB per file, 100 MB total.');
  if($dir){$files[$path]=['directory'=>true,'size'=>0];return;}
  if(!is_resource($stream))throw new InvalidArgumentException('Cannot read archive entry; encrypted or unsupported archives are not accepted.');$content=stream_get_contents($stream,PROJECT_FILE_LIMIT+1);if($content===false||strlen($content)!==$size)throw new InvalidArgumentException('Invalid or oversized archive entry.');
  if($crc!==null&&strtolower(str_pad($crc,8,'0',STR_PAD_LEFT))!==hash('crc32b',$content))throw new InvalidArgumentException('Archive checksum failed.');$files[$path]=['directory'=>false,'size'=>$size,'blob'=>project_blob($root,$content)];
  }finally{if(is_resource($stream))fclose($stream);}
 };
 if($p['archive_type']==='zip'){
  if(!class_exists('ZipArchive'))throw new InvalidArgumentException('ZIP extraction requires the PHP zip extension. Ask your hosting administrator to enable it.');$z=new ZipArchive();if($z->open($root.'/original')!==true)throw new InvalidArgumentException('Invalid ZIP archive.');try{if($z->numFiles>3000)throw new InvalidArgumentException('Archive exceeds 3,000 entries.');for($i=0;$i<$z->numFiles;$i++){$s=$z->statIndex($i);$os=0;$attr=0;$z->getExternalAttributesIndex($i,$os,$attr);$type=($attr>>16)&0170000;if($os===3&&$type!==0&&$type!==0100000&&$type!==0040000)throw new InvalidArgumentException('Links and special files are not accepted.');if(($s['encryption_method']??0)!==0)throw new InvalidArgumentException('Password-protected archives are not accepted.');$dir=str_ends_with($s['name'],'/');$add($s['name'],$dir,(int)$s['size'],$dir?null:$z->getStream($s['name']),sprintf('%08x',$s['crc']));}}finally{$z->close();}
 }else{
  if(!class_exists('RarArchive'))throw new InvalidArgumentException('RAR extraction requires the PHP rar extension. Download the original or submit a ZIP instead.');$r=RarArchive::open($root.'/original');if(!$r)throw new InvalidArgumentException('Invalid RAR archive.');try{$entries=$r->getEntries();if($entries===false||count($entries)>3000)throw new InvalidArgumentException('Invalid archive or more than 3,000 entries.');foreach($entries as $e){if($e->isEncrypted())throw new InvalidArgumentException('Password-protected archives are not accepted.');$type=$e->getAttr()&0170000;if($e->getHostOs()===3&&$type!==0&&$type!==0100000&&$type!==0040000)throw new InvalidArgumentException('Links and special files are not accepted.');$add($e->getName(),$e->isDirectory(),$e->getUnpackedSize(),$e->isDirectory()?null:$e->getStream(),$e->getCrc());}}finally{$r->close();}
 }
 foreach(array_keys($files) as $path){$parent=dirname($path);while($parent!=='.'){if(isset($files[$parent])&&!$files[$parent]['directory'])throw new InvalidArgumentException('File and folder paths conflict.');$files[$parent]=['directory'=>true,'size'=>0];$parent=dirname($parent);}}
 $m=['revision'=>1,'files'=>$files,'updated_at'=>gmdate('c'),'updated_by'=>(int)$user['id']];project_write_manifest($root,$m);return $m;
 }finally{flock($lock,LOCK_UN);fclose($lock);}
}
function project_listing(array $m): array {$out=[];foreach($m['files'] as $path=>$f)$out[]=array_merge(['path'=>$path],array_diff_key($f,['blob'=>true]));return ['revision'=>$m['revision'],'entries'=>$out,'updated_at'=>$m['updated_at'],'updated_by'=>$m['updated_by']];}
