<?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();
if($_SERVER['REQUEST_METHOD']==='POST'){
 try{if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??''))throw new RuntimeException('Sessão expirada.');$action=(string)($_POST['action']??'');
  if($action==='organizer')afControlledEventAdminSetOrganizer($pdo,(int)$_POST['organizer_id'],(string)$_POST['status'],afAdminId(),trim((string)($_POST['reason']??'')));
  elseif($action==='event')afControlledEventAdminSetEventStatus($pdo,(int)$_POST['event_id'],(string)$_POST['status'],afAdminId(),trim((string)($_POST['reason']??'')));
  elseif($action==='purge')afControlledEventPurge($pdo,(int)$_POST['event_id'],'admin',afAdminId());
  elseif($action==='retention')afControlledEventProcessRetention($pdo,25,'admin',afAdminId());
  else throw new RuntimeException('Ação inválida.');
  afAdminLog($pdo,'controlled_event_admin_action','controlled_event',(int)($_POST['event_id']??$_POST['organizer_id']??0),['action'=>$action,'status'=>$_POST['status']??null]);setFlash('success','Ação registrada.');
 }catch(Throwable $e){setFlash('error',$e->getMessage());}
 header('Location: '.SITE_URL.'/pages/admin-eventos-infantis.php');exit;
}
$organizers=$pdo->query("SELECT o.*,u.nome,u.email,u.aura_id,a.idade_declarada,a.status_idade,(SELECT COUNT(*) FROM af_controlled_events e WHERE e.organizer_id=o.id) event_count FROM af_controlled_event_organizers o JOIN af_usuarios u ON u.id=o.usuario_id LEFT JOIN af_user_age_profiles a ON a.usuario_id=u.id ORDER BY FIELD(o.status,'pending','approved','suspended','revoked'),o.created_at DESC")->fetchAll()?:[];
$events=$pdo->query("SELECT e.*,o.organization_name,u.nome organizer_name,(SELECT COUNT(*) FROM af_controlled_event_participants p WHERE p.event_id=e.id AND p.status<>'purged') participant_count,(SELECT COUNT(*) FROM af_controlled_event_participants p WHERE p.event_id=e.id AND p.status IN ('authorized','checked_in','participating','completed')) authorized_count FROM af_controlled_events e JOIN af_controlled_event_organizers o ON o.id=e.organizer_id JOIN af_usuarios u ON u.id=o.usuario_id ORDER BY FIELD(e.status,'pending_approval','active','approved','draft','finished','cancelled','purged'),e.starts_at DESC LIMIT 300")->fetchAll()?:[];
$purges=$pdo->query("SELECT l.*,e.public_code,e.name,a.nome admin_name FROM af_controlled_event_purge_logs l JOIN af_controlled_events e ON e.id=l.event_id LEFT JOIN af_admin_users a ON a.id=l.executed_by_admin_id ORDER BY l.id DESC LIMIT 50")->fetchAll()?:[];
$pageTitle='Admin • Eventos infantis';$showNav=false;$bodyClass='admin-body';$adminPage='eventos_infantis';require __DIR__.'/../includes/header.php';
?>
<div class="admin-shell"><?php require __DIR__.'/../includes/admin_nav.php';?><main class="admin-main"><header class="admin-topbar"><div><small>ETAPA 23 • AMBIENTE CONTROLADO</small><h1>Eventos infantis</h1></div><span class="admin-count"><?=count($events)?> evento(s)</span></header><?=renderFlash()?>
<div class="admin-warning">Aprovar um evento não libera transmissão pública, comentários, mensagens ou progressão global. Essas travas são fixas no servidor.</div>
<section class="admin-section"><div class="admin-section-head"><h2>Contas de organizador</h2></div><div class="admin-cards-list"><?php if(!$organizers):?><div class="admin-empty">Nenhuma solicitação.</div><?php endif?><?php foreach($organizers as $o):?><article class="admin-report-card"><header><div><span class="admin-pill"><?=esc($o['status'])?></span><b><?=esc($o['organization_name']?:$o['nome'])?></b></div><time><?=date('d/m/Y H:i',strtotime($o['created_at']))?></time></header><div class="admin-report-grid"><p><small>RESPONSÁVEL</small><b><?=esc($o['nome'])?></b><span><?=esc($o['email'])?></span></p><p><small>IDADE</small><b><?=(int)$o['idade_declarada']?> anos</b><span><?=esc($o['status_idade']??'pendente')?></span></p><p><small>EVENTOS</small><b><?=(int)$o['event_count']?></b><span><?=esc($o['contact_phone']??'')?></span></p></div><form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="action" value="organizer"><input type="hidden" name="organizer_id" value="<?=(int)$o['id']?>"><textarea name="reason" rows="2" placeholder="Justificativa de aprovação, suspensão ou revogação"></textarea><div class="admin-action-row"><button class="admin-primary" name="status" value="approved">Aprovar</button><button class="admin-danger" name="status" value="suspended">Suspender</button><button class="admin-danger" name="status" value="revoked">Revogar</button></div></form></article><?php endforeach?></div></section>
<section class="admin-section"><div class="admin-section-head"><h2>Fila de eventos</h2><form method="post"><?=camposCsrf()?><input type="hidden" name="action" value="retention"><button class="admin-primary">PROCESSAR RETENÇÃO VENCIDA</button></form></div><div class="admin-cards-list"><?php if(!$events):?><div class="admin-empty">Nenhum evento cadastrado.</div><?php endif?><?php foreach($events as $e):?><article class="admin-report-card"><header><div><span class="admin-pill"><?=esc($e['status'])?></span><b><?=esc($e['name'])?> • <?=esc($e['public_code'])?></b></div><time><?=date('d/m/Y H:i',strtotime($e['starts_at']))?></time></header><div class="admin-report-grid"><p><small>ORGANIZAÇÃO</small><b><?=esc($e['organization_name'])?></b><span><?=esc($e['organizer_name'])?></span></p><p><small>PARTICIPANTES</small><b><?=(int)$e['authorized_count']?> autorizados</b><span><?=(int)$e['participant_count']?> / <?=(int)$e['capacity']?></span></p><p><small>EXCLUSÃO</small><b><?=date('d/m/Y',strtotime($e['purge_after']))?></b><span><?=(int)$e['retention_days']?> dias</span></p></div><p class="admin-report-text"><b>Área de câmera:</b> <?=esc($e['camera_area_instructions'])?></p><p class="admin-report-text"><b>Plano:</b> <?=esc($e['safety_plan'])?></p><form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="action" value="event"><input type="hidden" name="event_id" value="<?=(int)$e['id']?>"><textarea name="reason" rows="2" placeholder="Justificativa administrativa"></textarea><div class="admin-action-row"><?php if(in_array($e['status'],['draft','pending_approval'],true)):?><button class="admin-primary" name="status" value="approved">APROVAR EVENTO</button><?php endif?><?php if($e['status']!=='purged'):?><button class="admin-danger" name="status" value="cancelled">CANCELAR</button><?php endif?></div></form><?php if(in_array($e['status'],['finished','cancelled'],true)):?><form method="post" onsubmit="return confirm('Excluir agora os dados operacionais deste evento?')"><?=camposCsrf()?><input type="hidden" name="action" value="purge"><input type="hidden" name="event_id" value="<?=(int)$e['id']?>"><button class="admin-danger">EXECUTAR EXCLUSÃO AGORA</button></form><?php endif?></article><?php endforeach?></div></section>
<section class="admin-section"><div class="admin-section-head"><h2>Últimas execuções de retenção</h2></div><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Evento</th><th>Modo</th><th>Status</th><th>Data</th></tr></thead><tbody><?php foreach($purges as $p):?><tr><td><?=esc($p['public_code'].' • '.$p['name'])?></td><td><?=esc($p['execution_mode'])?></td><td><?=esc($p['status'])?></td><td><?=date('d/m/Y H:i',strtotime($p['created_at']))?></td></tr><?php endforeach?></tbody></table></div></section>
</main></div><script src="<?=SITE_URL?>/assets/js/admin.js?v=23.0"></script><?php require __DIR__.'/../includes/footer.php';?>
