<?php
require_once('../../config.php');
$id=$_GET['id']??'';
$MAX_AGE=600;
$decoded=base64_decode(strtr($id,'-_','+/'),true);
if(!$decoded){http_response_code(400);exit;}
$parts=explode('|',$decoded,3);
if(count($parts)!==3){http_response_code(400);exit;}
[$sig,$ts,$path]=$parts;
if(time()-(int)$ts>$MAX_AGE){http_response_code(403);exit('Token expired');}
$payload=$ts.'|'.$path;
$expect=hash_hmac('sha256',$payload,FAX_VIEW_SECRET);
if(!hash_equals($expect,$sig)){http_response_code(403);exit('Invalid signature');}
$realPath=realpath($path);
if(!$realPath||!is_file($realPath)){http_response_code(404);exit('File not found');}
$baseInbox=realpath($applicationArchivePath).DIRECTORY_SEPARATOR;
$baseOut=realpath($applicationOutboxPath).DIRECTORY_SEPARATOR;
$isInbound=str_starts_with($realPath,$baseInbox);
$isOutbound=str_starts_with($realPath,$baseOut);
if(!$isInbound&&!$isOutbound){http_response_code(403);exit('Access denied');}
if($isInbound){
$metaFile=dirname($realPath).DIRECTORY_SEPARATOR.pathinfo($realPath,PATHINFO_FILENAME).'.meta';
$meta=[];$shouldUpdate=false;
if(is_file($metaFile)){
$meta=loadMeta($metaFile);
if(!isset($meta['read'])||$meta['read']!==true)$shouldUpdate=true;
}else $shouldUpdate=true;
if($shouldUpdate){
$meta['read']=true;
$meta['read_time']=date('Y-m-d H:i:s');
$meta['read_user']=$_SESSION['user'];
saveMeta($metaFile,$meta);
}}
$finfo=finfo_open(FILEINFO_MIME_TYPE);
$mime=finfo_file($finfo,$realPath);
finfo_close($finfo);
$allowedMimes=['application/pdf','image/tiff'];
if(!in_array($mime,$allowedMimes)){http_response_code(403);exit('Unsupported file type');}
header('Content-Type:'.$mime);
header('Content-Disposition:inline;filename="'.basename($realPath).'"');
header('Content-Length:'.filesize($realPath));
header('Cache-Control:private,max-age=0,must-revalidate');
header('Pragma:no-cache');
readfile($realPath);
exit;
