<?php
declare(strict_types=1);
require_once __DIR__.'/files_policy.php';
// Same authenticated PDO/user/profile functions used by your supplied leave_hr.php.
require_once __DIR__.'/leave_common.php';
function fm_json(array $body, int $status=200): void {
    http_response_code($status); header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store'); echo json_encode($body, JSON_UNESCAPED_UNICODE); exit;
}
function fm_fail(string $message, int $status): void { global $pdo; if(isset($pdo) && $pdo->inTransaction()) $pdo->rollBack(); fm_json(['detail'=>$message],$status); }
function fm_root(): string {
    // Keep managed documents separate from existing public uploads.
    $directory = dirname(__DIR__).'/uploads/staff_files';
    if (!is_dir($directory) && !@mkdir($directory, 0700, true) && !is_dir($directory)) {
        fm_fail('Cannot create uploads/staff_files. Allow PHP to write to the uploads folder.', 503);
    }
    $root = realpath($directory);
    if (!$root || !is_writable($root)) {
        fm_fail('The uploads/staff_files folder is not writable.', 503);
    }
    // Apache/XAMPP must honor .htaccess (the standard XAMPP configuration does).
    // The authenticated files.php endpoint still reads the stored objects normally.
    $protection = $root.DIRECTORY_SEPARATOR.'.htaccess';
    $rules = "Require all denied\n";
    if (@file_get_contents($protection) !== $rules) {
        if (@file_put_contents($protection, $rules, LOCK_EX) !== strlen($rules)) {
            fm_fail('Cannot protect the staff uploads folder. Check folder write permissions.', 503);
        }
    }
    return $root;
}
function fm_path(string $key): string {
    if (!preg_match('/^[a-f0-9]{32,64}$/D',$key)) fm_fail('Invalid storage key.',400);
    return fm_root().DIRECTORY_SEPARATOR.$key;
}
function fm_input(): array {
    $raw=file_get_contents('php://input',false,null,0,8193);
    if (strlen($raw)>8192) fm_fail('Request is too large.',413);
    $data=json_decode($raw,true); if (!is_array($data)) fm_fail('Invalid JSON request.',400);
    return $data;
}
function fm_filename(string $s): string {
    $s=basename(str_replace('\\','/',$s));
    $s=preg_replace('/[\x00-\x1f\x7f]/','',$s);
    if ($s==='' || strlen($s)>200) fm_fail('Choose a filename under 200 bytes.',422);
    $ext=strtolower(pathinfo($s,PATHINFO_EXTENSION));
    if (!in_array($ext,['pdf','doc','docx','xls','xlsx','ppt','pptx','txt','csv','png','jpg','jpeg'],true)) fm_fail('Unsupported file type.',422);
    return $s;
}
function fm_file(PDO $pdo, array $actor, int $id, bool $owner=false): array {
    $args=[]; $acl=fm_acl_sql($actor,$args); $args[]=$id;
    $q=$pdo->prepare("SELECT f.* FROM managed_files f WHERE $acl AND f.id=? AND f.deleted_at IS NULL");
    $q->execute($args);$f=$q->fetch(PDO::FETCH_ASSOC);
    if (!$f) fm_fail('File is unavailable or access was removed.',404);
    if ($owner && (int)$f['owner_id']!==(int)$actor['id']) fm_fail('Only the uploader may change this file.',403);
    if ($owner && !empty($f['folder_id'])) fm_folder_for_upload($pdo,$actor,(int)$f['folder_id']);
    return $f;
}
function fm_audit(PDO $pdo,array $actor,int $id,string $action,int $version): void {
    $pdo->prepare('INSERT INTO managed_file_audit(file_id,actor_id,action,version) VALUES (?,?,?,?)')->execute([$id,$actor['id'],$action,$version]);
}
function fm_upload(PDO $pdo,array $actor,string $id): array {
    if (!preg_match('/^[a-f0-9]{32}$/D',$id)) fm_fail('Invalid upload.',400);
    $q=$pdo->prepare('SELECT * FROM managed_uploads WHERE id=? AND owner_id=? AND expires_at>CURRENT_TIMESTAMP FOR UPDATE');
    $q->execute([$id,$actor['id']]);$u=$q->fetch(PDO::FETCH_ASSOC);
    if (!$u) fm_fail('Upload expired. Remove the queued item and select the file again.',410);
    return $u;
}
function fm_check_mime(string $filename,string $path): string {
    $mime=(new finfo(FILEINFO_MIME_TYPE))->file($path) ?: 'application/octet-stream';
    $ext=strtolower(pathinfo($filename,PATHINFO_EXTENSION));
    $allowed=[
      'pdf'=>['application/pdf'], 'png'=>['image/png'], 'jpg'=>['image/jpeg'], 'jpeg'=>['image/jpeg'],
      'txt'=>['text/plain'], 'csv'=>['text/plain','text/csv','application/csv'],
      'doc'=>['application/msword','application/x-ole-storage','application/CDFV2'],
      'xls'=>['application/vnd.ms-excel','application/x-ole-storage','application/CDFV2'],
      'ppt'=>['application/vnd.ms-powerpoint','application/x-ole-storage','application/CDFV2'],
      'docx'=>['application/zip','application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
      'xlsx'=>['application/zip','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
      'pptx'=>['application/zip','application/vnd.openxmlformats-officedocument.presentationml.presentation'],
    ];
    if (!in_array($mime,$allowed[$ext]??[],true)) fm_fail('File content does not match an allowed document type.',422);
    return $mime;
}

require_once __DIR__.'/files_folders.php';
