<?php
require_once __DIR__ . '/../includes/header.php';

$busca = sanitize($_GET['busca'] ?? '');
$pagina = max(1, intval($_GET['pg'] ?? 1));
$por_pagina = 20;
$offset = ($pagina - 1) * $por_pagina;

$where = "1=1";
$params = [];

if ($busca !== '') {
    $where .= " AND (nome LIKE :busca OR email LIKE :busca)";
    $params['busca'] = "%{$busca}%";
}

$stmt_total = $pdo->prepare("SELECT COUNT(*) FROM usuarios WHERE {$where}");
$stmt_total->execute($params);
$total = $stmt_total->fetchColumn();
$total_paginas = ceil($total / $por_pagina);

$sql = "SELECT * FROM usuarios WHERE {$where} ORDER BY nome ASC LIMIT {$por_pagina} OFFSET {$offset}";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$usuarios = $stmt->fetchAll();
?>

<div class="page-header">
    <div>
        <h2>Gestao de Usuarios</h2>
        <div class="subtitle"><?= $total ?> usuario(s) cadastrado(s)</div>
    </div>
    <div class="d-flex gap-10">
        <a href="usuario_form.php" class="btn btn-novo">+ Novo Usuario</a>
    </div>
</div>

<form method="GET" class="filtros-bar">
    <div class="form-group">
        <label>Buscar</label>
        <input name="busca" placeholder="Nome ou email" value="<?= $busca ?>">
    </div>
    <div class="form-group" style="max-width:100px;">
        <label>&nbsp;</label>
        <button class="btn btn-primary w-100">Filtrar</button>
    </div>
</form>

<div class="card-premium">
<div class="table-responsive">
<table class="table-premium">
<thead>
<tr>
    <th>Nome</th>
    <th>Email</th>
    <th>Status</th>
    <th class="text-end">Acoes</th>
</tr>
</thead>
<tbody>
<?php if (empty($usuarios)): ?>
<tr><td colspan="4" class="text-center text-muted" style="padding:30px;">Nenhum usuario encontrado</td></tr>
<?php else: ?>
<?php foreach ($usuarios as $u): ?>
<tr>
    <td><strong><?= sanitize($u['nome']) ?></strong></td>
    <td><?= sanitize($u['email']) ?></td>
    <td>
        <span class="badge <?= ($u['status'] ?? 'ativo') === 'ativo' ? 'badge-ativo' : 'badge-inativo' ?>">
            <?= ucfirst(sanitize($u['status'] ?? 'ativo')) ?>
        </span>
    </td>
    <td class="text-end">
        <a href="usuario_form.php?id=<?= intval($u['id']) ?>" class="btn btn-sm btn-info" title="Editar">&#9998;</a>
        <a href="usuario_status.php?id=<?= intval($u['id']) ?>" class="btn btn-sm btn-warning" title="Ativar/Inativar">&#9899;</a>
        <a href="usuario_excluir.php?id=<?= intval($u['id']) ?>" class="btn btn-sm btn-danger" title="Excluir" onclick="return confirm('Deseja excluir este usuario?')">&#10005;</a>
    </td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>

<?php if ($total_paginas > 1): ?>
<div class="paginacao">
    <?php for ($i = 1; $i <= $total_paginas; $i++): ?>
        <a href="?pg=<?= $i ?>&busca=<?= urlencode($busca) ?>"
           class="<?= $i === $pagina ? 'ativo' : '' ?>"><?= $i ?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
