<?php
/** AURA FARMING — Etapa 22: central administrativa de moderação */
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();
if($_SERVER['REQUEST_METHOD']==='POST'){
 try{
  if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??''))throw new RuntimeException('Sessão expirada.');
  $form=(string)($_POST['form']??'report');
  if($form==='report'){
   $reportId=(int)($_POST['report_id']??0);$action=(string)($_POST['action']??'take_review');$reason=sanitize($_POST['reason']??'');$hours=(int)($_POST['duration_hours']??24);
   afModerationAdminApplyAction($pdo,$adminId,$reportId,$action,$reason,$hours);afAdminLog($pdo,'moderation_'.$action,'safety_report',$reportId,['reason'=>$reason,'duration_hours'=>$hours]);setFlash('success','Ação de moderação registrada.');
  }elseif($form==='filter_add'){
   $scope=(string)($_POST['scope']??'global');$type=(string)($_POST['pattern_type']??'word');$value=trim((string)($_POST['pattern_value']??''));$severity=(string)($_POST['severity']??'medium');$action=(string)($_POST['filter_action']??'mask');$minor=!empty($_POST['minor_only']);
   if(mb_strlen($value)<2)throw new RuntimeException('Informe uma palavra ou expressão válida.');
   if(!in_array($scope,['global','comments','messages','live','minor'],true))$scope='global';if(!in_array($type,['word','phrase','regex'],true))$type='word';if(!in_array($severity,['low','medium','high','critical'],true))$severity='medium';if(!in_array($action,['mask','review','block','suspend'],true))$action='mask';
   if($type==='regex'&&@preg_match('~'.$value.'~u','')===false)throw new RuntimeException('A expressão regular informada é inválida.');
   $pdo->prepare("INSERT INTO af_content_filters(scope,pattern_type,pattern_value,normalized_value,replacement,severity,action,minor_only,active,created_by_admin_id,created_at,updated_at) VALUES (?,?,?,?, '•••',?,?,?,1,?,NOW(),NOW())")
       ->execute([$scope,$type,$value,afModerationNormalize($value),$severity,$action,$minor?1:0,$adminId]);afAdminLog($pdo,'content_filter_added','content_filter',(int)$pdo->lastInsertId(),['pattern'=>$value]);setFlash('success','Filtro adicionado.');
  }elseif($form==='filter_toggle'){
   $id=(int)($_POST['filter_id']??0);$pdo->prepare('UPDATE af_content_filters SET active=IF(active=1,0,1),updated_at=NOW() WHERE id=?')->execute([$id]);afAdminLog($pdo,'content_filter_toggled','content_filter',$id);setFlash('success','Filtro atualizado.');
  }elseif($form==='incident'){
   $id=(int)($_POST['incident_id']??0);$status=(string)($_POST['incident_status']??'reviewing');if(!in_array($status,['open','reviewing','resolved','archived'],true))$status='reviewing';$pdo->prepare("UPDATE af_minor_safety_incidents SET status=?,resolved_at=IF(?='resolved',NOW(),resolved_at),updated_at=NOW() WHERE id=?")->execute([$status,$status,$id]);afAdminLog($pdo,'minor_incident_'.$status,'minor_safety_incident',$id);setFlash('success','Incidente atualizado.');
  }
 }catch(Throwable $e){setFlash('error',$e->getMessage());}
 header('Location: '.SITE_URL.'/pages/admin-denuncias.php?tab='.urlencode((string)($_POST['return_tab']??'queue')));exit;
}
$tab=(string)($_GET['tab']??'queue');if(!in_array($tab,['queue','incidents','filters','history'],true))$tab='queue';
$status=(string)($_GET['status']??'pending');$where=match($status){'resolved'=>"r.status='resolved'",'archived'=>"r.status='archived'",'acted'=>"r.status='acted'",'all'=>'1=1',default=>"r.status IN ('open','triage','in_review')"};
$reports=[];$incidents=[];$filters=[];$actions=[];
if($tab==='queue'){$reports=$pdo->query("SELECT r.*,rep.nome reporter_name,rep.aura_id reporter_aura,t.nome target_name,t.aura_id target_aura,a.nome admin_name,
 (SELECT COUNT(*) FROM af_safety_reports x WHERE x.reported_user_id=r.reported_user_id AND x.created_at>=DATE_SUB(NOW(),INTERVAL 30 DAY)) recurrence_30
 FROM af_safety_reports r LEFT JOIN af_usuarios rep ON rep.id=r.reporter_user_id LEFT JOIN af_usuarios t ON t.id=r.reported_user_id LEFT JOIN af_admin_users a ON a.id=r.assigned_admin_id
 WHERE {$where} ORDER BY FIELD(r.priority,'critical','high','medium','low'),r.id DESC LIMIT 150")->fetchAll()?:[];}
elseif($tab==='incidents'){$incidents=$pdo->query("SELECT i.*,m.nome minor_name,m.aura_id minor_aura,u.nome related_name,u.aura_id related_aura,r.protocol FROM af_minor_safety_incidents i JOIN af_usuarios m ON m.id=i.minor_user_id LEFT JOIN af_usuarios u ON u.id=i.related_user_id LEFT JOIN af_safety_reports r ON r.id=i.report_id ORDER BY FIELD(i.severity,'critical','high','warning','info'),i.id DESC LIMIT 180")->fetchAll()?:[];}
elseif($tab==='filters'){$filters=$pdo->query("SELECT f.*,a.nome admin_name FROM af_content_filters f LEFT JOIN af_admin_users a ON a.id=f.created_by_admin_id ORDER BY f.active DESC,FIELD(f.severity,'critical','high','medium','low'),f.id DESC LIMIT 300")->fetchAll()?:[];}
else{$actions=$pdo->query("SELECT ma.*,u.nome target_name,u.aura_id target_aura,a.nome admin_name,r.protocol FROM af_moderation_actions ma LEFT JOIN af_usuarios u ON u.id=ma.target_user_id LEFT JOIN af_admin_users a ON a.id=ma.admin_user_id LEFT JOIN af_safety_reports r ON r.id=ma.report_id ORDER BY ma.id DESC LIMIT 250")->fetchAll()?:[];}
$stats=$pdo->query("SELECT SUM(status IN ('open','triage','in_review')) pending,SUM(priority='critical' AND status IN ('open','triage','in_review')) critical,SUM(involves_minor=1 AND status IN ('open','triage','in_review')) minors,SUM(status='resolved') resolved FROM af_safety_reports")->fetch()?:[];
$labels=afModerationReportLabels();$pageTitle='Admin • Moderação';$showNav=false;$bodyClass='admin-body';$adminPage='denuncias';require __DIR__.'/../includes/header.php';
?>
<div class="admin-shell"><?php require __DIR__.'/../includes/admin_nav.php';?><main class="admin-main moderation-admin"><header class="admin-topbar"><div><small>ETAPA 22 • SEGURANÇA DA COMUNIDADE</small><h1>Moderação e denúncias</h1></div><span class="admin-count"><?=(int)($stats['pending']??0)?> pendentes</span></header><?=renderFlash()?>
<section class="moderation-stat-grid"><article><b><?=(int)($stats['pending']??0)?></b><span>NA FILA</span></article><article class="is-critical"><b><?=(int)($stats['critical']??0)?></b><span>CRÍTICAS</span></article><article><b><?=(int)($stats['minors']??0)?></b><span>ENVOLVEM MENORES</span></article><article><b><?=(int)($stats['resolved']??0)?></b><span>RESOLVIDAS</span></article></section>
<nav class="admin-tabs moderation-tabs"><a class="<?=$tab==='queue'?'active':''?>" href="?tab=queue">Fila de análise</a><a class="<?=$tab==='incidents'?'active':''?>" href="?tab=incidents">Incidentes de menores</a><a class="<?=$tab==='filters'?'active':''?>" href="?tab=filters">Filtros de conteúdo</a><a class="<?=$tab==='history'?'active':''?>" href="?tab=history">Histórico de ações</a></nav>
<?php if($tab==='queue'):?>
<nav class="admin-tabs moderation-subtabs"><?php foreach(['pending'=>'Pendentes','acted'=>'Com ação','resolved'=>'Resolvidas','archived'=>'Arquivadas','all'=>'Todas'] as $k=>$v):?><a class="<?=$status===$k?'active':''?>" href="?tab=queue&status=<?=$k?>"><?=$v?></a><?php endforeach;?></nav>
<div class="admin-cards-list"><?php if(!$reports):?><div class="admin-empty">Nenhuma denúncia neste filtro.</div><?php endif;?><?php foreach($reports as $r):?><article class="admin-report-card moderation-report-card priority-<?=esc($r['priority'])?>"><header><div><span class="admin-pill priority-<?=esc($r['priority'])?>"><?=strtoupper(esc($r['priority']))?></span><b><?=esc($r['protocol'])?> • <?=esc($labels[$r['category']]??$r['category'])?></b><?php if($r['involves_minor']):?><span class="moderation-minor-pill">MENOR ENVOLVIDO</span><?php endif;?></div><time><?=date('d/m/Y H:i',strtotime($r['created_at']))?></time></header>
<div class="admin-report-grid"><p><small>DENUNCIANTE</small><b><?=esc($r['reporter_name']??'Não identificado')?></b><span><?=esc($r['reporter_aura']??'')?></span></p><p><small>ALVO</small><b><?=esc($r['target_name']??'Não informado')?></b><span><?=esc($r['target_aura']??'')?> • <?=(int)$r['recurrence_30']?> denúncia(s) em 30 dias</span></p><p><small>CONTEXTO</small><b><?=strtoupper(esc($r['report_type']))?></b><span>Partida <?=esc((string)($r['partida_id']??'-'))?> • risco <?=(int)$r['risk_score']?>/100</span></p></div>
<p class="admin-report-text"><?=nl2br(esc($r['description']))?></p>
<form method="post" class="admin-review-form moderation-action-form"><?=camposCsrf()?><input type="hidden" name="form" value="report"><input type="hidden" name="return_tab" value="queue"><input type="hidden" name="report_id" value="<?=(int)$r['id']?>"><input name="reason" value="<?=esc($r['resolution']??'')?>" placeholder="Motivo, conclusão ou providência tomada" required><label>Horas<input type="number" name="duration_hours" min="1" max="720" value="24"></label><select name="action"><option value="take_review">Assumir análise</option><option value="warning">Enviar advertência</option><option value="hide_content">Ocultar conteúdo</option><option value="preventive_suspend">Suspensão preventiva</option><option value="temporary_suspend">Suspensão temporária</option><option value="permanent_ban">Banimento permanente</option><option value="restore">Restaurar conta</option><option value="resolve">Resolver denúncia</option><option value="archive">Arquivar</option></select><button class="admin-primary">APLICAR AÇÃO</button></form></article><?php endforeach;?></div>
<?php elseif($tab==='incidents'):?>
<div class="admin-cards-list"><?php if(!$incidents):?><div class="admin-empty">Nenhum incidente registrado.</div><?php endif;?><?php foreach($incidents as $i):?><article class="admin-report-card moderation-incident-card priority-<?=esc($i['severity'])?>"><header><div><span class="admin-pill priority-<?=esc($i['severity'])?>"><?=strtoupper(esc($i['severity']))?></span><b>#<?=(int)$i['id']?> • <?=esc(str_replace('_',' ',$i['incident_type']))?></b></div><time><?=date('d/m/Y H:i',strtotime($i['created_at']))?></time></header><div class="admin-report-grid"><p><small>MENOR</small><b><?=esc($i['minor_name'])?></b><span><?=esc($i['minor_aura'])?></span></p><p><small>RELACIONADO</small><b><?=esc($i['related_name']??'Não identificado')?></b><span><?=esc($i['related_aura']??'')?></span></p><p><small>DENÚNCIA</small><b><?=esc($i['protocol']??'Sem protocolo')?></b><span>Responsável <?=empty($i['guardian_notified_at'])?'não notificado':'notificado'?></span></p></div><p class="admin-report-text"><?=esc($i['summary'])?></p><form method="post" class="admin-review-form"><?=camposCsrf()?><input type="hidden" name="form" value="incident"><input type="hidden" name="return_tab" value="incidents"><input type="hidden" name="incident_id" value="<?=(int)$i['id']?>"><select name="incident_status"><option value="reviewing">Em análise</option><option value="resolved">Resolvido</option><option value="archived">Arquivado</option><option value="open">Reabrir</option></select><button class="admin-primary">ATUALIZAR</button></form></article><?php endforeach;?></div>
<?php elseif($tab==='filters'):?>
<section class="admin-panel moderation-filter-create"><header><div><small>LISTA DE PALAVRAS E PADRÕES</small><h2>Novo filtro</h2></div></header><form method="post" class="admin-form moderation-filter-form"><?=camposCsrf()?><input type="hidden" name="form" value="filter_add"><input type="hidden" name="return_tab" value="filters"><label>Escopo<select name="scope"><option value="global">Global</option><option value="comments">Comentários</option><option value="messages">Mensagens</option><option value="live">Ao vivo</option><option value="minor">Proteção de menores</option></select></label><label>Tipo<select name="pattern_type"><option value="word">Palavra</option><option value="phrase">Expressão</option><option value="regex">Expressão regular</option></select></label><label>Palavra ou padrão<input name="pattern_value" maxlength="500" required></label><label>Severidade<select name="severity"><option value="low">Baixa</option><option value="medium">Média</option><option value="high">Alta</option><option value="critical">Crítica</option></select></label><label>Ação<select name="filter_action"><option value="mask">Mascarar</option><option value="review">Enviar para revisão</option><option value="block">Bloquear envio</option><option value="suspend">Bloquear e avaliar suspensão</option></select></label><label class="moderation-check"><input type="checkbox" name="minor_only" value="1"><span><b>Aplicar somente quando houver menor</b></span></label><button class="btn btn-primary">ADICIONAR FILTRO</button></form></section>
<div class="moderation-filter-table"><?php foreach($filters as $f):?><article class="admin-panel <?=$f['active']?'':'is-disabled'?>"><div><b><?=esc($f['pattern_value'])?></b><span><?=esc($f['scope'])?> • <?=esc($f['pattern_type'])?> • <?=esc($f['severity'])?> • ação <?=esc($f['action'])?><?=$f['minor_only']?' • somente menores':''?></span></div><form method="post"><?=camposCsrf()?><input type="hidden" name="form" value="filter_toggle"><input type="hidden" name="return_tab" value="filters"><input type="hidden" name="filter_id" value="<?=(int)$f['id']?>"><button class="<?=$f['active']?'admin-muted':'admin-primary'?>"><?=$f['active']?'DESATIVAR':'ATIVAR'?></button></form></article><?php endforeach;?></div>
<?php else:?>
<div class="moderation-history-table"><?php if(!$actions):?><div class="admin-empty">Nenhuma ação registrada.</div><?php endif;?><?php foreach($actions as $a):?><article class="admin-panel"><time><?=date('d/m/Y H:i',strtotime($a['created_at']))?></time><div><b><?=esc(str_replace('_',' ',strtoupper($a['action_type'])))?></b><span><?=esc($a['target_name']??'Sem usuário alvo')?> <?=esc($a['target_aura']??'')?> • <?=esc($a['protocol']??'ação direta')?></span><p><?=esc($a['reason'])?></p></div><small><?=esc($a['admin_name']??'Automático')?></small></article><?php endforeach;?></div>
<?php endif;?></main></div><script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script><?php require __DIR__.'/../includes/footer.php';?>
