<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';
function paper_scope(array $user): array {
 if(in_array($user['role'],['admin','staff'],true))return ['1=1',[]];
 if($user['role']==='student')return ['EXISTS (SELECT 1 FROM students s WHERE s.user_id=? AND s.department_id=p.department_id)',[$user['id']]];
 if($user['role']==='hod')return ['EXISTS (SELECT 1 FROM hod_assignments h WHERE h.user_id=? AND h.department_id=p.department_id AND (f.campus_id IS NULL OR h.campus_id=f.campus_id))',[$user['id']]];
 reply(403,['message'=>'Access denied.']);
}
function paper_get(array $user,int $id): array {
 [$where,$args]=paper_scope($user);$q=db()->prepare('SELECT p.*,c.course_name,d.department_name FROM past_papers p JOIN file_assets f ON f.id=p.paper_file_id JOIN courses c ON c.id=p.course_id JOIN departments d ON d.id=p.department_id WHERE p.id=? AND '.$where);$q->execute(array_merge([$id],$args));$p=$q->fetch();if(!$p)reply(404,['message'=>'Paper not found or unavailable for your department.']);return $p;
}
function paper_asset(array $user,int $paperId,string $kind): array {
 $p=paper_get($user,$paperId);$id=$kind==='solution'?$p['solution_file_id']:$p['paper_file_id'];if(!$id)reply(404,['message'=>'A solution has not been published for this paper yet.']);
 $q=db()->prepare('SELECT * FROM file_assets WHERE id=? AND department_id=? AND file_category=?');$q->execute([$id,$p['department_id'],$kind==='solution'?'solution':'past_paper']);$f=$q->fetch();if(!$f||!preg_match('/^[a-f0-9]{40}\.(pdf|doc|docx)$/D',$f['storage_key']))reply(404,['message'=>'Document unavailable.']);$f['path']=private_storage_root().'/papers/'.$f['storage_key'];if(!is_file($f['path']))reply(404,['message'=>'Document file is missing. Contact the department.']);return $f;
}
