<?php
require_once('../../config.php');
header('Content-Type:application/json');
if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(403);echo json_encode(['success'=>false,'redirect'=>'login.php']);exit;}
$token=$_POST['csrf']??'';
if(empty($_SESSION['csrf'])||$token!==$_SESSION['csrf']){http_response_code(403);echo json_encode(['success'=>false,'redirect'=>'login.php']);exit;}
if(!isset($_SESSION['user'])||!has_permission('faxdashboard')){http_response_code(403);echo json_encode(['success'=>false,'redirect'=>'login.php']);exit;}
$faxIn=$_POST['fax']??'';
if($faxIn===''){echo json_encode(['success'=>false,'message'=>'Fax file not specified']);exit;}
$nomeFax=basename($faxIn);
$spoolDir=realpath(rtrim($applicationSpoolDir,'/'));
if(!$spoolDir){echo json_encode(['success'=>false,'message'=>'Invalid spool dir']);exit;}
$inputFile=$spoolDir.'/'.$nomeFax;
if(!is_file($inputFile)||strpos(realpath($inputFile),$spoolDir)!==0){echo json_encode(['success'=>false,'message'=>'Fax file not found']);exit;}
function cmd_path($cmd){$p=shell_exec("command -v ".escapeshellarg($cmd));return $p?trim($p):null;}
$tiff2pdf=cmd_path('tiff2pdf');
if(!$tiff2pdf){echo json_encode(['success'=>false,'message'=>'tiff2pdf not found']);exit;}
$logFile='/var/spool/hylafax/etc/xferfaxlog';
$recvTime=null;$caller='unknown';$pages=0;$jid=null;
if(is_readable($logFile)){
$lines=file($logFile,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$lines=array_slice($lines,-3000);
foreach(array_reverse($lines) as $line){
if(!str_contains($line,"\tRECV\t")||!str_contains($line,$nomeFax))continue;
$f=explode("\t",$line);
if(count($f)<11)continue;
$dt=DateTime::createFromFormat('m/d/y H:i',trim($f[0]));
if($dt)$recvTime=$dt->format('Y-m-d H:i:s');
$raw=trim($f[8]??'','" ');
$num=preg_replace('/\D/','',$raw);
if($num!=='')$caller=$num;
$pages=intval($f[10]??0);
$jid=trim($f[2]);
break;
}}
if(!$recvTime)$recvTime=date('Y-m-d H:i:s',filemtime($inputFile));
$ts=strtotime($recvTime);
$fnameTime=date('Ymd_Hi',$ts);
$archivePath=realpath(rtrim($applicationArchivePath,'/'));
if(!$archivePath||!is_dir($archivePath)){mkdir($applicationArchivePath,0755,true);$archivePath=realpath($applicationArchivePath);}
if(!$archivePath){echo json_encode(['success'=>false,'message'=>'Archive dir error']);exit;}
do{
$uid=bin2hex(random_bytes(4));
$base=$fnameTime.'_'.$caller.'_'.$uid;
$pdfFile=$archivePath.'/'.$base.'.pdf';
$tifFile=$archivePath.'/'.$base.'.tiff';
$metaFile=$archivePath.'/'.$base.'.meta';
}while(file_exists($pdfFile));
if(!copy($inputFile,$tifFile)){echo json_encode(['success'=>false,'message'=>'TIFF copy failed']);exit;}
$cmd=escapeshellcmd($tiff2pdf)." -o ".escapeshellarg($pdfFile)." ".escapeshellarg($tifFile)." 2>&1";
exec($cmd,$out,$ret);
if($ret!==0||!is_file($pdfFile)){@unlink($tifFile);echo json_encode(['success'=>false,'message'=>'Conversion failed','log'=>$out]);exit;}
$status=($jid&&$recvTime)?'success':'unknown';
$meta=['uid'=>$uid,'jid'=>$jid,'received_time'=>$recvTime,'caller'=>$caller,'pages'=>$pages,'status'=>$status];
if(saveMeta($metaFile,$meta)){
@unlink($inputFile);@chmod($pdfFile,0666);@chmod($tifFile,0666);@chmod($metaFile,0666);
echo json_encode(['success'=>true,'file'=>$base.'.pdf']);
}else echo json_encode(['success'=>false,'message'=>'Failed to save metadata']);
exit;
