<?php
$u=current_user();
$isAdmin=is_admin();
$qText=trim((string)request('q',''));
$params=[];
$where="l.action='login'";
if(!$isAdmin){
    $where.=' AND l.user_id=?';
    $params[]=(int)$u['id'];
}else{
    if(is_role('sub_admin'))$where.=" AND (u.role IS NULL OR u.role NOT IN ('super_admin','sub_admin'))";
    if($qText!==''){
    $where.=' AND (u.name LIKE ? OR u.email LIKE ? OR u.public_id LIKE ? OR l.ip LIKE ?)';
    $like='%'.$qText.'%';
    array_push($params,$like,$like,$like,$like);
    }
}
$stmt=db()->prepare("SELECT l.*,u.name,u.email,u.public_id,u.avatar FROM activity_logs l LEFT JOIN users u ON u.id=l.user_id WHERE $where ORDER BY l.id DESC LIMIT 250");
$stmt->execute($params);
$logs=$stmt->fetchAll();
?>
<section class="page-intro"><div><span class="mini-label">SEGURANÇA</span><h2>Histórico de logins</h2><p><?= is_role('super_admin')?'Acompanhe os acessos registrados de todos os usuários.':(is_role('sub_admin')?'Acompanhe os acessos dos usuários não administrativos.':'Consulte os acessos registrados na sua conta.') ?></p></div></section>
<?php if($isAdmin):?>
<section class="panel login-history-tools">
  <form method="get" action="dashboard.php" class="filter-bar"><input type="hidden" name="page" value="login_history"><div class="form-group"><label>Pesquisar usuário / ID / IP</label><input class="input" name="q" value="<?= e($qText) ?>" placeholder="Nome, e-mail, LXU-... ou IP"></div><button class="btn btn-secondary">Pesquisar</button><?php if($qText!==''):?><a class="btn btn-secondary" href="dashboard.php?page=login_history">Limpar busca</a><?php endif;?></form>
  <form method="post" action="actions.php" style="margin-top:12px"><?= csrf_field() ?><input type="hidden" name="action" value="clear_login_history"><input type="hidden" name="return_page" value="login_history"><button class="btn btn-danger" data-confirm="Apagar TODO o histórico de logins da plataforma? Esta ação não pode ser desfeita.">Zerar histórico de logins</button></form>
</section>
<?php endif;?>
<section class="panel">
  <div class="panel-header"><div><h3><?= $isAdmin?'Acessos da plataforma':'Meus acessos' ?></h3><p><?= count($logs) ?> registro(s) exibido(s).</p></div></div>
  <div class="login-history-list">
    <?php if(!$logs):?><div class="empty-state"><strong>Nenhum login registrado</strong>Os próximos acessos aparecerão aqui.</div><?php else:foreach($logs as $log):?>
      <article class="login-history-row">
        <div class="login-history-avatar"><?= avatar_html(['name'=>$log['name']?:'Sistema','avatar'=>$log['avatar']??'']) ?></div>
        <div class="login-history-main"><strong><?= e($log['name']?:'Sistema') ?></strong><?php if($isAdmin):?><small><?= e($log['public_id']?:'Sem ID público') ?><?= !empty($log['email'])?' • '.e($log['email']):'' ?></small><?php endif;?><small><?= e(date('d/m/Y H:i:s',strtotime($log['created_at']))) ?></small></div>
        <div class="login-history-ip"><small>IP</small><strong><?= e($log['ip']?:'Não informado') ?></strong></div>
      </article>
    <?php endforeach;endif;?>
  </div>
</section>
