<?php
require_once __DIR__.'/../../_bootstrap.php';
require_once ROOT_PATH.'/includes/admin_functions.php';

function afAdminApiUser(PDO $pdo, array $roles = []): array
{
    $raw = bearerToken();
    if ($raw === '') jsonResponse(['ok'=>false,'erro'=>'Token administrativo ausente.'],401);
    $st = $pdo->prepare("SELECT s.id sessao_id,a.id,a.nome,a.email,a.papel,a.status,a.force_password_change
                         FROM af_admin_sessions s JOIN af_admin_users a ON a.id=s.admin_user_id
                         WHERE s.token_hash=? AND s.revogada_em IS NULL AND s.expira_em>NOW() AND a.status='ativo' LIMIT 1");
    $st->execute([hash('sha256',$raw)]);$admin=$st->fetch();
    if(!$admin)jsonResponse(['ok'=>false,'erro'=>'Sessão administrativa inválida ou expirada.'],401);
    if($roles&&!in_array((string)$admin['papel'],$roles,true))jsonResponse(['ok'=>false,'erro'=>'Nível administrativo insuficiente.'],403);
    $pdo->prepare('UPDATE af_admin_sessions SET ultima_atividade=NOW(),ip_hash=? WHERE id=?')->execute([afAdminIpHash(),(int)$admin['sessao_id']]);
    if(function_exists('afStage24RegisterApiContext')){
        $GLOBALS['af_stage24_api_context']['admin_user_id']=(int)$admin['id'];
        afStage24RegisterApiContext(null,'admin_api',true,null,['auth'=>'admin','role'=>$admin['papel']??'']);
    }
    return $admin;
}
