<?php
declare(strict_types=1);
require_once __DIR__.'/../lib/guidelines.php';
$user=require_auth();$scope=guideline_scope($user);
if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST')reply(405,['status'=>'error','message'=>'Use POST.']);
if(!$scope['can_edit'])reply(403,['status'=>'error','message'=>'Only admins and assigned HODs can upload course resources.']);
start_auth_session();if(!hash_equals($_SESSION['csrf_token'],(string)($_SERVER['HTTP_X_CSRF_TOKEN']??'')))reply(403,['status'=>'error','message'=>'Your form session expired. Refresh this page and try again.']);
$course=guideline_course($scope,(int)($_POST['course_id']??0));$kind=(string)($_POST['kind']??'attachment');
if(!in_array($kind,['image','attachment'],true))reply(422,['status'=>'error','message'=>'Choose an image or attachment.']);
$file=$_FILES['file']??null;$max=$kind==='image'?5*1024*1024:20*1024*1024;
if(!$file||$file['error']!==UPLOAD_ERR_OK||$file['size']<1||$file['size']>$max)reply(422,['status'=>'error','message'=>$kind==='image'?'Choose an image up to 5 MB.':'Choose an attachment up to 20 MB.']);
$extension=strtolower(pathinfo((string)$file['name'],PATHINFO_EXTENSION));$mime=(new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name'])?:'';
$images=['jpg'=>'image/jpeg','jpeg'=>'image/jpeg','png'=>'image/png','webp'=>'image/webp'];
if($kind==='image'){
 $size=getimagesize($file['tmp_name']);if(!isset($images[$extension])||$mime!==$images[$extension]||!$size||$size[0]>12000||$size[1]>12000)reply(422,['status'=>'error','message'=>'Use a valid JPG, PNG or WebP image, no larger than 12000 pixels per side.']);
}else{
 $types=['pdf'=>['application/pdf'],'txt'=>['text/plain'],'docx'=>['application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/zip'],'xlsx'=>['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/zip'],'pptx'=>['application/vnd.openxmlformats-officedocument.presentationml.presentation','application/zip']];
 if(!isset($types[$extension])||!in_array($mime,$types[$extension],true))reply(422,['status'=>'error','message'=>'Attachments must be PDF, DOCX, XLSX, PPTX or plain text.']);
}
$root=private_storage_root().'/guidelines';if(!is_dir($root)&&!mkdir($root,0750,true)&&!is_dir($root))reply(503,['status'=>'error','message'=>'Private resource storage is unavailable.']);
$key=bin2hex(random_bytes(24)).'.'.$extension;$target=$root.'/'.$key;
if(!move_uploaded_file($file['tmp_name'],$target))reply(503,['status'=>'error','message'=>'The upload could not be stored.']);
try{db()->prepare('INSERT INTO guideline_assets(course_id,file_name,storage_key,media_type,file_size_bytes,asset_kind,uploaded_by) VALUES(?,?,?,?,?,?,?)')->execute([(int)$course['id'],substr(basename((string)$file['name']),0,255),$key,$mime,(int)$file['size'],$kind,(int)$user['id']]);$id=db()->lastInsertId();reply(201,['status'=>'success','asset'=>['id'=>$id,'file_name'=>basename((string)$file['name']),'media_type'=>$mime,'file_size_bytes'=>(int)$file['size'],'asset_kind'=>$kind,'url'=>guideline_asset_url($id)]]);}catch(Throwable $error){@unlink($target);error_log('Guideline upload: '.$error->getMessage());reply(503,['status'=>'error','message'=>'Could not record this resource. Check the guidelines database migration.']);}
