<?php
require_once dirname(__DIR__,2).'/config.php';
require_once dirname(__DIR__,2).'/include/plugin/push.lib.php';
$outboxPath=realpath($applicationOutboxPath);
$logPath="/var/spool/hylafax/etc/xferfaxlog";
if(!file_exists($logPath)||!is_readable($logPath))exit("Error: Hylafax log file not found or not readable.\n");
$logData=shell_exec('/usr/bin/tail -n 3000 '.escapeshellarg($logPath));
$logLines=explode("\n",trim($logData));
$statusMap=[];
foreach($logLines as $line){
$f=explode("\t",$line);
if(count($f)<14||($f[1]??'')!=='SEND')continue;
$dt=DateTime::createFromFormat('m/d/y H:i',$f[0]);
if(!$dt)continue;
$num=preg_replace('/[^0-9]/','',trim($f[7]??'','"'));
if(str_starts_with($num,'82'))$num='0'.substr($num,2);
$num=$num?:'unknown';
$status=trim($f[13]??'','" ')?:'OK';
for($i=-3;$i<=3;$i++){
$d=clone $dt;
if($i)$d->modify("$i minutes");
$k=$d->format('Ymd_Hi')."_".(strlen($num)>8?substr($num,-8):$num);
$statusMap[$k]=$status;
}}
$it=new RecursiveDirectoryIterator($outboxPath);
foreach(new RecursiveIteratorIterator($it) as $file){
if(!$file->isFile())continue;
if(!preg_match('/\.meta$/i',$file->getFilename()))continue;
$metaPath=$file->getRealPath();
$meta=loadMeta($metaPath);
if(!isset($meta['status'])||$meta['status']!=='sent')continue;
$pdfName=pathinfo(str_replace('.meta','',$metaPath),PATHINFO_FILENAME);
$numMatch='';
if(preg_match('/^\d{8}_\d{4}_(\d+)/',$pdfName,$m))$numMatch=(strlen($m[1])>8)?substr($m[1],-8):$m[1];
$key=substr($pdfName,0,13).'_'.$numMatch;
if(isset($statusMap[$key])){
$finalStatus=$statusMap[$key]==='OK'?'success':'failed';
$meta['status']=$finalStatus;
$meta['completed_time']=date('Y-m-d H:i:s');
if($finalStatus==='failed')$meta['error']="Hylafax Error: ".$statusMap[$key];
saveMeta($metaPath,$meta);
echo"[LOG] Updated: $pdfName -> $finalStatus\n";
$title=$finalStatus==='success'?__('📠 Fax Sent Successfully'):__('📠 Fax Sending Failed');
$body=sprintf(__('Fax : %s'),$pdfName);
$sender=$meta['user_id']??null;
$admins=getAdminUserIds();
if($finalStatus==='success'){if($sender)sendPushToUsers([$sender],$title,$body,"/fax_outbox.php");}
else{$targets=array_unique(array_merge([$sender],$admins));sendPushToUsers($targets,$title,$body,"/fax_outbox.php");}
}else{
$errorTimerSeconds=$fax_error_timer??3600;
$fileMTime=filemtime($metaPath);
$diffSeconds=time()-$fileMTime;
if($diffSeconds>$errorTimerSeconds){
$destNum=$meta['destination']??'';
$killMessage="No response from system.";
if($destNum){
$destEscaped=escapeshellarg($destNum);
$jobId=shell_exec("faxstat -s | grep $destEscaped | awk '{print $1}' | head -n 1");
$jobId=trim($jobId);
if($jobId&&is_numeric($jobId)){
shell_exec("faxrm ".escapeshellarg($jobId));
$killMessage="Hylafax Job #$jobId forcibly killed due to timeout.";
}else $killMessage="Job not found in Hylafax queue. Marked as timed out.";
}
$meta['status']='failed';
$meta['completed_time']=date('Y-m-d H:i:s');
$meta['error']="Timeout Fail: ".$killMessage;
saveMeta($metaPath,$meta);
echo"[TIMEOUT] Killed & Updated: $pdfName -> failed\n";
$title=__('📠 Fax Sending Timeout');
$body=sprintf(__('Fax : %s timeout'),$pdfName);
$sender=$meta['user_id']??null;
$admins=getAdminUserIds();
$targets=array_unique(array_merge([$sender],$admins));
sendPushToUsers($targets,$title,$body,"/fax_outbox.php");
}}}
