<?php
declare(strict_types=1);
require_once __DIR__.'/../lib/project_collaborations.php';
$user=require_auth();
if(!in_array($user['role'],['admin','student','hod','staff'],true))reply(403,['message'=>'Access denied.']);
try {
 $method=$_SERVER['REQUEST_METHOD']??'GET';$action=$_GET['action']??'list';$data=$_GET;
 if($method==='POST'){
  if(str_starts_with($_SERVER['CONTENT_TYPE']??'','multipart/form-data')){if(!hash_equals($_SESSION['csrf_token'],$_SERVER['HTTP_X_CSRF_TOKEN']??''))reply(403,['message'=>'Refresh the page and try again.']);$data=$_POST;}
  else $data=post_data(6500000);
 }elseif($method!=='GET')reply(405,['message'=>'Use GET or POST.']);
 if($action==='set_department'&&$method==='POST'){
  if(!in_array($user['role'],['admin','staff'],true))reply(403,['message'=>'Only administrators configure their department.']);$dept=(int)($data['department_id']??0);$q=db()->prepare('SELECT id FROM departments WHERE id=? AND is_active=1');$q->execute([$dept]);if(!$q->fetch())throw new InvalidArgumentException('Select an active department.');$q=db()->prepare('INSERT INTO collaboration_admin_departments(user_id,department_id) VALUES (?,?) ON DUPLICATE KEY UPDATE department_id=VALUES(department_id)');$q->execute([$user['id'],$dept]);reply(200,['message'=>'Department saved.']);
 }
 if($action==='students'&&$method==='GET'){
  if(!in_array($user['role'],['admin','staff'],true))reply(403,['message'=>'Only administrators manage members.']);$dept=collaboration_department($user);$departments=db()->query('SELECT id,department_name FROM departments WHERE is_active=1 ORDER BY department_name')->fetchAll();
  if(!$dept&&$user['role']!=='staff')reply(200,['students'=>[],'total'=>0,'department_id'=>null,'departments'=>$departments,'next_offset'=>null]);
  $term=trim(substr((string)($_GET['q']??''),0,150));$offset=max(0,min(10000000,(int)($_GET['offset']??0)));$args=[$dept,'%'.$term.'%','%'.$term.'%'];$where="u.role='student' AND u.is_active=1 AND s.department_id=? AND (u.full_name LIKE ? OR u.username LIKE ?)";
  if($user['role']==='staff'){$where="u.role='student' AND u.is_active=1 AND (u.full_name LIKE ? OR u.username LIKE ?)";$args=['%'.$term.'%','%'.$term.'%'];}
  $q=db()->prepare('SELECT COUNT(*) FROM users u JOIN students s ON s.user_id=u.id WHERE '.$where);$q->execute($args);$total=(int)$q->fetchColumn();
  $q=db()->prepare('SELECT u.id,'.collaboration_name_sql().' AS full_name,u.username FROM users u JOIN students s ON s.user_id=u.id WHERE '.$where.' ORDER BY full_name,u.id LIMIT 100 OFFSET '.$offset);$q->execute($args);$rows=$q->fetchAll();reply(200,['students'=>$rows,'total'=>$total,'all_departments'=>$user['role']==='staff','department_id'=>$dept,'departments'=>$departments,'next_offset'=>$offset+count($rows)<$total?$offset+count($rows):null]);
 }
 if($action==='list'&&$method==='GET'){
  $q=db()->prepare("SELECT p.*,".collaboration_name_sql()." AS full_name,u.username AS administrator_username,(SELECT COUNT(*) FROM collaboration_members m WHERE m.project_id=p.id) AS member_count FROM collaboration_projects p JOIN users u ON u.id=p.created_by WHERE NOT EXISTS (SELECT 1 FROM collaboration_deleted_projects x WHERE x.project_id=p.id) AND (? IN ('admin','staff') OR EXISTS (SELECT 1 FROM collaboration_members m WHERE m.project_id=p.id AND m.user_id=?)) ORDER BY p.id DESC LIMIT 200");$q->execute([$user['role'],$user['id']]);$rows=$q->fetchAll();foreach($rows as &$p){$m=project_manifest(project_root($p));$p['updated_at']=$m['updated_at'];$p['updated_by_name']=$m['updated_by_name']??null;}unset($p);reply(200,['projects'=>$rows,'can_create'=>in_array($user['role'],['admin','staff'],true)]);
 }
 if($action==='create'&&$method==='POST'){
  if(!in_array($user['role'],['admin','staff'],true))reply(403,['message'=>'Only administrators create projects.']);
  $title=text_field($data,'title',160);$description=text_field($data,'description',5000);if(!$title)throw new InvalidArgumentException('Enter a project title.');
  $key=bin2hex(random_bytes(24));$root=project_root(['storage_key'=>$key]);if(!mkdir($root,0700)||!mkdir($root.'/blobs',0700))throw new RuntimeException('Storage unavailable.');
  $m=['revision'=>1,'files'=>[],'activity'=>[],'updated_at'=>gmdate('c'),'updated_by'=>(int)$user['id'],'updated_by_name'=>$user['full_name']?:($user['username']??'Administrator')];project_write_manifest($root,$m);
  try{$q=db()->prepare('INSERT INTO collaboration_projects(title,description,created_by,storage_key) VALUES (?,?,?,?)');$q->execute([$title,$description,$user['id'],$key]);}catch(Throwable $e){@unlink($root.'/manifest.json');@rmdir($root.'/blobs');@rmdir($root);throw $e;}
  reply(201,['id'=>db()->lastInsertId(),'message'=>'Project created. Add students in Manage members.']);
 }
 $p=collaboration_get($user,(int)($data['id']??0));$root=project_root($p);
 if(in_array($action,['rename_project','delete_project'],true)&&$method==='POST'){
  if(!in_array($user['role'],['admin','staff'],true))reply(403,['message'=>'Only administrators rename or delete projects.']);$lock=project_lock($root);
  try{$p=collaboration_get($user,(int)$p['id']);if(($data['expected_title']??'')!==$p['title'])reply(409,['message'=>'The project was renamed. Refresh the list and retry.']);
   if($action==='rename_project'){$title=text_field($data,'title',160);if(!$title)throw new InvalidArgumentException('Enter a project name.');$q=db()->prepare('UPDATE collaboration_projects SET title=? WHERE id=?');$q->execute([$title,$p['id']]);}
   else{$q=db()->prepare('INSERT INTO collaboration_deleted_projects(project_id,deleted_by) VALUES (?,?)');$q->execute([$p['id'],$user['id']]);}
   audit_event((int)$user['id'],(string)$user['role'],'collaboration_project',(int)$p['id'],$action,$p['title']);
  }finally{flock($lock,LOCK_UN);fclose($lock);}reply(200,['message'=>$action==='rename_project'?'Project renamed.':'Project deleted.']);
 }

 if($action==='members'&&$method==='GET'){
  $q=db()->prepare('SELECT u.id,'.collaboration_name_sql().' AS full_name,u.username,m.added_at FROM collaboration_members m JOIN users u ON u.id=m.user_id WHERE m.project_id=? ORDER BY full_name');$q->execute([$p['id']]);reply(200,['members'=>$q->fetchAll()]);
 }
 if(in_array($action,['add_member','remove_member'],true)&&$method==='POST'){
  if(!in_array($user['role'],['admin','staff'],true))reply(403,['message'=>'Only administrators manage members.']);$uid=(int)($data['user_id']??0);
  if($action==='add_member'){$q=db()->prepare("SELECT u.id FROM users u JOIN students s ON s.user_id=u.id WHERE u.id=? AND u.role='student' AND u.is_active=1 AND (?=1 OR s.department_id=?)");$q->execute([$uid,$user['role']==='staff'?1:0,collaboration_department($user)??0]);if(!$q->fetch())throw new InvalidArgumentException('Choose an active student in your department.');$q=db()->prepare('INSERT IGNORE INTO collaboration_members(project_id,user_id,added_by) VALUES (?,?,?)');$q->execute([$p['id'],$uid,$user['id']]);}
  else{$q=db()->prepare('DELETE FROM collaboration_members WHERE project_id=? AND user_id=?');$q->execute([$p['id'],$uid]);}
  reply(200,['message'=>$action==='add_member'?'Student added.':'Student removed.']);
 }
 if($action==='project'&&$method==='GET'){$q=db()->prepare('SELECT COUNT(*) AS total FROM collaboration_members WHERE project_id=?');$q->execute([$p['id']]);$p['member_count']=(int)$q->fetchColumn();unset($p['storage_key']);reply(200,['project'=>$p,'can_create'=>in_array($user['role'],['admin','staff'],true)]);}
 $m=project_manifest($root);
 if($method==='GET'&&in_array($action,['history','change'],true)){
  $path=project_path((string)($data['path']??''));$f=$m['files'][$path]??null;if(!$f||$f['directory'])reply(404,['message'=>'File not found.']);
  if($action==='history')reply(200,['history'=>collaboration_history($m,$path),'hash'=>$f['blob'],'revision'=>$m['revision']]);
  $index=filter_var($data['event']??null,FILTER_VALIDATE_INT);$event=$index!==false&&$index!==null?($m['activity'][$index]??null):null;
  if(!$event||$event['path']!==$path||!isset($event['before_blob'],$event['after_blob'],$event['line_changes']))reply(404,['message'=>'Line details are unavailable for this older contribution.']);
  reply(200,collaboration_diff_preview($event,$root));
 }
 if($method==='GET'&&$action==='tree')reply(200,collaboration_listing($m));
 if($method==='GET'&&$action==='export'){
  if(!class_exists('ZipArchive'))throw new InvalidArgumentException('Enable the PHP ZIP extension to download a project ZIP.');$temp=tempnam($root,'export-');$z=new ZipArchive();
  try{if($z->open($temp,ZipArchive::OVERWRITE)!==true)throw new RuntimeException('Export unavailable.');foreach($m['files'] as $path=>$entry){if($entry['directory'])$z->addEmptyDir($path);else $z->addFile($root.'/blobs/'.$entry['blob'],$path);}if(!$z->close())throw new RuntimeException('Export failed.');header('Content-Type: application/zip');header('Content-Disposition: attachment; filename="collaboration-'.$p['id'].'.zip"');header('X-Content-Type-Options: nosniff');header('Cache-Control: no-store');readfile($temp);}finally{@unlink($temp);}exit;
 }
 if($method==='GET'&&in_array($action,['file','download'],true)){
  $path=project_path((string)($data['path']??''));$f=$m['files'][$path]??null;if(!$f||$f['directory'])reply(404,['message'=>'File not found.']);
  if($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($f['size']>1048576)reply(200,['editable'=>false,'message'=>'Download files above 1 MB to open locally.']);$content=file_get_contents($root.'/blobs/'.$f['blob']);if(str_contains($content,"\0")||!preg_match('//u',$content))reply(200,['editable'=>false,'message'=>'Binary file. Download to open locally.']);reply(200,['editable'=>true,'content'=>$content,'hash'=>$f['blob'],'revision'=>$m['revision']]);
 }
 if($method!=='POST'||!in_array($action,['new_file','new_folder','save','upload','delete'],true))reply(405,['message'=>'Unsupported action.']);
 // Staff manage all projects; other contributors require membership.
 $lock=project_lock($root);
 try {
  collaboration_get($user,(int)$p['id']);$m=project_manifest($root);
  if((int)($data['revision']??0)!==(int)$m['revision'])reply(409,['message'=>'The project changed. Refresh files and retry. Your unsaved editor text has been kept.']);
  $rawPath=(string)($data['path']??'');$path=$action==='upload'&&$rawPath===''?'':project_path($rawPath);
  if($action==='delete'){collaboration_delete($m,$path,$user);
  }elseif($action==='upload'){
   $f=$_FILES['file']??null;if(!$f||$f['error']!==UPLOAD_ERR_OK||$f['size']<1||$f['size']>PROJECT_ARCHIVE_LIMIT)throw new InvalidArgumentException('Choose a file up to 25 MB (10 MB for a single non-ZIP file).');
   $incoming=[];$originalName=basename(str_replace('\\','/',$f['name']));
   if(strtolower(pathinfo($originalName,PATHINFO_EXTENSION))==='zip'){
    $key=bin2hex(random_bytes(24));$stage=project_root(['storage_key'=>$key]);if(!mkdir($stage,0700)||!mkdir($stage.'/blobs',0700)||!move_uploaded_file($f['tmp_name'],$stage.'/original'))throw new RuntimeException('Upload unavailable.');
    try{$import=project_extract(['storage_key'=>$key,'archive_type'=>'zip'],$user);foreach($import['files'] as $relative=>$entry){$target=project_path(($path!==''?$path.'/':'').$relative);if(!$entry['directory'])$entry['blob']=project_blob($root,file_get_contents($stage.'/blobs/'.$entry['blob']));$incoming[$target]=$entry;}}
    finally{foreach(glob($stage.'/blobs/*')?:[] as $item)@unlink($item);foreach(['original','manifest.json','lock'] as $item)@unlink($stage.'/'.$item);@rmdir($stage.'/blobs');@rmdir($stage);}
   }else{if($f['size']>PROJECT_FILE_LIMIT)throw new InvalidArgumentException('Single files must be 10 MB or smaller.');$incoming[project_path(($path!==''?$path.'/':'').$originalName)]=['directory'=>false,'size'=>(int)$f['size'],'blob'=>project_blob($root,file_get_contents($f['tmp_name']))];}
   if($path!==''&&!isset($m['files'][$path])){$m['files'][$path]=['directory'=>true,'size'=>0];collaboration_stamp($m,$path,$user,'Created folder');}elseif($path!==''&&!$m['files'][$path]['directory'])throw new InvalidArgumentException('Upload destination must be a folder.');
   foreach($incoming as $target=>$entry){if(isset($m['files'][$target])){if($entry['directory']&&$m['files'][$target]['directory'])continue;throw new InvalidArgumentException('Upload conflicts with '.$target.'. Choose a new destination folder or edit the existing file.');}$m['files'][$target]=$entry;collaboration_stamp($m,$target,$user,$entry['directory']?'Created folder':'Uploaded file');}
  }elseif($action==='save'){
   $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'=>'File changed. Reopen it before saving.']);
   $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.');$before=file_get_contents($root.'/blobs/'.$current['blob']);
   if($before===$content)reply(200,array_merge(collaboration_listing($m),['message'=>'No code changes to save.','hash'=>$current['blob']]));
   $changes=collaboration_line_changes($before,$content);$afterHash=project_blob($root,$content);$m['files'][$path]=['directory'=>false,'size'=>strlen($content),'blob'=>$afterHash];collaboration_stamp($m,$path,$user,'Edited file');
   $last=count($m['activity'])-1;$m['activity'][$last]=array_merge($m['activity'][$last],['line_changes'=>$changes,'before_blob'=>$current['blob'],'after_blob'=>$afterHash,'revision'=>$m['revision']+1]);
  }else{
   if(isset($m['files'][$path]))throw new InvalidArgumentException('That file or folder already exists.');$dir=$action==='new_folder';$m['files'][$path]=$dir?['directory'=>true,'size'=>0]:['directory'=>false,'size'=>0,'blob'=>project_blob($root,'')];collaboration_stamp($m,$path,$user,$dir?'Created folder':'Created file');
  }
  collaboration_limits($m['files']);$m['revision']++;project_write_manifest($root,$m);
 }finally{flock($lock,LOCK_UN);fclose($lock);}
 reply(200,array_merge(collaboration_listing($m),['message'=>'Changes saved.','hash'=>$m['files'][$path]['blob']??null]));
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('SLPS collaborations: '.get_class($e).' '.$e->getMessage());reply(503,['message'=>'Project Collaborations is unavailable. Apply all collaboration migrations and check private storage permissions.']);}
