<?php
declare(strict_types=1);
require_once __DIR__.'/auth.php';
require_once __DIR__.'/conexao.php';
require_once __DIR__.'/inventario_mobile_helpers.php';
date_default_timezone_set('America/Sao_Paulo');
if(function_exists('tiPermExigir')) tiPermExigir($mysqli,'inventario_mobile','administrar');
$mysqli->set_charset('utf8mb4');
$csrf=mobCsrf();$flash=mobGetFlash();$novoCodigo=null;

if($_SERVER['REQUEST_METHOD']==='POST'){
 try{
  mobCheckCsrf();$action=mobText($_POST['acao']??'',40);$user=mobUsuario();
  if($action==='salvar'){
   $interval=(int)($_POST['sync_interval_min']??30);if(!in_array($interval,[15,30,60,120],true))throw new RuntimeException('Intervalo inválido.');
   $recent=max(1,min(12,(int)($_POST['recent_hours']??2)));$silent=max($recent,min(168,(int)($_POST['silent_hours']??24)));$offline=max($silent,min(2160,(int)($_POST['offline_alert_hours']??168)));
   $storage=max(3,min(40,(int)($_POST['storage_critical_percent']??10)));$patchAge=max(30,min(1460,(int)($_POST['security_patch_max_age_days']??365)));$minSdk=max(21,min(40,(int)($_POST['min_android_sdk']??29)));
   $version=mobText($_POST['current_app_version']??'1.0.0',40);$versionCode=max(1,(int)($_POST['current_app_version_code']??1));$apps=!empty($_POST['collect_apps'])?1:0;$api=!empty($_POST['api_enabled'])?1:0;
   $stmt=$mysqli->prepare('UPDATE ti_mobile_config SET sync_interval_min=?,recent_hours=?,silent_hours=?,offline_alert_hours=?,storage_critical_percent=?,security_patch_max_age_days=?,min_android_sdk=?,current_app_version=?,current_app_version_code=?,collect_apps=?,api_enabled=?,updated_by=? WHERE id=1');
   $stmt->bind_param('iiiiiiisiiis',$interval,$recent,$silent,$offline,$storage,$patchAge,$minSdk,$version,$versionCode,$apps,$api,$user);$stmt->execute();$stmt->close();
   mobFlash('ok','Configurações atualizadas.');mobRedirect('inventario_mobile_config.php');
  }
  if($action==='rotacionar'){
   $novoCodigo=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',$novoCodigo);
   $hours=max(1,min(168,(int)($_POST['valid_hours']??24)));$uses=max(1,min(500,(int)($_POST['uses']??1)));
   $stmt=$mysqli->prepare('UPDATE ti_mobile_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,$user);$stmt->execute();$stmt->close();
  }
  if($action==='app_save'){
   $package=strtolower(mobText($_POST['package_name']??'',220));$label=mobText($_POST['app_label']??'',220);$required=!empty($_POST['obrigatorio'])?1:0;
   if(!preg_match('/^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)+$/',$package)||$label==='')throw new RuntimeException('Informe um package name e nome válidos.');
   $stmt=$mysqli->prepare('INSERT INTO ti_mobile_apps_catalogo(package_name,app_label,obrigatorio,ativo) VALUES(?,?,?,1) ON DUPLICATE KEY UPDATE app_label=VALUES(app_label),obrigatorio=VALUES(obrigatorio),ativo=1');
   $stmt->bind_param('ssi',$package,$label,$required);$stmt->execute();$stmt->close();mobFlash('ok','Aplicativo corporativo salvo.');mobRedirect('inventario_mobile_config.php#apps');
  }
  if($action==='app_disable'){$id=(int)($_POST['app_id']??0);$stmt=$mysqli->prepare('UPDATE ti_mobile_apps_catalogo SET ativo=0 WHERE id=?');$stmt->bind_param('i',$id);$stmt->execute();$stmt->close();mobFlash('ok','Aplicativo removido da coleta futura.');mobRedirect('inventario_mobile_config.php#apps');}
  if($action==='limpar_nonces'){$mysqli->query("DELETE FROM ti_mobile_nonces WHERE criado_em<DATE_SUB(NOW(),INTERVAL 2 DAY)");mobFlash('ok','Nonces antigos removidos.');mobRedirect('inventario_mobile_config.php');}
 }catch(Throwable $e){mobFlash('err',$e->getMessage());mobRedirect('inventario_mobile_config.php');}
}
$cfg=mobConfig($mysqli);$catalog=[];if(mobTableExists($mysqli,'ti_mobile_apps_catalogo')){$r=$mysqli->query('SELECT * FROM ti_mobile_apps_catalogo WHERE ativo=1 ORDER BY app_label');while($r&&$row=$r->fetch_assoc())$catalog[]=$row;}
?>
<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Configurar Inventário Android</title><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet"><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=2" rel="stylesheet"></head><body><div class="topline"></div><div class="gridbg"></div><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-gear-fill"></i>Administração</span><h1 class="title">Inventário Android</h1><p class="subtitle">Ativação temporária, periodicidade, alertas, aplicativos e distribuição do agente.</p></div></div><nav class="nav"><a class="primary" href="inventario_equipamentos.php"><i class="bi bi-arrow-left"></i>Voltar</a></nav></div></header>
<main class="main"><?php if($flash):?><div class="flash <?=$flash['tipo']==='ok'?'ok':'err'?>"><?=mobE($flash['msg'])?></div><?php endif;?>
<?php if($novoCodigo):?><section class="form-card"><div class="codebox"><div><small>NOVO CÓDIGO — COPIE AGORA</small><code><?=mobE($novoCodigo)?></code></div><i class="bi bi-key-fill"></i></div><p class="callout warn">O servidor armazena somente o hash. Validade: <?=mobE($_POST['valid_hours']??24)?>h; usos: <?=mobE($_POST['uses']??1)?>.</p></section><?php endif;?>
<section class="form-card" id="ativacao"><section class="form-section"><h3><i class="bi bi-key-fill"></i> Ativação de dispositivos</h3><p class="callout">Após o uso do código temporário, o aparelho recebe um token individual. O segredo completo nunca aparece em logs nem no banco.</p><form method="post"><input type="hidden" name="csrf_token" value="<?=mobE($csrf)?>"><input type="hidden" name="acao" value="rotacionar"><div class="form-grid"><div class="group"><label>Validade (horas)</label><input class="control" type="number" min="1" max="168" name="valid_hours" value="24"></div><div class="group"><label>Quantidade de ativações</label><input class="control" type="number" min="1" max="500" name="uses" value="1"></div></div><div class="form-actions"><button class="btn purple" type="submit">Gerar código temporário</button></div></form></section>
<section class="form-section"><h3><i class="bi bi-sliders"></i> Regras e versão</h3><form method="post"><input type="hidden" name="csrf_token" value="<?=mobE($csrf)?>"><input type="hidden" name="acao" value="salvar"><div class="form-grid">
<div class="group"><label>Intervalo</label><select class="control" name="sync_interval_min"><?php foreach([15,30,60,120] as $m):?><option value="<?=$m?>" <?=$m===(int)($cfg['sync_interval_min']??30)?'selected':''?>><?=$m?> minutos</option><?php endforeach;?></select></div>
<div class="group"><label>Comunicação recente (h)</label><input class="control" type="number" min="1" max="12" name="recent_hours" value="<?=(int)($cfg['recent_hours']??2)?>"></div><div class="group"><label>Sem comunicação (h)</label><input class="control" type="number" min="2" max="168" name="silent_hours" value="<?=(int)($cfg['silent_hours']??24)?>"></div><div class="group"><label>Offline prolongado (h)</label><input class="control" type="number" min="24" max="2160" name="offline_alert_hours" value="<?=(int)($cfg['offline_alert_hours']??168)?>"></div>
<div class="group"><label>Armazenamento crítico (%)</label><input class="control" type="number" min="3" max="40" name="storage_critical_percent" value="<?=(int)($cfg['storage_critical_percent']??10)?>"></div><div class="group"><label>Patch antigo (dias)</label><input class="control" type="number" min="30" max="1460" name="security_patch_max_age_days" value="<?=(int)($cfg['security_patch_max_age_days']??365)?>"></div><div class="group"><label>API Android mínima</label><input class="control" type="number" min="21" max="40" name="min_android_sdk" value="<?=(int)($cfg['min_android_sdk']??29)?>"></div>
<div class="group"><label>Versão atual</label><input class="control" name="current_app_version" value="<?=mobE($cfg['current_app_version']??'1.0.0')?>"></div><div class="group"><label>Version code</label><input class="control" type="number" min="1" name="current_app_version_code" value="<?=(int)($cfg['current_app_version_code']??1)?>"></div>
<div class="group"><label style="display:flex;gap:7px;align-items:center;text-transform:none"><input type="checkbox" name="collect_apps" value="1" <?=!empty($cfg['collect_apps'])?'checked':''?>>Monitorar apps configurados</label></div><div class="group"><label style="display:flex;gap:7px;align-items:center;text-transform:none"><input type="checkbox" name="api_enabled" value="1" <?=!empty($cfg['api_enabled'])?'checked':''?>>API ativa</label></div></div><div class="form-actions"><button class="btn primary" type="submit">Salvar configurações</button></div></form></section>
<section class="form-section" id="apps"><h3><i class="bi bi-grid-fill"></i> Aplicativos monitorados</h3><p class="callout">O agente consulta somente estes pacotes declarados; não solicita acesso à lista completa de apps.</p><form method="post"><input type="hidden" name="csrf_token" value="<?=mobE($csrf)?>"><input type="hidden" name="acao" value="app_save"><div class="form-grid"><div class="group"><label>Nome</label><input class="control" name="app_label" required></div><div class="group"><label>Package name</label><input class="control" name="package_name" required placeholder="br.gov.extrema.app"></div><div class="group"><label style="display:flex;gap:7px;align-items:center;text-transform:none"><input type="checkbox" name="obrigatorio" value="1">Obrigatório</label></div></div><div class="form-actions"><button class="btn primary" type="submit">Adicionar aplicativo</button></div></form><div class="timeline"><?php foreach($catalog as $app):?><article class="event"><span class="event-icon"><i class="bi bi-app-indicator"></i></span><div><strong><?=mobE($app['app_label'])?> <?=$app['obrigatorio']?'• obrigatório':''?></strong><p><?=mobE($app['package_name'])?></p></div><form method="post"><input type="hidden" name="csrf_token" value="<?=mobE($csrf)?>"><input type="hidden" name="acao" value="app_disable"><input type="hidden" name="app_id" value="<?=(int)$app['id']?>"><button class="mini">Remover</button></form></article><?php endforeach;?></div></section>
<section class="form-section"><h3><i class="bi bi-download"></i> Distribuição</h3><div class="detail-grid"><div class="detail"><span>APK</span><strong><?=mobApkExists()?'Publicado':'Ainda não publicado'?></strong></div><div class="detail"><span>Versão publicada</span><strong><?=mobE($cfg['current_app_version']??'1.0.0')?></strong></div><div class="detail"><span>Projeto Android</span><strong><?=mobAgentSourceExists()?'Disponível':'Será atualizado ao finalizar'?></strong></div></div></section></section></main></div></body></html>
