<?php
declare(strict_types=1);
require_once __DIR__.'/files_common.php';
$user=leave_current_user($pdo);
$profile=leave_official_profile($pdo,$user);
// Keep this adapter tied to trusted DB-derived profile values, never request fields.
$actor=['id'=>(int)$user['id'], 'name'=>(string)($profile['name']??''),
 'role'=>fm_role((string)($profile['position']??'')), 'campus'=>(string)($profile['campus']??'')];
$actor['campus_key']=fm_campus($actor['campus']);
if (!fm_is_staff($user)) fm_fail('Staff access is required.',403);
if (isset($user['account_status']) && strtolower((string)$user['account_status'])==='suspended') fm_json(['detail'=>'Account suspended.','code'=>'account_suspended'],403);
$method=$_SERVER['REQUEST_METHOD']??'GET'; $op=$_GET['op']??'manifest';
try {
 fm_handle_folder_operation($pdo,$actor,$op,$method);
 if ($op==='manifest'  && $method==='GET') {
    $args=[];$acl=fm_acl_sql($actor,$args);
    $q=$pdo->prepare("SELECT f.id,f.folder_id,f.owner_id,f.owner_name,f.owner_role,f.campus,f.campus_key,f.title,f.current_version,f.updated_at,
      v.filename,v.size_bytes,v.sha256,v.mime FROM managed_files f JOIN managed_file_versions v ON v.file_id=f.id AND v.version=f.current_version
      WHERE f.deleted_at IS NULL AND $acl ORDER BY f.id DESC");
    $q->execute($args);$files=$q->fetchAll(PDO::FETCH_ASSOC);
    foreach($files as &$f) { foreach(['id','owner_id','current_version','size_bytes'] as $k) $f[$k]=(int)$f[$k];
      $f['can_edit']=$f['owner_id']===$actor['id'];
      $f['folder_id']=$f['folder_id']===null?null:(int)$f['folder_id'];
      $f['audience']=fm_audience($f);
    } unset($f);
    $folderArgs=[];$folderAcl=fm_folder_acl_sql($actor,$folderArgs);
    $q=$pdo->prepare("SELECT g.* FROM managed_folders g WHERE $folderAcl ORDER BY g.name,g.id");$q->execute($folderArgs);
    $folders=$q->fetchAll(PDO::FETCH_ASSOC);
    foreach($folders as &$folder) $folder=fm_folder_public($folder,$actor); unset($folder);
    $q=$pdo->prepare("SELECT m.folder_id,g.name,g.owner_name,g.campus,m.invited_at FROM managed_folder_members m JOIN managed_folders g ON g.id=m.folder_id WHERE m.user_id=? AND m.state='pending' AND g.deleted_at IS NULL ORDER BY m.invited_at DESC");
    $q->execute([$actor['id']]);$invitations=$q->fetchAll(PDO::FETCH_ASSOC);
    foreach($invitations as &$invite)$invite['folder_id']=(int)$invite['folder_id'];unset($invite);
    $payload=['user'=>$actor,'files'=>$files,'folders'=>$folders,'invitations'=>$invitations,
      'can_create_folder'=>true,'can_create_public_folder'=>fm_is_executive($actor),
      'upload_audience'=>fm_audience(['owner_role'=>$actor['role']]),'max_bytes'=>26214400];
    $etag='"'.hash('sha256',json_encode($payload)).'"';
    header('ETag: '.$etag);header('Cache-Control: private, no-cache');
    if (($_SERVER['HTTP_IF_NONE_MATCH']??'')===$etag) {http_response_code(304);exit;}
    fm_json($payload);
 }
 if ($op==='meta' && $method==='GET') {
    $f=fm_file($pdo,$actor,(int)($_GET['id']??0));
    $q=$pdo->prepare('SELECT * FROM managed_file_versions WHERE file_id=? AND version=?');$q->execute([$f['id'],$f['current_version']]);
    $v=$q->fetch(PDO::FETCH_ASSOC);unset($v['storage_key']);fm_json(['file'=>$f,'version'=>$v]);
 }
 if ($op==='download' && $method==='GET') {
    $f=fm_file($pdo,$actor,(int)($_GET['id']??0));$version=(int)($_GET['version']??0);
    // Never mix a partial download with bytes from a replacement version.
    if ($version!==(int)$f['current_version']) fm_fail('A new file version is available. Refresh and download it.',409);
    $q=$pdo->prepare('SELECT * FROM managed_file_versions WHERE file_id=? AND version=?');$q->execute([$f['id'],$version]);$v=$q->fetch(PDO::FETCH_ASSOC);
    $offset=(int)($_GET['offset']??0);$length=min(524288,max(1,(int)($_GET['length']??524288)));
    if ($offset<0 || $offset>=(int)$v['size_bytes']) fm_fail('Invalid download offset.',416);
    $length=min($length,(int)$v['size_bytes']-$offset);$path=fm_path($v['storage_key']);
    $h=fopen($path,'rb');if (!$h) fm_fail('Stored file is unavailable.',503);fseek($h,$offset);
    $bytes=fread($h,$length);fclose($h);
    if (strlen($bytes)!==$length) fm_fail('Incomplete stored file.',503);
    if ($offset===0) fm_audit($pdo,$actor,(int)$f['id'],'download',$version);
    header('Cache-Control: no-store');header('Content-Type: application/octet-stream');header('X-Content-Type-Options: nosniff');
    header('Content-Length: '.strlen($bytes));echo $bytes;exit;
 }
 if ($op==='begin' && $method==='POST') {
    $in=fm_input();$key=(string)($in['client_key']??'');$sha=(string)($in['sha256']??'');
    if (!preg_match('/^[a-f0-9]{32}$/D',$key)||!preg_match('/^[a-f0-9]{64}$/D',$sha)) fm_fail('Invalid upload identity.',422);
    $size=(int)($in['size_bytes']??0);if($size<1||$size>26214400) fm_fail('Files must be between 1 byte and 25 MB.',422);
    $name=fm_filename((string)($in['filename']??''));$title=trim((string)($in['title']??$name));
    if($title===''||strlen($title)>200) fm_fail('Title must be 1–200 bytes.',422);
    $fileId=(int)($in['file_id']??0);$expected=(int)($in['expected_version']??0);
    $folderId=(int)($in['folder_id']??0);
    if ($folderId<0) fm_fail('Invalid folder.',422);
    if($fileId>0) {
      $existing=fm_file($pdo,$actor,$fileId,true);
      // Replacements preserve publication scope, even from older clients.
      $folderId=(int)($existing['folder_id']??0);
    }
    if($folderId>0) fm_folder_for_upload($pdo,$actor,$folderId);
    $id=bin2hex(random_bytes(16));
    $q=$pdo->prepare('INSERT INTO managed_uploads(id,owner_id,client_key,file_id,expected_version,filename,title,size_bytes,sha256,folder_id) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner_id,client_key) DO NOTHING');
    $q->execute([$id,$actor['id'],$key,$fileId?:null,$expected,$name,$title,$size,$sha,$folderId?:null]);
    $q=$pdo->prepare('SELECT * FROM managed_uploads WHERE owner_id=? AND client_key=?');$q->execute([$actor['id'],$key]);$u=$q->fetch(PDO::FETCH_ASSOC);
    if((int)($u['folder_id']??0)!==$folderId || $u['sha256']!==$sha || (int)$u['size_bytes']!==$size || (int)$u['file_id']!==$fileId || $u['filename']!==$name || $u['title']!==$title || (int)$u['expected_version']!==$expected) fm_fail('Upload identity conflicts with another file.',409);
    fm_json(['upload_id'=>$u['id'],'offset'=>(int)$u['received_bytes'],'result_file_id'=>$u['result_file_id'],'result_version'=>$u['result_version']]);
 }
 if ($op==='chunk' && $method==='POST') {
    $pdo->beginTransaction();$u=fm_upload($pdo,$actor,(string)($_GET['upload_id']??''));
    if($u['result_file_id']) fm_fail('Upload is already complete.',409);
    $offset=(int)($_GET['offset']??-1);$bytes=file_get_contents('php://input',false,null,0,524289);
    $n=strlen($bytes);if($n<1||$n>524288||$offset<0||$offset+$n>(int)$u['size_bytes']) fm_fail('Invalid upload chunk.',422);
    $path=fm_path($u['id']);
    if($offset<(int)$u['received_bytes']) {
       if($offset+$n>(int)$u['received_bytes']) fm_fail('Chunk overlaps an unconfirmed offset.',409);
       $h=fopen($path,'rb');if(!$h) fm_fail('Partial upload unavailable.',503);fseek($h,$offset);$old=fread($h,$n);fclose($h);
       if(!hash_equals(hash('sha256',$old),hash('sha256',$bytes))) fm_fail('Repeated chunk differs from stored bytes.',409);
    } else {
       if($offset!==(int)$u['received_bytes']) fm_fail('Upload offset changed. Retry to resume.',409);
       $h=fopen($path,'c+b');if(!$h) fm_fail('Cannot write file.',503);chmod($path,0600);
       ftruncate($h,$offset);fseek($h,$offset);$written=fwrite($h,$bytes);fflush($h);fclose($h);
       if($written!==$n) fm_fail('File storage is full.',507);
       $u['received_bytes']=$offset+$n;
       $pdo->prepare('UPDATE managed_uploads SET received_bytes=? WHERE id=?')->execute([$u['received_bytes'],$u['id']]);
    }
    $pdo->commit();fm_json(['offset'=>(int)$u['received_bytes']]);
 }
 if ($op==='finish' && $method==='POST') {
    $in=fm_input();$pdo->beginTransaction();$u=fm_upload($pdo,$actor,(string)($in['upload_id']??''));
    if($u['result_file_id']) {$pdo->commit();fm_json(['file_id'=>(int)$u['result_file_id'],'version'=>(int)$u['result_version']]);}
    $path=fm_path($u['id']);
    if((int)$u['received_bytes']!==(int)$u['size_bytes']||!is_file($path)||filesize($path)!==(int)$u['size_bytes']||!hash_equals($u['sha256'],hash_file('sha256',$path))) fm_fail('Upload is incomplete or checksum failed.',422);
    $mime=fm_check_mime($u['filename'],$path);
    if (!empty($u['folder_id'])) fm_folder_for_upload($pdo,$actor,(int)$u['folder_id']);
    if($u['file_id']) {
       $q=$pdo->prepare('SELECT * FROM managed_files WHERE id=? FOR UPDATE');$q->execute([$u['file_id']]);$f=$q->fetch(PDO::FETCH_ASSOC);
       if(!$f||$f['deleted_at']||(int)$f['owner_id']!==$actor['id']) fm_fail('File cannot be updated.',403);
       if((int)$f['current_version']!==(int)$u['expected_version']) fm_fail('Another version was saved. Refresh, then choose Replace again.',409);
       if ((int)($f['folder_id']??0)!==(int)($u['folder_id']??0)) fm_fail('File folder changed. Start the upload again.',409);
       $fileId=(int)$f['id'];$version=(int)$f['current_version']+1;
    } else {
       $q=$pdo->prepare('INSERT INTO managed_files(owner_id,owner_name,owner_role,campus,campus_key,title,folder_id) VALUES(?,?,?,?,?,?,?) RETURNING id');
       $q->execute([$actor['id'],$actor['name'],$actor['role'],$actor['campus'],$actor['campus_key'],$u['title'],$u['folder_id']]);$fileId=(int)$q->fetchColumn();$q->closeCursor();$version=1;
    }
    // Immutable content object. Copy preserves staging bytes if DB commit fails.
    $storage=hash('sha256','rockview-upload:'.$u['id']);$dest=fm_path($storage);
    if(!copy($path,$dest)) fm_fail('Cannot finalize stored file.',507);chmod($dest,0600);
    $pdo->prepare('INSERT INTO managed_file_versions(file_id,version,filename,size_bytes,sha256,mime,storage_key) VALUES(?,?,?,?,?,?,?)')->execute([$fileId,$version,$u['filename'],$u['size_bytes'],$u['sha256'],$mime,$storage]);
    $pdo->prepare('UPDATE managed_files SET current_version=?,title=?,updated_at=CURRENT_TIMESTAMP WHERE id=?')->execute([$version,$u['title'],$fileId]);
    $pdo->prepare('UPDATE managed_uploads SET result_file_id=?,result_version=? WHERE id=?')->execute([$fileId,$version,$u['id']]);
    fm_audit($pdo,$actor,$fileId,$version===1?'upload':'replace',$version);$pdo->commit();@unlink($path);
    fm_json(['file_id'=>$fileId,'version'=>$version]);
 }
 if($op==='delete' && $method==='POST') {
    $in=fm_input();$pdo->beginTransaction();$f=fm_file($pdo,$actor,(int)($in['id']??0),true);
    $q=$pdo->prepare('UPDATE managed_files SET deleted_at=CURRENT_TIMESTAMP WHERE id=? AND current_version=? AND deleted_at IS NULL');$q->execute([$f['id'],(int)($in['expected_version']??0)]);
    if(!$q->rowCount()) fm_fail('File changed. Refresh before deleting.',409);
    fm_audit($pdo,$actor,(int)$f['id'],'delete',(int)$f['current_version']);$pdo->commit();fm_json(['deleted'=>true]);
 }
 fm_fail('Unsupported file operation.',405);
} catch(Throwable $e) {
 if($pdo->inTransaction()) $pdo->rollBack();error_log('File module: '.$e->getMessage());
 fm_fail('The file service could not complete the request. Please retry.',500);
}
