<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';
requireLogin();
afControlledEventMaybeProcessRetention($pdo);
$uid=(int)$_SESSION['usuario_id'];$errors=[];
$organizer=afControlledEventOrganizer($pdo,$uid);
if($_SERVER['REQUEST_METHOD']==='POST'){
    try{
        if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??''))throw new RuntimeException('Sessão expirada.');
        $action=(string)($_POST['action']??'');
        if($action==='request_organizer'){
            afControlledEventRequestOrganizer($pdo,$uid,(string)($_POST['organization_name']??''),(string)($_POST['contact_phone']??''));
            setFlash('success','Solicitação de organizador enviada para análise administrativa.');
        }elseif($action==='create_event'){
            $event=afControlledEventCreate($pdo,$uid,$_POST);setFlash('success','Evento criado como rascunho. Revise a lista e envie para aprovação.');
            header('Location: '.SITE_URL.'/pages/organizador-eventos.php?event='.(int)$event['id']);exit;
        }elseif(in_array($action,['submit','activate','finish','cancel'],true)){
            afControlledEventUpdateStatusByOrganizer($pdo,(int)($_POST['event_id']??0),$uid,$action);setFlash('success','Evento atualizado.');
        }elseif($action==='add_participant'){
            afControlledEventAddParticipant($pdo,(int)($_POST['event_id']??0),$uid,(string)($_POST['identifier']??''));setFlash('success','Participante incluído. O responsável recebeu uma solicitação de autorização.');
        }elseif($action==='remove_participant'){
            afControlledEventRemoveParticipant($pdo,(int)($_POST['event_id']??0),$uid,(int)($_POST['participant_id']??0),(string)($_POST['reason']??'Removido pela organização'));setFlash('success','Participante removido e credencial revogada.');
        }elseif($action==='start_supervision'){
            afControlledEventStartSupervision($pdo,(int)($_POST['event_id']??0),$uid);setFlash('success','Supervisão presencial ativada neste dispositivo.');
        }else throw new RuntimeException('Ação inválida.');
    }catch(Throwable $e){$errors[]=$e->getMessage();}
    if(!$errors){header('Location: '.SITE_URL.'/pages/organizador-eventos.php'.(!empty($_POST['event_id'])?'?event='.(int)$_POST['event_id']:''));exit;}
}
$organizer=afControlledEventOrganizer($pdo,$uid);$events=$organizer&&$organizer['status']==='approved'?afControlledEventListForOrganizer($pdo,$uid):[];
$eventId=max(0,(int)($_GET['event']??0));$current=null;$participants=[];$supervision=false;
if($eventId>0&&$organizer&&$organizer['status']==='approved'){
    try{$current=afControlledEventAssertOrganizerOwns($pdo,$eventId,$uid);$participants=afControlledEventParticipants($pdo,$eventId);$supervision=afControlledEventHasActiveSupervision($pdo,$eventId);}catch(Throwable $e){$errors[]=$e->getMessage();}
}
$pageTitle='Organizador de eventos infantis';$showNav=false;$pageStyles=[SITE_URL.'/assets/css/eventos-infantis.css?v=23.0'];$pageScripts=[SITE_URL.'/assets/vendor/qrcode/aura-qrcode.js?v=1.0',SITE_URL.'/assets/js/eventos-infantis.js?v=23.0'];require __DIR__.'/../includes/header.php';
?>
<header class="app-header"><a href="<?=SITE_URL?>/pages/home.php" class="btn-back">← Início</a><div class="logo-inline"><span class="logo-main">AURA</span><span class="logo-sub">EVENTOS</span></div><a href="<?=SITE_URL?>/pages/evento-infantil.php" class="btn-notif">🎟️</a></header>
<main class="event-shell">
<?=renderFlash()?><?php if($errors):?><div class="flash flash--error"><span>✕</span><?=esc(implode(' | ',$errors))?></div><?php endif?>
<section class="event-hero"><div class="event-hero__icon">🛡️</div><div><small>ETAPA 23</small><h1>MODO EVENTO INFANTIL</h1><p>Participação antecipada, autorização do responsável, QR individual, área de câmera delimitada, supervisão presencial, ranking fechado e exclusão programada dos dados.</p></div></section>
<?php if(!$organizer):?>
<section class="event-card"><h2>Solicitar conta de organizador</h2><p>A conta precisa ser adulta e confirmada. A administração analisa a solicitação antes de permitir eventos infantis.</p><form method="post" class="event-form"><?=camposCsrf()?><input type="hidden" name="action" value="request_organizer"><label><span>Organização ou responsável pelo evento</span><input name="organization_name" maxlength="180" required></label><label><span>Telefone de contato</span><input name="contact_phone" maxlength="30" required></label><button class="btn btn-primary" type="submit">ENVIAR SOLICITAÇÃO</button></form></section>
<?php elseif($organizer['status']!=='approved'):?>
<div class="event-warning"><span>⏳</span><div><b>Conta de organizador: <?=esc(strtoupper($organizer['status']))?></b><p>A criação de eventos permanece bloqueada até a aprovação administrativa.</p></div></div>
<?php else:?>
<?php if($current&&$current['status']==='active'):?><div class="event-supervision <?=$supervision?'':'is-off'?>" data-supervision-event="<?=(int)$current['id']?>"><b data-supervision-status><?=$supervision?'SUPERVISÃO ATIVA':'ATIVANDO SUPERVISÃO...'?></b><span>Mantenha esta tela aberta durante as partidas.</span></div><?php endif?>
<div class="event-grid">
<article class="event-card"><small>EVENTOS</small><h2><?=count($events)?></h2><p>criados por esta conta</p></article>
<article class="event-card"><small>ORGANIZADOR</small><h2>APROVADO</h2><p><?=esc((string)$organizer['organization_name'])?></p></article>
<article class="event-card"><small>REGRAS FIXAS</small><h2>SEM LIVE</h2><p>comentários e mensagens também bloqueados</p></article>
</div>

