<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/admin_functions.php';
afAdminRequireAuth();

$adminId = afAdminId();
$modeRequested = (string)($_GET['mode'] ?? afStage25CurrentMode($pdo));
if (!array_key_exists($modeRequested, afStage25ReleaseModes())) $modeRequested = afStage25CurrentMode($pdo);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!validarCsrfToken($_POST[CSRF_TOKEN_NAME] ?? '')) throw new RuntimeException('Sessão expirada.');
        $acao = (string)($_POST['acao'] ?? '');
        if ($acao === 'rodar_testes') {
            $releaseMode = (string)($_POST['release_mode'] ?? afStage25CurrentMode($pdo));
            $res = afStage25RunAutomatedChecklist($pdo, $adminId, 'manual', $releaseMode);
            if ($res['status'] === 'passed') setFlash('success', 'Checklist da Etapa 25 aprovada com '.$res['summary']['pass_rate'].'%.');
            else setFlash('error', 'Checklist reprovada. Corrija os itens marcados antes de liberar menores.');
            header('Location: '.SITE_URL.'/pages/admin-liberacao-controlada.php?mode='.rawurlencode($releaseMode)); exit;
        }
        if ($acao === 'aprovar_liberacao') {
            $releaseMode = (string)($_POST['release_mode'] ?? 'adults_only');
            $days = (int)($_POST['expires_days'] ?? afStage25Config($pdo, 'stage25_release_expires_days', 30));
            $approval = afStage25ApproveRelease($pdo, $adminId, $releaseMode, (string)($_POST['note'] ?? ''), $days);
            setFlash('success', 'Liberação controlada ativada: '.$approval['mode'].($approval['expires_at'] ? ' até '.date('d/m/Y H:i', strtotime($approval['expires_at'])) : '.'));
            header('Location: '.SITE_URL.'/pages/admin-liberacao-controlada.php?mode='.rawurlencode($releaseMode)); exit;
        }
        if ($acao === 'revogar_liberacao') {
            afStage25RevokeRelease($pdo, $adminId, (string)($_POST['reason'] ?? 'Revogado no painel da Etapa 25.'));
            setFlash('success', 'Liberação revogada. O sistema voltou para somente adultos.');
            header('Location: '.SITE_URL.'/pages/admin-liberacao-controlada.php'); exit;
        }
        throw new RuntimeException('Ação inválida.');
    } catch (Throwable $e) {
        setFlash('error', $e->getMessage());
        header('Location: '.SITE_URL.'/pages/admin-liberacao-controlada.php?mode='.rawurlencode($modeRequested)); exit;
    }
}

$metrics = afStage25Metrics($pdo);
$modes = afStage25ReleaseModes();
$checklist = afStage25BuildChecklist($pdo, $modeRequested, true);
$summary = afStage25ChecklistSummary($checklist);
$canApprove = afStage25ReleaseCanApprove($pdo, $modeRequested);
$latestRun = $metrics['latest_run'];
$activeRelease = $metrics['active_release'];
$recentRuns = [];
$recentApprovals = [];
try {
    if (afStage25TableExists($pdo,'af_stage25_test_runs')) {
        $recentRuns = $pdo->query('SELECT r.*,a.nome admin_nome FROM af_stage25_test_runs r LEFT JOIN af_admin_users a ON a.id=r.initiated_by_admin_id ORDER BY r.id DESC LIMIT 10')->fetchAll();
    }
    if (afStage25TableExists($pdo,'af_stage25_release_approvals')) {
        $recentApprovals = $pdo->query('SELECT r.*,a.nome admin_nome FROM af_stage25_release_approvals r LEFT JOIN af_admin_users a ON a.id=r.approved_by_admin_id ORDER BY r.id DESC LIMIT 10')->fetchAll();
    }
} catch (Throwable $e) {}

