<?php
declare(strict_types=1);

function pcE(mixed $value):string{return htmlspecialchars((string)$value,ENT_QUOTES,'UTF-8');}
function pcText(mixed $value,int $max=255):string{$value=trim((string)$value);return function_exists('mb_substr')?mb_substr($value,0,$max,'UTF-8'):substr($value,0,$max);}
function pcTableExists(mysqli $db,string $table):bool{$safe=$db->real_escape_string($table);$r=$db->query("SHOW TABLES LIKE '{$safe}'");return $r instanceof mysqli_result&&$r->num_rows>0;}
function pcConfig(mysqli $db):array{if(!pcTableExists($db,'ti_pc_config'))return [];$r=$db->query('SELECT * FROM ti_pc_config WHERE id=1 LIMIT 1');return $r?($r->fetch_assoc()?:[]):[];}
function pcUsuario():string{return trim((string)($_SESSION['usuario']??$_SESSION['username']??''));}
function pcNorm(string $value):string{$value=function_exists('mb_strtolower')?mb_strtolower($value,'UTF-8'):strtolower($value);$ascii=@iconv('UTF-8','ASCII//TRANSLIT//IGNORE',$value);return preg_replace('/[^a-z0-9]+/','',(string)($ascii!==false?$ascii:$value))??'';}
function pcEhRenan():bool{return pcNorm(pcUsuario())==='renan';}
function pcCsrf():string{if(empty($_SESSION['csrf_inventario_pc']))$_SESSION['csrf_inventario_pc']=bin2hex(random_bytes(24));return (string)$_SESSION['csrf_inventario_pc'];}
function pcCheckCsrf():void{if(empty($_POST['csrf_token'])||empty($_SESSION['csrf_inventario_pc'])||!hash_equals((string)$_SESSION['csrf_inventario_pc'],(string)$_POST['csrf_token']))throw new RuntimeException('Sessao expirada. Atualize a pagina.');}
function pcRedirect(string $url):never{header('Location: '.$url);exit;}
function pcFlash(string $type,string $message):void{$_SESSION['pc_flash']=['tipo'=>$type,'msg'=>$message];}
function pcGetFlash():?array{$x=$_SESSION['pc_flash']??null;unset($_SESSION['pc_flash']);return is_array($x)?$x:null;}
function pcAgo(?string $date):string{if(!$date||!strtotime($date))return 'nunca';$seconds=max(0,time()-strtotime($date));if($seconds<60)return $seconds.' s';if($seconds<3600)return floor($seconds/60).' min';if($seconds<86400)return floor($seconds/3600).' h';return floor($seconds/86400).' dias';}
function pcCommunication(?string $date,int $recent=2,int $silent=24,int $offline=168):array{if(!$date||!strtotime($date)||time()-strtotime($date)>=$offline*3600)return ['label'=>'OFFLINE PROLONGADO','class'=>'danger'];if(time()-strtotime($date)>=$silent*3600)return ['label'=>'SEM COMUNICACAO','class'=>'warn'];if(time()-strtotime($date)<=$recent*3600)return ['label'=>'COMUNICANDO','class'=>'ok'];return ['label'=>'COMUNICACAO INTERMITENTE','class'=>'warn'];}
function pcGb(mixed $mb):string{return number_format(((float)$mb)/1024,1,',','.').' GB';}
function pcRunSql(mysqli $db,string $file):void{$sql=file_get_contents($file);if($sql===false)throw new RuntimeException('Arquivo SQL nao encontrado.');if(!$db->multi_query($sql))throw new RuntimeException($db->error);do{if($r=$db->store_result())$r->free();if(!$db->more_results())break;}while($db->next_result());if($db->errno)throw new RuntimeException($db->error);}
function pcAgentExists():bool{return is_file(__DIR__.'/downloads/Agente-TI-Extrema-Windows-v1.0.1.zip')||is_file(__DIR__.'/downloads/Agente-TI-Extrema-Windows.zip');}
function pcAgentUrl():string{return is_file(__DIR__.'/downloads/Agente-TI-Extrema-Windows-v1.0.1.zip')?'downloads/Agente-TI-Extrema-Windows-v1.0.1.zip':'downloads/Agente-TI-Extrema-Windows.zip';}
function pcAuditWeb(mysqli $db,string $action,?int $agentId=null,?string $details=null):void{if(!pcTableExists($db,'ti_pc_auditoria'))return;$actor=pcUsuario();$ip=substr((string)($_SERVER['REMOTE_ADDR']??''),0,45);$stmt=$db->prepare('INSERT INTO ti_pc_auditoria(agente_id,acao,ator,ip_remoto,detalhes) VALUES(?,?,?,?,?)');$stmt->bind_param('issss',$agentId,$action,$actor,$ip,$details);$stmt->execute();$stmt->close();}
