<?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.');afAdminUserAction($pdo,(int)($_POST['usuario_id']??0),(string)($_POST['acao']??''),$_POST);setFlash('success','Usuário atualizado.');}
 catch(Throwable $e){setFlash('error',$e->getMessage());}
 header('Location: '.SITE_URL.'/pages/admin-usuarios.php?'.http_build_query(array_filter(['q'=>$_GET['q']??'','status'=>$_GET['status']??''])));exit;
}
$q=sanitize($_GET['q']??'');$status=(string)($_GET['status']??'todos');$where=['1=1'];$params=[];
if($q!==''){$where[]='(u.nome LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR u.aura_id LIKE ?)';$like='%'.$q.'%';array_push($params,$like,$like,$like,$like);}
if($status==='ativos')$where[]='u.status=1';elseif($status==='bloqueados')$where[]='(u.status=2 OR u.seguranca_status<>\'normal\')';elseif($status==='inativos')$where[]='u.status=0';
$sqlWhere=implode(' AND ',$where);$st=$pdo->prepare("SELECT COUNT(*) FROM af_usuarios u WHERE {$sqlWhere}");$st->execute($params);$pg=afAdminPagination((int)$st->fetchColumn(),25);
$st=$pdo->prepare("SELECT u.*,p.cidade,p.estado,p.pais,(SELECT COUNT(*) FROM af_dispositivos d WHERE d.usuario_id=u.id AND d.ativo=1) dispositivos_ativos FROM af_usuarios u LEFT JOIN af_perfis p ON p.usuario_id=u.id WHERE {$sqlWhere} ORDER BY u.id DESC LIMIT {$pg['per_page']} OFFSET {$pg['offset']}");$st->execute($params);$items=$st->fetchAll()?:[];
$pageTitle='Admin • Usuários';$showNav=false;$bodyClass='admin-body';$adminPage='usuarios';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>GESTÃO DE CONTAS</small><h1>Usuários</h1></div><span class="admin-count"><?=$pg['total']?> registros</span></header><?=renderFlash()?>
<form class="admin-filters" method="get"><input name="q" value="<?=esc($q)?>" placeholder="Nome, usuário, e-mail ou AURA-ID"><select name="status"><option value="todos">Todos</option><?php foreach(['ativos'=>'Ativos','inativos'=>'Inativos','bloqueados'=>'Bloqueados'] as $k=>$v):?><option value="<?=$k?>" <?=$status===$k?'selected':''?>><?=$v?></option><?php endforeach;?></select><button>Filtrar</button></form>
<section class="admin-panel"><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Jogador</th><th>Progresso</th><th>Segurança</th><th>Dispositivos</th><th>Ações</th></tr></thead><tbody><?php if(!$items):?><tr><td colspan="5" class="admin-empty">Nenhum usuário encontrado.</td></tr><?php endif;foreach($items as $u):?><tr><td><b><?=esc($u['nome'])?></b><small>@<?=esc($u['username'])?> • <?=esc($u['email'])?><br><?=esc($u['aura_id'])?> • <?=esc(trim(($u['cidade']??'').' '.($u['estado']??'')))?></small></td><td><b>Nv. <?=(int)$u['nivel']?></b><small><?=number_format((float)$u['melhor_pontuacao'],2,',','.')?> pontos • <?=(int)$u['total_partidas']?> partidas</small></td><td><span class="admin-pill status-<?=esc($u['seguranca_status'])?>"><?=esc($u['seguranca_status'])?></span><small>Risco <?=(int)$u['risco_conta']?> • <?=esc($u['papel'])?></small></td><td><?=(int)$u['dispositivos_ativos']?></td><td><form method="post" class="admin-inline-actions"><?=camposCsrf()?><input type="hidden" name="usuario_id" value="<?=(int)$u['id']?>"><select name="acao"><option value="ativar">Ativar</option><option value="inativar">Inativar</option><option value="bloquear">Bloquear 7 dias</option><?php if(afAdminIsSuper()):?><option value="banir">Banir</option><?php endif;?></select><button>Aplicar</button></form></td></tr><?php endforeach;?></tbody></table></div></section>
<?php include __DIR__.'/../includes/admin_pagination.php';?></main></div><script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script><?php require __DIR__.'/../includes/footer.php';?>