$pageTitle = 'Etapa 25 — Liberação controlada';
$hidePublicNav = true;
$bodyClass = 'admin-body';
$adminPage = 'liberacao_controlada';
require __DIR__.'/../includes/header.php';
?>
<div class="admin-shell">
<?php require __DIR__.'/../includes/admin_nav.php'; ?>
<main class="admin-main stage25-admin">
  <header class="admin-topbar">
    <div><small>ETAPA 25</small><h1>Testes e liberação controlada</h1></div>
    <span class="admin-count">v<?=esc(STAGE25_RELEASE_VERSION)?> • <?=date('d/m/Y H:i')?></span>
  </header>
  <?=renderFlash()?>

  <section class="stage25-status-card mode-<?=esc((string)$metrics['mode'])?>">
    <div>
      <small>Modo atual do sistema</small>
      <h2><?=esc($modes[(string)$metrics['mode']]['label'] ?? (string)$metrics['mode'])?></h2>
      <p><?=esc($modes[(string)$metrics['mode']]['description'] ?? '')?></p>
      <?php if($activeRelease): ?>
        <p class="stage25-note">Aprovado por <?=esc($activeRelease['admin_nome'] ?: 'admin')?> em <?=date('d/m/Y H:i', strtotime((string)$activeRelease['approved_at']))?><?=!empty($activeRelease['expires_at'])?' • expira em '.date('d/m/Y H:i', strtotime((string)$activeRelease['expires_at'])):''?>.</p>
      <?php else: ?>
        <p class="stage25-note danger">Nenhuma liberação ativa. Menores continuam bloqueados fora das rotinas essenciais.</p>
      <?php endif; ?>
    </div>
    <form method="post" class="stage25-revoke-form"><?=camposCsrf()?><input type="hidden" name="acao" value="revogar_liberacao"><input name="reason" placeholder="Motivo da revogação"><button class="danger" onclick="return confirm('Revogar liberação de menores agora?')">Revogar e voltar para adultos</button></form>
  </section>

  <section class="admin-kpi-grid report-kpis">
    <article><span>✅</span><div><small>Status da checklist</small><strong><?=esc($summary['status'])?></strong></div></article>
    <article><span>📊</span><div><small>Aprovação</small><strong><?=number_format((float)$summary['pass_rate'],2,',','.')?>%</strong></div></article>
    <article><span>🚨</span><div><small>Falhas críticas</small><strong><?=(int)$summary['critical_failures']?></strong></div></article>
    <article><span>🔥</span><div><small>Alertas críticos</small><strong><?=(int)$metrics['critical_alerts']?></strong></div></article>
    <article><span>👶</span><div><small>Contas menores</small><strong><?=(int)$metrics['minor_accounts']?></strong></div></article>
    <article><span>🎟️</span><div><small>Eventos ativos</small><strong><?=(int)$metrics['active_events']?></strong></div></article>
  </section>

  <section class="admin-card stage25-mode-select">
    <h2>Escolher modo para testar/aprovar</h2>
    <div class="stage25-mode-grid">
      <?php foreach($modes as $key=>$m): ?>
        <a class="stage25-mode <?=$modeRequested===$key?'active':''?>" href="?mode=<?=rawurlencode($key)?>"><b><?=esc($m['label'])?></b><small><?=esc($key)?></small><p><?=esc($m['description'])?></p></a>
      <?php endforeach; ?>
    </div>
  </section>

  <section class="admin-grid-two">
    <article class="admin-card">
      <h2>Checklist automática</h2>
      <p>Execute a bateria final depois de instalar todas as etapas, configurar o controlador, aprovar o relatório jurídico e revisar os alertas da Etapa 24.</p>
      <form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="acao" value="rodar_testes"><input type="hidden" name="release_mode" value="<?=esc($modeRequested)?>"><button class="admin-primary">Rodar testes da Etapa 25</button></form>
      <?php if($latestRun): ?><p class="stage25-note">Último teste: #<?=(int)$latestRun['id']?> • <?=esc($latestRun['status'])?> • <?=number_format((float)$latestRun['pass_rate'],2,',','.')?>% • <?=date('d/m/Y H:i', strtotime((string)$latestRun['started_at']))?></p><?php endif; ?>
    </article>
    <article class="admin-card">
      <h2>Aprovação de liberação</h2>
      <?php if(!empty($canApprove['allowed'])): ?>
        <p class="stage25-pass">Modo apto para liberação controlada.</p>
        <form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="acao" value="aprovar_liberacao"><input type="hidden" name="release_mode" value="<?=esc($modeRequested)?>"><input type="number" name="expires_days" min="1" max="365" value="<?=esc((string)afStage25Config($pdo,'stage25_release_expires_days',30))?>" placeholder="dias"><input name="note" placeholder="Observação da aprovação"><button class="admin-primary" onclick="return confirm('Ativar este modo de liberação?')">Aprovar <?=esc($modes[$modeRequested]['label'])?></button></form>
      <?php else: ?>
        <p class="stage25-fail">Bloqueado: <?=esc((string)($canApprove['message'] ?? 'Itens pendentes.'))?></p>
        <small>Código: <?=esc((string)($canApprove['code'] ?? ''))?></small>
      <?php endif; ?>
    </article>
  </section>

  <section class="admin-card">
    <h2>Itens avaliados para <?=esc($modes[$modeRequested]['label'])?></h2>
    <div class="stage25-checklist">
      <?php foreach($checklist as $item): ?>
        <article class="stage25-check status-<?=esc($item['status'])?> severity-<?=esc($item['severity'])?>">
          <span><?=($item['status']==='passed')?'✓':(($item['status']==='warning')?'!':'×')?></span>
          <div><b><?=esc($item['title'])?></b><small><?=esc($item['category'])?> • <?=esc($item['severity'])?> • <?=esc($item['key'])?></small><p><?=esc($item['message'])?></p></div>
        </article>
      <?php endforeach; ?>
    </div>
  </section>

  <section class="admin-grid-two">
    <article class="admin-card"><h2>Últimas baterias de teste</h2>
      <?php if(!$recentRuns): ?><p class="admin-empty">Nenhum teste executado.</p><?php endif; ?>
      <?php foreach($recentRuns as $r): ?><div class="stage25-log-row"><b>#<?=(int)$r['id']?> • <?=esc($r['status'])?> • <?=esc($r['release_mode'])?></b><small><?=number_format((float)$r['pass_rate'],2,',','.')?>% • <?=esc($r['admin_nome'] ?: 'sistema')?> • <?=date('d/m/Y H:i', strtotime((string)$r['started_at']))?></small></div><?php endforeach; ?>
    </article>
    <article class="admin-card"><h2>Histórico de liberações</h2>
      <?php if(!$recentApprovals): ?><p class="admin-empty">Nenhuma liberação registrada.</p><?php endif; ?>
      <?php foreach($recentApprovals as $r): ?><div class="stage25-log-row"><b><?=esc($r['release_mode'])?> • <?=esc($r['status'])?></b><small><?=esc($r['admin_nome'] ?: 'sistema')?> • <?=!empty($r['approved_at'])?date('d/m/Y H:i', strtotime((string)$r['approved_at'])):'—'?><?=!empty($r['expires_at'])?' • expira '.date('d/m/Y H:i', strtotime((string)$r['expires_at'])):''?></small></div><?php endforeach; ?>
    </article>
  </section>

  <section class="admin-warning">
    A Etapa 25 não libera recursos públicos de alto risco para menores. Live pública, mensagens com desconhecidos, compartilhamento público, replay com imagem real e download de vídeo continuam bloqueados pela política central.
  </section>
</main>
</div>
<link rel="stylesheet" href="<?=SITE_URL?>/assets/css/admin-auditoria.css?v=24.0">
<link rel="stylesheet" href="<?=SITE_URL?>/assets/css/stage25-release.css?v=25.0">
<script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script>
<?php require __DIR__.'/../includes/footer.php'; ?>
