<?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";
    $params['busca'] = "%{$busca}%";
}

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

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

<div class="page-header">
    <div>
        <h2>Gestao de Categorias</h2>
        <div class="subtitle"><?= $total ?> categoria(s) cadastrada(s)</div>
    </div>
    <div class="d-flex gap-10">
        <a href="categoria_form.php" class="btn btn-novo">+ Nova Categoria</a>
    </div>
</div>

<form method="GET" class="filtros-bar">
    <div class="form-group">
        <label>Buscar</label>
        <input name="busca" placeholder="Nome da categoria" 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>Status</th>
    <th class="text-end">Acoes</th>
</tr>
</thead>
<tbody>
<?php if (empty($categorias)): ?>
<tr><td colspan="3" class="text-center text-muted" style="padding:30px;">Nenhuma categoria encontrada</td></tr>
<?php else: ?>
<?php foreach ($categorias as $c): ?>
<tr>
    <td><strong><?= sanitize($c['nome']) ?></strong></td>
    <td>
        <span class="badge <?= ($c['status'] ?? 'ativo') === 'ativo' ? 'badge-ativo' : 'badge-inativo' ?>">
            <?= ucfirst(sanitize($c['status'] ?? 'ativo')) ?>
        </span>
    </td>
    <td class="text-end">
        <a href="categoria_form.php?id=<?= intval($c['id']) ?>" class="btn btn-sm btn-info" title="Editar">&#9998;</a>
        <a href="categoria_status.php?id=<?= intval($c['id']) ?>" class="btn btn-sm btn-warning" title="Ativar/Inativar">&#9899;</a>
        <a href="categoria_excluir.php?id=<?= intval($c['id']) ?>" class="btn btn-sm btn-danger" title="Excluir" onclick="return confirm('Deseja excluir esta categoria?')">&#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'; ?>
