<?php require_roles('super_admin');$adminFilter=is_role('sub_admin')?" WHERE u.role NOT IN ('super_admin','sub_admin')":'';$users=db()->query('SELECT u.*,c.name company_name FROM users u LEFT JOIN companies c ON c.id=u.company_id'.$adminFilter.' ORDER BY u.last_seen DESC')->fetchAll();$online=0;$offline=0;$busy=0;foreach($users as $x){$isOnline=$x['last_seen']&&strtotime($x['last_seen'])>=time()-300;if($isOnline)$online++;else$offline++;if($x['work_status']==='busy'||$x['work_status']==='on_route')$busy++;}?>
<div class="stats-grid"><article class="stat-card"><div class="stat-top"><span>Online agora</span><span class="stat-icon">🟢</span></div><strong><?= $online ?></strong><small>Ativos nos últimos 5 minutos</small></article><article class="stat-card"><div class="stat-top"><span>Offline</span><span class="stat-icon">🔴</span></div><strong><?= $offline ?></strong><small>Sem atividade recente</small></article><article class="stat-card"><div class="stat-top"><span>Em atendimento</span><span class="stat-icon">🟡</span></div><strong><?= $busy ?></strong><small>Ocupados ou em rota</small></article><article class="stat-card"><div class="stat-top"><span>Total monitorado</span><span class="stat-icon">📡</span></div><strong><?= count($users) ?></strong><small><?= is_role('sub_admin')?'Perfis não administrativos':'Todos os perfis' ?></small></article></div>
<section class="panel"><div class="panel-header"><div><h2>Monitoramento em tempo real</h2><p>Último acesso, IP administrativo, perfil e situação operacional.</p></div></div><div class="table-wrap"><table><thead><tr><th>Usuário</th><th>Perfil</th><th>Empresa</th><th>Conexão</th><th>Trabalho</th><th>Último acesso</th><th>IP</th></tr></thead><tbody><?php foreach($users as $x):$isOnline=$x['last_seen']&&strtotime($x['last_seen'])>=time()-300;?><tr><td><div class="table-title"><span class="table-thumb"><?= role_icon($x['role']) ?></span><div><strong><?= e($x['name']) ?></strong><small style="display:block"><?= e($x['email']) ?></small></div></div></td><td><?= e(role_label($x['role'])) ?></td><td><?= e($x['company_name']?:'—') ?></td><td><?= status_badge($isOnline?'active':'offline') ?></td><td><?= status_badge($x['work_status']) ?></td><td><?= $x['last_seen']?e(date('d/m/Y H:i:s',strtotime($x['last_seen']))):'Nunca' ?></td><td><?= e($x['last_ip']?:'—') ?></td></tr><?php endforeach;?></tbody></table></div></section>
