<?php
if(session_status()===PHP_SESSION_NONE)session_start();
require_once('../../config.php');
header('Content-Type:application/json;charset=utf-8');
if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);echo json_encode(['success'=>false,'message'=>'Method not allowed']);exit;}
$prev='index.php';
if(!empty($_SERVER['HTTP_REFERER'])){$u=parse_url($_SERVER['HTTP_REFERER']);if(!empty($u['path']))$prev=$u['path'];}
$receivedToken=$_POST['csrf']??$_SERVER['HTTP_X_CSRF_TOKEN']??'';
if(empty($_SESSION['csrf'])||$receivedToken!==$_SESSION['csrf']){echo json_encode(['success'=>false,'message'=>'Security token mismatch.','redirect'=>$prev]);exit;}
if(!isset($_SESSION['user'])||!has_permission('inboxmenu')){echo json_encode(['success'=>false,'message'=>'Session expired','redirect'=>'login.php']);exit;}
$file=basename($_POST['file']??'');
$dir=trim($_POST['dir']??'','/\\');
if($file===''){echo json_encode(['success'=>false,'message'=>'Invalid file']);exit;}
if(str_contains($dir,'..')){echo json_encode(['success'=>false,'message'=>'Invalid directory']);exit;}
$ext=strtolower(pathinfo($file,PATHINFO_EXTENSION));
if(!in_array($ext,['pdf','tiff','tif'],true)){echo json_encode(['success'=>false,'message'=>'Invalid file type']);exit;}
$base=realpath(rtrim($applicationArchivePath,DIRECTORY_SEPARATOR));
if(!$base){echo json_encode(['success'=>false,'message'=>'Base path error']);exit;}
$path=$base.DIRECTORY_SEPARATOR.($dir?$dir.DIRECTORY_SEPARATOR:'').$file;
$real=realpath($path);
if(!$real||!str_starts_with($real,$base)||!is_file($real)){echo json_encode(['success'=>false,'message'=>'File not found']);exit;}
$metaFile=dirname($real).DIRECTORY_SEPARATOR.pathinfo($real,PATHINFO_FILENAME).'.meta';
$meta=loadMeta($metaFile);
$userId='unknown';
if(is_array($_SESSION['user']))$userId=$_SESSION['user']['id']??$_SESSION['user']['username']??'unknown';
elseif(is_string($_SESSION['user']))$userId=$_SESSION['user'];
$userId=preg_replace('/[^a-zA-Z0-9_\-]/','',$userId);
$userId=substr($userId,0,50);
if(empty($meta['read'])){$meta['read']=true;$meta['read_time']=date('Y-m-d H:i:s');$meta['read_user']=$userId;}
if(saveMeta($metaFile,$meta)===false){error_log("Failed to write meta file: ".$metaFile);echo json_encode(['success'=>false,'message'=>'Write failed']);exit;}
echo json_encode(['success'=>true]);exit;
