<?php
if(session_status()===PHP_SESSION_NONE)session_start();
require_once dirname(__DIR__,2).'/config.php';
header('Content-Type:application/json');
$rt=$_POST['csrf']??$_SERVER['HTTP_X_CSRF_TOKEN']??'';
$st=$_SESSION['csrf']??'';
if(empty($st)||$rt!==$st){echo json_encode(['success'=>false,'message'=>'Security token mismatch.']);exit;}
if(!isset($_SESSION['user'])||!has_permission('faxsend')){echo json_encode(['success'=>false,'message'=>'Session expired','redirect'=>'login.php']);exit;}
$outboxPath=realpath(rtrim($applicationOutboxPath,'/')).DIRECTORY_SEPARATOR;
$faxNumbers=isset($_POST['faxnumber'])?explode(',',$_POST['faxnumber']):[];
$files=$_FILES['uploadedfile']??null;
$scheduletime=trim($_POST['scheduletime']??'');
$scheduleTs=$scheduletime?strtotime($scheduletime):0;
$isScheduled=$scheduleTs&&$scheduleTs>time();
$priority=($_POST['priority']??'')==='high'?'high':'63';
$faxMemo=trim($_POST['faxmemo']??'');
if(empty($faxNumbers)||!$files||empty($files['tmp_name'][0])){echo json_encode(['success'=>false,'message'=>__('No numbers or files')]);exit;}
function get_cmd_path(string $cmd):?string{$p=shell_exec('command -v '.escapeshellarg($cmd));return $p?trim($p):null;}
$gsPath=get_cmd_path('gs');
$convertPath=get_cmd_path('convert');
$sendfaxPath=get_cmd_path('sendfax');
$pdfinfoPath=get_cmd_path('pdfinfo');
if(!$gsPath||!$convertPath||!$sendfaxPath){echo json_encode(['success'=>false,'message'=>__('Fax tools not installed')]);exit;}
$allowedExts=['pdf','tif','tiff','jpg','jpeg','png'];
$allowedMimes=['application/pdf','image/tiff','image/jpeg','image/png'];
$successCount=0;
$tmpWorkDir=$outboxPath.'tmp_'.bin2hex(random_bytes(8)).DIRECTORY_SEPARATOR;
if(!mkdir($tmpWorkDir,0755)){echo json_encode(['success'=>false,'message'=>'Failed to create workspace']);exit;}
$pdfParts=[];
try{
foreach($files['tmp_name'] as $idx=>$tmpName){
if($files['error'][$idx]!==UPLOAD_ERR_OK)continue;
$finfo=finfo_open(FILEINFO_MIME_TYPE);
$mimeType=finfo_file($finfo,$tmpName);
finfo_close($finfo);
$ext=strtolower(pathinfo($files['name'][$idx],PATHINFO_EXTENSION));
if(!in_array($ext,$allowedExts,true)||!in_array($mimeType,$allowedMimes,true))continue;
$partPdf=$tmpWorkDir."part_{$idx}.pdf";
if($mimeType==='application/pdf')copy($tmpName,$partPdf);
else exec(sprintf('%s %s -resize 2480x3508 -gravity center -extent 2480x3508 %s 2>&1',
escapeshellarg($convertPath),escapeshellarg($tmpName),escapeshellarg($partPdf)));
if(file_exists($partPdf))$pdfParts[]=escapeshellarg($partPdf);
}
if(empty($pdfParts))throw new Exception(__('No valid files to process'));
foreach($faxNumbers as $num){
$num=preg_replace('/[^0-9]/','',$num);
if($num==='')continue;
$uid=bin2hex(random_bytes(4));
$dateStr=date('Ymd_Hi');
$baseName="{$dateStr}_{$num}_{$uid}";
$targetPdf=$outboxPath.$baseName.'.pdf';
$targetTiff=$outboxPath.$baseName.'.tiff';
$metaFile=$outboxPath.$baseName.'.meta';
$mergeCmd=sprintf("%s -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=%s %s 2>&1",
escapeshellarg($gsPath),escapeshellarg($targetPdf),implode(' ',$pdfParts));
exec($mergeCmd,$mOut,$mRet);
if($mRet!==0||!file_exists($targetPdf))continue;
chmod($targetPdf,0644);
exec(sprintf('%s -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=tiffg4 -sOutputFile=%s %s 2>&1',
escapeshellarg($gsPath),escapeshellarg($targetTiff),escapeshellarg($targetPdf)),$gOut,$gRet);
if($gRet!==0||!file_exists($targetTiff))continue;
chmod($targetTiff,0644);
$totalPages=1;
if($pdfinfoPath){
exec(sprintf('%s %s',escapeshellarg($pdfinfoPath),escapeshellarg($targetPdf)),$pOut);
foreach($pOut as $line){if(str_starts_with($line,'Pages:')){$totalPages=(int)trim(substr($line,6));break;}}
}
$meta=['destination'=>$num,'user'=>$_SESSION['user']??'','priority'=>$priority,'created_time'=>date('Y-m-d H:i:s'),'pages'=>$totalPages];
if($faxMemo!==''){$meta['memo']=$faxMemo;$meta['memo_time']=date('Y-m-d H:i:s');}
if($isScheduled){$meta['status']='scheduled';$meta['schedule']=date('Y-m-d H:i',$scheduleTs);saveMeta($metaFile,$meta);$successCount++;continue;}
$retryCount=isset($fax_retry)?(int)$fax_retry:1;
exec(sprintf('%s -n -t %s -P %s -d %s %s 2>&1',
escapeshellarg($sendfaxPath),escapeshellarg($retryCount),escapeshellarg($priority),escapeshellarg($num),escapeshellarg($targetTiff)),$sOut,$sRet);
$meta['status']=$sRet===0?'sent':'failed';
$meta['sent_time']=date('Y-m-d H:i:s');
if($sRet!==0)$meta['error']=implode("\n",$sOut);
else $successCount++;
saveMeta($metaFile,$meta);
}}
catch(Exception $e){echo json_encode(['success'=>false,'message'=>$e->getMessage()]);exit;}
finally{foreach(glob($tmpWorkDir.'*') as $f)@unlink($f);@rmdir($tmpWorkDir);}
echo json_encode(['success'=>true,'count'=>$successCount]);
exit;
