<?php
require_once('config.php');
header('Content-Type:application/json;charset=utf-8');
if(!isset($_SESSION['user'])||!has_permission('faxsend')){echo json_encode(["show"=>false,"label"=>"Permission denied","color"=>"#555"]);exit;}
if(!function_exists('safe_exec')){
function safe_exec(string $cmd,array $args=[]):string{
$allowed=['faxstat','pgrep'];
if(!in_array($cmd,$allowed,true)){return'';}
$escaped=array_map('escapeshellarg',$args);
$fullCmd='timeout 3 '.$cmd.' '.implode(' ',$escaped).' 2>&1';
$out=shell_exec($fullCmd)??'';
return substr(trim($out),0,4096);
}}
$res=["show"=>false,"label"=>"","color"=>"#555"];
$raw=safe_exec('faxstat',['-s']);
if(trim($raw)===''||preg_match('/not found|permission denied|can\'t contact|cannot open|error/i',$raw)){echo json_encode(["show"=>true,"label"=>"🔴 ".__('Service unavailable'),"color"=>"#dc2626"],JSON_UNESCAPED_UNICODE);exit;}
$lines=explode("\n",$raw);
$statusScore=0;
foreach($lines as $line){
$line=trim($line);
if(!$line)continue;
if(preg_match('/HylaFAX scheduler.*?Running/i',$line)){
if($statusScore<1){
$res=["show"=>true,"label"=>"🟢 ".__('Running and idle'),"color"=>"#16a34a"];
$statusScore=1;
}}
if(preg_match('/(Waiting for modem to come ready|Freeing|Initializing)/i',$line)){
if($statusScore<2){
$res=["show"=>true,"label"=>"🟠 ".__('Initializing'),"color"=>"#f97316"];
$statusScore=2;
}}
if(preg_match('/(Waiting for modem to come free|Receiving|Calling|Sending|Connected)/i',$line)){
if($statusScore<3){
$res=["show"=>true,"label"=>"🟡 ".__('In use'),"color"=>"#eab308"];
$statusScore=3;
}}
if(preg_match('/(Not ready|Fail|Down|wedged|Not Running)/i',$line)){
$res=["show"=>true,"label"=>"🔴 ".__('Error'),"color"=>"#dc2626"];
$statusScore=4;
break;}
}
echo json_encode($res,JSON_UNESCAPED_UNICODE);
