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

$contas = $pdo->query("SELECT * FROM contas_bancarias ORDER BY status ASC, nome ASC")->fetchAll();

// Saldo total
$saldo_total = $pdo->query("SELECT COALESCE(SUM(saldo_atual),0) FROM contas_bancarias WHERE status='ativo'")->fetchColumn();
?>

<div class="page-header">
    <div>
        <h2>Contas Bancarias</h2>
        <div class="subtitle">Controle de contas e saldos</div>
    </div>
    <a href="conta_bancaria_form.php" class="btn btn-novo">+ Nova Conta</a>
</div>

<div class="grid-3 mb-3">
    <div class="card-kpi blue">
        <div class="kpi-label">Saldo Total</div>
        <div class="kpi-value"><?= moeda($saldo_total) ?></div>
        <div class="kpi-sub">Soma de todas as contas ativas</div>
    </div>
    <div class="card-kpi green">
        <div class="kpi-label">Contas Ativas</div>
        <div class="kpi-value"><?= count(array_filter($contas, fn($c) => $c['status']==='ativo')) ?></div>
    </div>
    <div class="card-kpi purple">
        <div class="kpi-label">Total Cadastradas</div>
        <div class="kpi-value"><?= count($contas) ?></div>
    </div>
</div>

<div class="card-premium">
<div class="table-responsive">
<table class="table-premium">
<thead>
<tr>
    <th>Nome</th>
    <th>Banco</th>
    <th>Agencia/Conta</th>
    <th>Tipo</th>
    <th>Saldo Atual</th>
    <th>Status</th>
    <th class="text-end">Acoes</th>
</tr>
</thead>
<tbody>
<?php if (empty($contas)): ?>
<tr><td colspan="7" class="text-center text-muted" style="padding:30px;">Nenhuma conta bancaria cadastrada</td></tr>
<?php else: ?>
<?php foreach ($contas as $c): ?>
<tr>
    <td><strong><?= sanitize($c['nome']) ?></strong></td>
    <td><?= sanitize($c['banco'] ?: '-') ?></td>
    <td><?= sanitize(($c['agencia'] ?: '-') . ' / ' . ($c['numero_conta'] ?: '-')) ?></td>
    <td><span class="badge badge-mensal"><?= ucfirst(str_replace('_', ' ', $c['tipo'])) ?></span></td>
    <td class="<?= $c['saldo_atual'] >= 0 ? 'text-success' : 'text-danger' ?>">
        <strong><?= moeda($c['saldo_atual']) ?></strong>
    </td>
    <td><span class="badge <?= $c['status']==='ativo' ? 'badge-ativo' : 'badge-inativo' ?>"><?= ucfirst($c['status']) ?></span></td>
    <td class="text-end">
        <a href="extrato_bancario.php?conta_id=<?= intval($c['id']) ?>" class="btn btn-sm btn-info" title="Ver Extrato">&#128196;</a>
        <a href="conta_bancaria_form.php?id=<?= intval($c['id']) ?>" class="btn btn-sm btn-warning" title="Editar">&#9998;</a>
    </td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>

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