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

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

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

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

if ($status_filtro !== '') {
    $where .= " AND a.status = ?";
    $params[] = $status_filtro;
}

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

// =========================
// LISTAGEM
// =========================
$sql = "
    SELECT a.*
    FROM alunos a
    WHERE {$where}
    ORDER BY a.nome ASC
    LIMIT {$por_pagina} OFFSET {$offset}
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$alunos = $stmt->fetchAll();
?>

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

<!-- FILTROS -->
<form method="GET" class="filtros-bar">
    <div class="form-group">
        <label>Buscar</label>
        <input name="busca" placeholder="Nome ou codigo" value="<?= $busca ?>">
    </div>

    <div class="form-group" style="max-width:160px;">
        <label>Status</label>
        <select name="status">
            <option value="">Todos</option>
            <option value="Ativo" <?= $status_filtro === 'Ativo' ? 'selected' : '' ?>>Ativo</option>
            <option value="Inativo" <?= $status_filtro === 'Inativo' ? 'selected' : '' ?>>Inativo</option>
        </select>
    </div>

    <div class="form-group" style="max-width:100px;">
        <label>&nbsp;</label>
        <button class="btn btn-primary w-100">Filtrar</button>
    </div>
</form>

<!-- TABELA -->
<div class="card-premium">
<div class="table-responsive">
<table class="table-premium">
<thead>
<tr>
    <th>Nome</th>
    <th>Tipo</th>
    <th>Mensalidade</th>
    <th>Vencimento</th>
    <th>Status</th>
    <th class="text-end">Acoes</th>
</tr>
</thead>

<tbody>

<?php if (empty($alunos)): ?>
<tr>
    <td colspan="6" class="text-center text-muted" style="padding:30px;">
        Nenhum aluno encontrado
    </td>
</tr>

<?php else: ?>
<?php foreach ($alunos as $a): ?>

<tr>
    <td>
        <strong><?= sanitize($a['nome']) ?></strong>
        <?php if (!empty($a['codigo_aluno'])): ?>
            <br><small class="text-muted"><?= sanitize($a['codigo_aluno']) ?></small>
        <?php endif; ?>
    </td>

    <td>
        <span class="badge badge-mensal">
            <?= ucfirst(sanitize($a['tipo_periodo'] ?? 'mensal')) ?>
        </span>
    </td>

    <td>
        <?= !empty($a['valor_mensalidade']) ? moeda($a['valor_mensalidade']) : '-' ?>
    </td>

    <td>
        <?= !empty($a['dia_vencimento']) ? 'Dia ' . intval($a['dia_vencimento']) : '-' ?>
    </td>

    <td>
        <span class="badge <?= $a['status'] === 'Ativo' ? 'badge-ativo' : 'badge-inativo' ?>">
            <?= sanitize($a['status']) ?>
        </span>
    </td>

    <td class="text-end">
        <a href="aluno_form.php?id=<?= intval($a['id']) ?>" class="btn btn-sm btn-info">&#9998;</a>
        <a href="<?= base_url('financeiro/gerar_financeiro.php') ?>?aluno_id=<?= intval($a['id']) ?>" class="btn btn-sm btn-success">$</a>
        <a href="aluno_status.php?id=<?= intval($a['id']) ?>" class="btn btn-sm btn-warning">&#9899;</a>
        <a href="aluno_excluir.php?id=<?= intval($a['id']) ?>" class="btn btn-sm btn-danger" onclick="return confirm('Deseja excluir este aluno?')">&#10005;</a>
    </td>
</tr>

<?php endforeach; ?>
<?php endif; ?>

</tbody>
</table>
</div>

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

</div>

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