<?php
require_roles('super_admin');
$admins=db()->query("SELECT id,name,email,public_id,status FROM users WHERE role='sub_admin' ORDER BY name")->fetchAll();
$range=max(7,min(90,(int)request('days',30)));$from=date('Y-m-d',strtotime('-'.($range-1).' days'));
$presence=db()->prepare("SELECT p.*,u.name FROM admin_daily_presence p JOIN users u ON u.id=p.user_id WHERE u.role='sub_admin' AND p.work_date>=? ORDER BY p.work_date DESC,u.name");$presence->execute([$from]);$presenceRows=$presence->fetchAll();
$summary=[];foreach($admins as $a){$id=(int)$a['id'];$summary[$id]=['admin'=>$a,'today_create'=>0,'week_create'=>0,'month_create'=>0,'today_renew'=>0,'week_renew'=>0,'month_renew'=>0,'today_seconds'=>0,'week_seconds'=>0,'month_seconds'=>0,'linked_users'=>0,'linked_companies'=>0];}
foreach($summary as $id=>&$x){foreach(['today'=>today(),'week'=>date('Y-m-d',strtotime('-6 days')),'month'=>date('Y-m-d',strtotime('-29 days'))] as $key=>$dateFrom){$q=db()->prepare("SELECT SUM(CASE WHEN action='create_user' THEN 1 ELSE 0 END) c,SUM(CASE WHEN action='renew_user' THEN 1 ELSE 0 END) r FROM activity_logs WHERE user_id=? AND date(created_at)>=?");$q->execute([$id,$dateFrom]);$row=$q->fetch();$x[$key.'_create']=(int)($row['c']??0);$x[$key.'_renew']=(int)($row['r']??0);$pq=db()->prepare('SELECT COALESCE(SUM(active_seconds),0) FROM admin_daily_presence WHERE user_id=? AND work_date>=?');$pq->execute([$id,$dateFrom]);$x[$key.'_seconds']=(int)$pq->fetchColumn();}$lq=db()->prepare('SELECT COUNT(*) FROM users WHERE created_by_admin_id=? OR activated_by_admin_id=?');$lq->execute([$id,$id]);$x['linked_users']=(int)$lq->fetchColumn();$cq=db()->prepare('SELECT COUNT(*) FROM companies WHERE created_by_admin_id=? OR activated_by_admin_id=?');$cq->execute([$id,$id]);$x['linked_companies']=(int)$cq->fetchColumn();}unset($x);
$logs=db()->prepare("SELECT l.*,u.name FROM activity_logs l JOIN users u ON u.id=l.user_id WHERE u.role='sub_admin' AND date(l.created_at)>=? AND l.action<>'login' ORDER BY l.id DESC LIMIT 500");$logs->execute([$from]);$logs=$logs->fetchAll();
function fmt_admin_time($seconds){$seconds=max(0,(int)$seconds);$h=floor($seconds/3600);$m=floor(($seconds%3600)/60);return $h.'h '.str_pad((string)$m,2,'0',STR_PAD_LEFT).'min';}
?>
<section class="page-intro"><div><span class="mini-label">AUDITORIA</span><h2>Relatório dos Administradores</h2><p>Acompanhe o que cada administrador fez e o tempo ativo estimado no painel.</p></div><form method="get"><input type="hidden" name="page" value="admin_activity"><select name="days" data-auto-submit><option value="7"<?= selected($range,7) ?>>7 dias</option><option value="30"<?= selected($range,30) ?>>30 dias</option><option value="90"<?= selected($range,90) ?>>90 dias</option></select></form></section>
<section class="panel"><div class="table-wrap"><table><thead><tr><th>Administrador</th><th>Vinculados</th><th>Usuários cadastrados</th><th>Renovações</th><th>Tempo ativo</th></tr></thead><tbody><?php if(!$summary):?><tr><td colspan="5"><div class="empty-state"><strong>Nenhum Administrador</strong></div></td></tr><?php endif;?><?php foreach($summary as $x):?><tr><td><strong><?= e($x['admin']['name']) ?></strong><small style="display:block"><?= e($x['admin']['email']) ?></small></td><td><strong><?= $x['linked_users'] ?></strong> usuário(s)<br><small><?= $x['linked_companies'] ?> empresa(s)</small></td><td>Hoje: <b><?= $x['today_create'] ?></b><br>7 dias: <b><?= $x['week_create'] ?></b><br>30 dias: <b><?= $x['month_create'] ?></b></td><td>Hoje: <b><?= $x['today_renew'] ?></b><br>7 dias: <b><?= $x['week_renew'] ?></b><br>30 dias: <b><?= $x['month_renew'] ?></b></td><td>Hoje: <b><?= e(fmt_admin_time($x['today_seconds'])) ?></b><br>7 dias: <b><?= e(fmt_admin_time($x['week_seconds'])) ?></b><br>30 dias: <b><?= e(fmt_admin_time($x['month_seconds'])) ?></b></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel"><div class="panel-header"><div><h3>Tempo por dia</h3><p>Somamos intervalos de atividade de até 15 minutos entre uma ação/página e outra.</p></div></div><div class="table-wrap"><table><thead><tr><th>Data</th><th>Administrador</th><th>Primeira atividade</th><th>Última atividade</th><th>Tempo ativo</th></tr></thead><tbody><?php foreach($presenceRows as $p):?><tr><td><?= e(date('d/m/Y',strtotime($p['work_date']))) ?></td><td><?= e($p['name']) ?></td><td><?= e(date('H:i',strtotime($p['first_seen']))) ?></td><td><?= e(date('H:i',strtotime($p['last_seen']))) ?></td><td><strong><?= e(fmt_admin_time($p['active_seconds'])) ?></strong></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel"><div class="panel-header"><div><h3>Ações executadas</h3><p>Últimas ações administrativas dentro do período selecionado.</p></div></div><div class="activity-list"><?php if(!$logs):?><div class="empty-state"><strong>Nenhuma ação registrada</strong></div><?php endif;?><?php foreach($logs as $l):?><div class="activity"><span class="activity-dot"></span><div><p><strong><?= e($l['name']) ?></strong> — <?= e(activity_action_label($l['action'])) ?></p><small><?= e($l['details']?:($l['entity'].' #'.$l['entity_id'])) ?></small><small><?= e(date('d/m/Y H:i',strtotime($l['created_at']))) ?></small></div></div><?php endforeach;?></div></section>
