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

// Filtros seguros
$busca = sanitize($_GET['busca'] ?? '');
$dt_ini = sanitize($_GET['dt_ini'] ?? '');
$dt_fim = sanitize($_GET['dt_fim'] ?? '');
$status_f = sanitize($_GET['status'] ?? '');
$pagina = max(1, intval($_GET['pg'] ?? 1));
$por_pagina = 25;
$offset = ($pagina - 1) * $por_pagina;

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

if ($busca !== '') {
    $where .= " AND (a.nome LIKE :busca OR cr.descricao LIKE :busca2)";
    $params['busca'] = "%{$busca}%";
    $params['busca2'] = "%{$busca}%";
}
if ($dt_ini !== '') {
    $where .= " AND cr.data_vencimento >= :dt_ini";
    $params['dt_ini'] = $dt_ini;
}
if ($dt_fim !== '') {
    $where .= " AND cr.data_vencimento <= :dt_fim";
    $params['dt_fim'] = $dt_fim;
}
if ($status_f !== '') {
    $where .= " AND cr.status = :status";
    $params['status'] = $status_f;
}

// KPIs
$kpi_vencido = $pdo->query("SELECT COALESCE(SUM(valor - valor_pago),0) FROM contas_receber WHERE data_vencimento < CURDATE() AND status='pendente'")->fetchColumn();
$kpi_avencer = $pdo->query("SELECT COALESCE(SUM(valor),0) FROM contas_receber WHERE data_vencimento >= CURDATE() AND status='pendente'")->fetchColumn();
$kpi_pago = $pdo->query("SELECT COALESCE(SUM(valor_pago),0) FROM contas_receber WHERE status='pago'")->fetchColumn();
$kpi_mes = $pdo->query("SELECT COALESCE(SUM(valor_pago),0) FROM contas_receber WHERE status='pago' AND MONTH(data_pagamento)=MONTH(CURDATE()) AND YEAR(data_pagamento)=YEAR(CURDATE())")->fetchColumn();

// Total
$stmt_t = $pdo->prepare("SELECT COUNT(*) FROM contas_receber cr LEFT JOIN alunos a ON a.id=cr.aluno_id WHERE {$where}");
$stmt_t->execute($params);
$total = $stmt_t->fetchColumn();
$total_paginas = ceil($total / $por_pagina);

// Lista
$sql = "SELECT cr.*, a.nome AS aluno_nome
        FROM contas_receber cr
        LEFT JOIN alunos a ON a.id = cr.aluno_id
        WHERE {$where}
        ORDER BY cr.data_vencimento ASC
        LIMIT {$por_pagina} OFFSET {$offset}";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$contas = $stmt->fetchAll();
?>

<div class="page-header">
    <div>
        <h2>Contas a Receber</h2>
        <div class="subtitle"><?= $total ?> registro(s)</div>
    </div>
    <div class="d-flex gap-10">
        <a href="conta_receber_form.php" class="btn btn-novo">+ Nova Conta</a>
    </div>
</div>

<!-- KPIs -->
<div class="grid-4 mb-3">
    <div class="card-kpi green">
        <div class="kpi-label">Recebido no Mes</div>
        <div class="kpi-value"><?= moeda($kpi_mes) ?></div>
    </div>
    <div class="card-kpi yellow">
        <div class="kpi-label">A Vencer</div>
        <div class="kpi-value"><?= moeda($kpi_avencer) ?></div>
    </div>
    <div class="card-kpi red">
        <div class="kpi-label">Vencido</div>
        <div class="kpi-value"><?= moeda($kpi_vencido) ?></div>
    </div>
    <div class="card-kpi blue">
        <div class="kpi-label">Total Pago</div>
        <div class="kpi-value"><?= moeda($kpi_pago) ?></div>
    </div>
</div>

<!-- Filtros -->
<form method="GET" class="filtros-bar">
    <div class="form-group">
        <label>Buscar</label>
        <input name="busca" placeholder="Aluno ou descricao" value="<?= $busca ?>">
    </div>
    <div class="form-group">
        <label>De</label>
        <input type="date" name="dt_ini" value="<?= $dt_ini ?>">
    </div>
    <div class="form-group">
        <label>Ate</label>
        <input type="date" name="dt_fim" value="<?= $dt_fim ?>">
    </div>
    <div class="form-group" style="max-width:150px;">
        <label>Status</label>
        <select name="status">
            <option value="">Todos</option>
            <option value="pendente" <?= $status_f==='pendente'?'selected':'' ?>>Pendente</option>
            <option value="pago" <?= $status_f==='pago'?'selected':'' ?>>Pago</option>
            <option value="atrasado" <?= $status_f==='atrasado'?'selected':'' ?>>Atrasado</option>
            <option value="cancelado" <?= $status_f==='cancelado'?'selected':'' ?>>Cancelado</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>Aluno</th>
    <th>Descricao</th>
    <th>Valor</th>
    <th>Pago</th>
    <th>Vencimento</th>
    <th>Parcela</th>
    <th>Status</th>
    <th class="text-end">Acoes</th>
</tr>
</thead>
<tbody>
<?php if (empty($contas)): ?>
<tr><td colspan="8" class="text-center text-muted" style="padding:30px;">Nenhuma conta encontrada</td></tr>
<?php else: ?>
<?php foreach ($contas as $c):
    $vencido = (strtotime($c['data_vencimento']) < time() && $c['status'] === 'pendente');
    $status_class = $c['status'] === 'pago' ? 'badge-pago' : ($vencido ? 'badge-vencido' : 'badge-' . $c['status']);
    $status_text = $c['status'] === 'pago' ? 'Pago' : ($vencido ? 'Vencido' : ucfirst($c['status']));
?>
<tr>
    <td><strong><?= sanitize($c['aluno_nome'] ?: '-') ?></strong></td>
    <td><?= sanitize($c['descricao']) ?></td>
    <td><?= moeda($c['valor']) ?></td>
    <td><?= $c['valor_pago'] > 0 ? moeda($c['valor_pago']) : '-' ?></td>
    <td><?= data_br($c['data_vencimento']) ?></td>
    <td class="text-center"><?= intval($c['parcela']) ?>/<?= intval($c['total_parcelas']) ?></td>
    <td><span class="badge <?= $status_class ?>"><?= $status_text ?></span></td>
    <td class="text-end">
        <a href="conta_receber_form.php?id=<?= intval($c['id']) ?>" class="btn btn-sm btn-info" title="Editar">&#9998;</a>
        <?php if ($c['status'] !== 'pago'): ?>
        <a href="conta_receber_baixar.php?id=<?= intval($c['id']) ?>" class="btn btn-sm btn-success" title="Dar Baixa">$</a>
        <?php endif; ?>
        <a href="conta_receber_excluir.php?id=<?= intval($c['id']) ?>" class="btn btn-sm btn-danger" title="Excluir" onclick="return confirm('Excluir esta conta?')">&#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) ?>&dt_ini=<?= $dt_ini ?>&dt_fim=<?= $dt_fim ?>&status=<?= $status_f ?>"
           class="<?= $i === $pagina ? 'ativo' : '' ?>"><?= $i ?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>
</div>

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