<?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();
$admin=afAdminAtual();
if($_SERVER['REQUEST_METHOD']==='POST'){
 try{
  if(!validarCsrfToken($_POST[CSRF_TOKEN_NAME]??''))throw new RuntimeException('Sessão expirada.');$acao=(string)($_POST['acao']??'');
  if($acao==='perfil'){$nome=trim(strip_tags((string)($_POST['nome']??'')));if(mb_strlen($nome)<3)throw new RuntimeException('Informe seu nome.');$pdo->prepare('UPDATE af_admin_users SET nome=?,atualizado_em=NOW() WHERE id=?')->execute([$nome,afAdminId()]);afAdminLog($pdo,'admin_perfil_atualizado','admin_user',afAdminId());}
  elseif($acao==='senha'){$st=$pdo->prepare('SELECT senha_hash FROM af_admin_users WHERE id=?');$st->execute([afAdminId()]);$hash=(string)$st->fetchColumn();if(!password_verify((string)($_POST['senha_atual']??''),$hash))throw new RuntimeException('A senha atual está incorreta.');$pass=(string)($_POST['nova_senha']??'');if(!hash_equals($pass,(string)($_POST['confirmar_senha']??'')))throw new RuntimeException('As novas senhas não coincidem.');if($e=afAdminPasswordError($pass))throw new RuntimeException($e);$pdo->prepare('UPDATE af_admin_users SET senha_hash=?,force_password_change=0,senha_alterada_em=NOW(),atualizado_em=NOW() WHERE id=?')->execute([password_hash($pass,PASSWORD_DEFAULT),afAdminId()]);$pdo->prepare('UPDATE af_admin_sessions SET revogada_em=NOW() WHERE admin_user_id=? AND id<>? AND revogada_em IS NULL')->execute([afAdminId(),(int)$_SESSION['admin_sessao_id']]);afAdminLog($pdo,'admin_senha_alterada','admin_user',afAdminId());}
  elseif($acao==='revogar'){$pdo->prepare('UPDATE af_admin_sessions SET revogada_em=NOW() WHERE admin_user_id=? AND id<>? AND revogada_em IS NULL')->execute([afAdminId(),(int)$_SESSION['admin_sessao_id']]);afAdminLog($pdo,'admin_sessoes_revogadas','admin_user',afAdminId());}
  else throw new RuntimeException('Ação inválida.');
  $st=$pdo->prepare('SELECT id,nome,email,papel,status,force_password_change,ultimo_login,criado_em FROM af_admin_users WHERE id=?');$st->execute([afAdminId()]);$admin=$st->fetch();$_SESSION['admin_usuario']=$admin;setFlash('success','Dados administrativos atualizados.');
 }catch(Throwable $e){setFlash('error',$e->getMessage());}
 header('Location: '.SITE_URL.'/admin/conta.php');exit;
}
$st=$pdo->prepare('SELECT id,ip_hash,ultima_atividade,criado_em,expira_em,revogada_em FROM af_admin_sessions WHERE admin_user_id=? ORDER BY id DESC LIMIT 20');$st->execute([afAdminId()]);$sessions=$st->fetchAll()?:[];
$pageTitle='Admin • Minha conta';$showNav=false;$bodyClass='admin-body';$adminPage='conta';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>SEGURANÇA DA CONTA</small><h1>Minha conta administrativa</h1></div></header><?=renderFlash()?>
<div class="admin-grid-2"><section class="admin-panel"><header><div><small>PERFIL</small><h2>Dados do administrador</h2></div></header><form method="post" class="admin-form"><?=camposCsrf()?><input type="hidden" name="acao" value="perfil"><label>Nome<input name="nome" required maxlength="120" value="<?=esc($admin['nome'])?>"></label><label>E-mail<input value="<?=esc($admin['email'])?>" disabled></label><label>Nível<input value="<?=esc($admin['papel'])?>" disabled></label><button class="admin-primary">Salvar perfil</button></form></section>
<section class="admin-panel"><header><div><small>SENHA</small><h2>Alterar senha</h2></div></header><form method="post" class="admin-form"><?=camposCsrf()?><input type="hidden" name="acao" value="senha"><label>Senha atual<input type="password" name="senha_atual" required></label><label>Nova senha<input type="password" name="nova_senha" required></label><label>Confirmar nova senha<input type="password" name="confirmar_senha" required></label><button class="admin-primary">Alterar senha</button></form></section></div>
<section class="admin-panel"><header><div><small>DISPOSITIVOS</small><h2>Sessões administrativas</h2></div><form method="post" onsubmit="return confirm('Encerrar todas as outras sessões?')"><?=camposCsrf()?><button class="admin-danger" name="acao" value="revogar">Encerrar outras sessões</button></form></header><div class="admin-table-wrap"><table class="admin-table"><thead><tr><th>Sessão</th><th>Criada</th><th>Última atividade</th><th>Expira</th><th>Status</th></tr></thead><tbody><?php foreach($sessions as $s):?><tr><td>#<?=(int)$s['id']?> <?=$s['id']==($_SESSION['admin_sessao_id']??0)?'<b>• atual</b>':''?></td><td><?=date('d/m/Y H:i',strtotime($s['criado_em']))?></td><td><?=date('d/m/Y H:i',strtotime($s['ultima_atividade']))?></td><td><?=date('d/m/Y',strtotime($s['expira_em']))?></td><td><span class="admin-pill"><?=empty($s['revogada_em'])?'ativa':'encerrada'?></span></td></tr><?php endforeach;?></tbody></table></div></section>
</main></div><script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script><?php require __DIR__.'/../includes/footer.php';
