<?php
declare(strict_types=1);
require_once __DIR__.'/auth.php';require_once __DIR__.'/conexao.php';require_once __DIR__.'/inventario_pc_helpers.php';date_default_timezone_set('America/Sao_Paulo');
if(function_exists('tiPermExigir'))tiPermExigir($mysqli,'computadores','administrar');if(!pcTableExists($mysqli,'ti_pc_config'))pcRedirect('instalar_inventario_pc.php');$mysqli->set_charset('utf8mb4');
if($_SERVER['REQUEST_METHOD']==='POST'){try{pcCheckCsrf();$action=pcText($_POST['acao']??'',30);if($action==='salvar'){$interval=(int)($_POST['sync_interval_min']??30);if(!in_array($interval,[15,30,60,120],true))$interval=30;$recent=max(1,min(24,(int)($_POST['recent_hours']??2)));$silent=max($recent,min(168,(int)($_POST['silent_hours']??24)));$offline=max($silent,min(720,(int)($_POST['offline_hours']??168)));$critical=max(1,min(50,(int)($_POST['storage_critical_percent']??10)));$version=pcText($_POST['current_agent_version']??'1.0.0',40);$versionCode=max(1,(int)($_POST['current_agent_version_code']??1));$enabled=!empty($_POST['api_enabled'])?1:0;$actor=pcUsuario();$stmt=$mysqli->prepare('UPDATE ti_pc_config SET sync_interval_min=?,recent_hours=?,silent_hours=?,offline_hours=?,storage_critical_percent=?,current_agent_version=?,current_agent_version_code=?,api_enabled=?,updated_by=? WHERE id=1');$stmt->bind_param('iiiiisiis',$interval,$recent,$silent,$offline,$critical,$version,$versionCode,$enabled,$actor);$stmt->execute();$stmt->close();pcAuditWeb($mysqli,'CONFIGURACAO_ALTERADA',null,'Politicas do inventario Windows.');pcFlash('ok','Configuracoes atualizadas.');}
elseif($action==='rotacionar'){$hours=max(1,min(168,(int)($_POST['valid_hours']??24)));$uses=max(1,min(500,(int)($_POST['uses']??1)));$code=strtoupper(substr(bin2hex(random_bytes(8)),0,4).'-'.substr(bin2hex(random_bytes(8)),0,4).'-'.substr(bin2hex(random_bytes(8)),0,4));$hash=hash('sha256',$code);$actor=pcUsuario();$stmt=$mysqli->prepare('UPDATE ti_pc_config SET enrollment_hash=?,enrollment_expires_at=DATE_ADD(NOW(),INTERVAL ? HOUR),enrollment_uses_remaining=?,updated_by=? WHERE id=1');$stmt->bind_param('siis',$hash,$hours,$uses,$actor);$stmt->execute();$stmt->close();$_SESSION['pc_activation_code']=$code;pcAuditWeb($mysqli,'CODIGO_ATIVACAO_GERADO',null,$uses.' uso(s), '.$hours.' hora(s).');pcFlash('ok','Codigo temporario gerado.');}
elseif($action==='limpar_nonces'){$mysqli->query("DELETE FROM ti_pc_nonces WHERE criado_em<DATE_SUB(NOW(),INTERVAL 2 DAY)");pcFlash('ok','Nonces antigos removidos.');}pcRedirect('inventario_pc_config.php');}catch(Throwable $e){pcFlash('err',$e->getMessage());pcRedirect('inventario_pc_config.php');}}
$cfg=pcConfig($mysqli);$flash=pcGetFlash();$code=$_SESSION['pc_activation_code']??null;unset($_SESSION['pc_activation_code']);$csrf=pcCsrf();
?><!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Configurar inventario Windows</title><link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet"><link href="inventario_mobile_style.css?v=3" rel="stylesheet"></head><body><div class="app"><header class="header"><div class="header-inner"><div class="brand"><div class="logo"><img src="assets/logo_pref.jpg" alt="Prefeitura"></div><div><span class="eyebrow"><i class="bi bi-windows"></i>Gerencia de Tecnologia</span><h1 class="title">Configurar agente Windows</h1><p class="subtitle">Ativacao temporaria, comunicacao, alertas e versionamento.</p></div></div><nav class="nav"><a href="inventario_computadores.php"><i class="bi bi-arrow-left"></i>Painel</a></nav></div></header><main class="main"><?php if($flash):?><div class="flash <?=$flash['tipo']==='ok'?'ok':'err'?>"><?=pcE($flash['msg'])?></div><?php endif;?><?php if($code):?><section class="form-card"><div class="codebox"><span>Codigo temporario</span><code><?=pcE($code)?></code></div><p class="callout warn">Copie agora. Valido ate <?=pcE($cfg['enrollment_expires_at']??'')?>; restam <?=(int)($cfg['enrollment_uses_remaining']??0)?> ativacoes.</p></section><?php endif;?><section class="two-col"><div class="form-card"><section class="form-section"><h3><i class="bi bi-key-fill"></i> Ativar computadores</h3><form method="post"><input type="hidden" name="csrf_token" value="<?=pcE($csrf)?>"><input type="hidden" name="acao" value="rotacionar"><div class="form-grid"><div class="group"><label>Validade em horas</label><input class="control" type="number" min="1" max="168" name="valid_hours" value="24"></div><div class="group"><label>Quantidade</label><input class="control" type="number" min="1" max="500" name="uses" value="1"></div></div><div class="form-actions"><button class="btn purple">Gerar codigo</button></div></form></section><?php if(pcAgentExists()):?><a class="btn primary" href="downloads/Agente-TI-Extrema-Windows.zip"><i class="bi bi-download"></i>Baixar instalador Windows</a><?php endif;?></div><div class="form-card"><section class="form-section"><h3><i class="bi bi-sliders"></i> Politicas</h3><form method="post"><input type="hidden" name="csrf_token" value="<?=pcE($csrf)?>"><input type="hidden" name="acao" value="salvar"><div class="form-grid"><div class="group"><label>Sincronizacao</label><select class="control" name="sync_interval_min"><?php foreach([15,30,60,120] as $v):?><option value="<?=$v?>" <?=$v==(int)$cfg['sync_interval_min']?'selected':''?>><?=$v?> minutos</option><?php endforeach;?></select></div><div class="group"><label>Recente (horas)</label><input class="control" type="number" name="recent_hours" value="<?=(int)$cfg['recent_hours']?>"></div><div class="group"><label>Sem comunicacao (horas)</label><input class="control" type="number" name="silent_hours" value="<?=(int)$cfg['silent_hours']?>"></div><div class="group"><label>Offline (horas)</label><input class="control" type="number" name="offline_hours" value="<?=(int)$cfg['offline_hours']?>"></div><div class="group"><label>Disco critico (%)</label><input class="control" type="number" name="storage_critical_percent" value="<?=(int)$cfg['storage_critical_percent']?>"></div><div class="group"><label>Versao atual</label><input class="control" name="current_agent_version" value="<?=pcE($cfg['current_agent_version'])?>"></div><div class="group"><label>Version code</label><input class="control" type="number" name="current_agent_version_code" value="<?=(int)$cfg['current_agent_version_code']?>"></div><div class="group"><label><input type="checkbox" name="api_enabled" value="1" <?=!empty($cfg['api_enabled'])?'checked':''?>> API habilitada</label></div></div><div class="form-actions"><button class="btn primary">Salvar</button></div></form></section></div></section><section class="form-card"><form method="post"><input type="hidden" name="csrf_token" value="<?=pcE($csrf)?>"><input type="hidden" name="acao" value="limpar_nonces"><button class="btn">Limpar nonces antigos</button></form></section></main></div></body></html>