<?php if($current):?>
<section class="event-card" style="margin-top:18px"><div style="display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap"><div><small>EVENTO <?=esc($current['public_code'])?></small><h2><?=esc($current['name'])?></h2><span class="event-status event-status--<?=esc($current['status'])?>"><?=esc(strtoupper($current['status']))?></span></div><a class="btn btn-secondary" href="<?=SITE_URL?>/pages/organizador-eventos.php">← TODOS OS EVENTOS</a></div>
<div class="event-meta"><span>📅 <?=date('d/m/Y H:i',strtotime($current['starts_at']))?></span><span>📍 <?=esc($current['venue_name'])?></span><span>👧 <?=count($participants)?> / <?=(int)$current['capacity']?></span><span>🗑️ retenção <?=(int)$current['retention_days']?> dias</span></div>
<div class="event-warning"><span>📷</span><div><b>Área delimitada</b><p><?=nl2br(esc($current['camera_area_instructions']))?></p></div></div>
<div class="event-actions">
<?php if($current['status']==='draft'):?><form method="post"><?=camposCsrf()?><input type="hidden" name="action" value="submit"><input type="hidden" name="event_id" value="<?=(int)$current['id']?>"><button class="btn btn-primary">ENVIAR PARA APROVAÇÃO</button></form><?php endif?>
<?php if($current['status']==='approved'):?><form method="post"><?=camposCsrf()?><input type="hidden" name="action" value="activate"><input type="hidden" name="event_id" value="<?=(int)$current['id']?>"><button class="btn btn-primary">ATIVAR EVENTO E SUPERVISÃO</button></form><?php endif?>
<?php if($current['status']==='active'):?><form method="post"><?=camposCsrf()?><input type="hidden" name="action" value="start_supervision"><input type="hidden" name="event_id" value="<?=(int)$current['id']?>"><button class="btn btn-outline-cyan">REATIVAR SUPERVISÃO</button></form><a class="btn btn-primary" href="<?=SITE_URL?>/pages/evento-checkin.php?event=<?=(int)$current['id']?>">ABRIR CHECK-IN</a><form method="post" onsubmit="return confirm('Encerrar o evento agora?')"><?=camposCsrf()?><input type="hidden" name="action" value="finish"><input type="hidden" name="event_id" value="<?=(int)$current['id']?>"><button class="btn btn-secondary">ENCERRAR EVENTO</button></form><?php endif?>
<a class="btn btn-secondary" href="<?=SITE_URL?>/pages/evento-ranking.php?event=<?=(int)$current['id']?>">RANKING FECHADO</a>
<?php if(in_array($current['status'],['draft','pending_approval','approved'],true)):?><form method="post" onsubmit="return confirm('Cancelar este evento?')"><?=camposCsrf()?><input type="hidden" name="action" value="cancel"><input type="hidden" name="event_id" value="<?=(int)$current['id']?>"><button class="btn btn-secondary">CANCELAR</button></form><?php endif?>
</div></section>
<?php if(in_array($current['status'],['draft','pending_approval','approved'],true)):?><section class="event-card" style="margin-top:18px"><h2>Lista antecipada de participantes</h2><form method="post" class="event-form-grid"><?=camposCsrf()?><input type="hidden" name="action" value="add_participant"><input type="hidden" name="event_id" value="<?=(int)$current['id']?>"><label><span>Aura ID ou e-mail da conta menor</span><input name="identifier" required placeholder="AURA-0000 ou email"></label><label style="align-self:end"><button class="btn btn-primary" type="submit">ADICIONAR PARTICIPANTE</button></label></form></section><?php endif?>
<section class="event-card" style="margin-top:18px"><h2>Participantes</h2><?php if(!$participants):?><p>Nenhum participante cadastrado.</p><?php else:?><div class="event-table-wrap"><table class="event-table"><thead><tr><th>Participante</th><th>Responsável</th><th>Status</th><th>QR/código</th><th>Ação</th></tr></thead><tbody><?php foreach($participants as $p):?><tr><td><b><?=esc($p['username'])?></b><br><small><?=esc($p['aura_id'])?></small></td><td><?=esc($p['guardian_name'])?><br><small><?=esc($p['guardian_email'])?></small></td><td><span class="event-status event-status--<?=esc($p['status'])?>"><?=esc(strtoupper($p['status']))?></span></td><td><?=!empty($p['short_code'])?'<b>'.esc($p['short_code']).'</b>':'Aguardando autorização'?></td><td><?php if(!in_array($p['status'],['removed','purged'],true)):?><form method="post" onsubmit="return confirm('Remover este participante e revogar a credencial?')"><?=camposCsrf()?><input type="hidden" name="action" value="remove_participant"><input type="hidden" name="event_id" value="<?=(int)$current['id']?>"><input type="hidden" name="participant_id" value="<?=(int)$p['id']?>"><input type="hidden" name="reason" value="Removido pela organização"><button class="btn btn-secondary" type="submit">REMOVER</button></form><?php endif?></td></tr><?php endforeach?></tbody></table></div><?php endif?></section>
<?php else:?>
<section class="event-card" style="margin-top:18px"><h2>Criar novo evento</h2><form method="post" class="event-form"><?=camposCsrf()?><input type="hidden" name="action" value="create_event"><div class="event-form-grid"><label><span>Nome do evento</span><input name="name" required maxlength="180"></label><label><span>Local</span><input name="venue_name" required maxlength="180"></label><label class="full"><span>Endereço privado do local</span><input name="venue_address_private" maxlength="500"></label><label><span>Início</span><input type="datetime-local" name="starts_at" required></label><label><span>Término</span><input type="datetime-local" name="ends_at" required></label><label><span>Idade mínima</span><input type="number" name="min_age" min="0" max="15" value="0"></label><label><span>Idade máxima</span><input type="number" name="max_age" min="0" max="15" value="15"></label><label><span>Capacidade</span><input type="number" name="capacity" min="1" max="500" value="50"></label><label><span>Retenção após o término (dias)</span><input type="number" name="retention_days" min="1" max="90" value="30"></label><label><span>Contato de emergência</span><input name="emergency_contact_name" required maxlength="180"></label><label><span>Telefone de emergência</span><input name="emergency_contact_phone" required maxlength="30"></label><label class="full"><span>Descrição</span><textarea name="description" rows="3"></textarea></label><label class="full"><span>Instruções da área delimitada de câmera</span><textarea name="camera_area_instructions" rows="4" required placeholder="Descreva marcação do piso, distância, iluminação, fundo e presença do supervisor."></textarea></label><label class="full"><span>Plano de segurança e supervisão</span><textarea name="safety_plan" rows="5" required placeholder="Descreva responsáveis presentes, controle de entrada, emergência e interrupção imediata."></textarea></label></div><button class="btn btn-primary" type="submit">CRIAR RASCUNHO</button></form></section>
<section class="event-card" style="margin-top:18px"><h2>Meus eventos</h2><div class="event-list"><?php foreach($events as $e):?><article class="event-card"><div style="display:flex;justify-content:space-between;gap:10px"><div><small><?=esc($e['public_code'])?></small><h3><?=esc($e['name'])?></h3></div><span class="event-status event-status--<?=esc($e['status'])?>"><?=esc(strtoupper($e['status']))?></span></div><div class="event-meta"><span><?=date('d/m/Y H:i',strtotime($e['starts_at']))?></span><span><?=(int)$e['participant_count']?> participantes</span></div><a class="btn btn-secondary" href="<?=SITE_URL?>/pages/organizador-eventos.php?event=<?=(int)$e['id']?>">GERENCIAR</a></article><?php endforeach?></div></section>
<?php endif?>
<?php endif?>
</main><?php require __DIR__.'/../includes/footer.php';?>
