<?php
$fmt = fn($v) => $v > 0 ? number_format((float)$v, 2, ',', '.') : '';
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-wallet2 me-2 text-accent"></i>Financeiro</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<!-- Seletor de ano -->
<div class="pbi-filtro-barra mb-4 d-flex gap-2 flex-wrap align-items-center">
    <?php foreach($anos as $a): ?>
    <a href="/financeiro/despesas?ano=<?= $a ?>" class="pbi-ano-btn <?= $a===$anoSel?'ativo':'' ?>"><?= $a ?></a>
    <?php endforeach; ?>
</div>

<?php if($salvo): ?>
<div class="alert alert-success d-flex align-items-center gap-2 mb-3">
    <i class="bi bi-check-circle-fill"></i> Despesas de <?= $anoSel ?> salvas com sucesso.
</div>
<?php endif; ?>

<form method="post" action="/financeiro/despesas/salvar">
    <input type="hidden" name="ano" value="<?= $anoSel ?>">

    <div class="pbi-card mb-4">
        <div class="pbi-card-header d-flex justify-content-between">
            <span><i class="bi bi-wallet2 me-2"></i>Despesas Operacionais — <?= $anoSel ?></span>
            <small class="text-muted">Valores mensais por categoria</small>
        </div>

        <div class="pbi-hint mb-2" style="margin-top:0">Cadastre aqui, mês a mês, quanto a loja gastou em cada tipo de despesa (aluguel, salários, energia, etc.). Esses valores entram no DRE para calcular o lucro final do negócio.</div>

        <div class="table-responsive">
            <table class="pbi-table" style="min-width:900px">
                <thead>
                    <tr>
                        <th style="min-width:140px">Mês</th>
                        <?php foreach($cats as $cat): ?>
                        <th class="text-end" style="min-width:130px"><?= htmlspecialchars($cat) ?></th>
                        <?php endforeach; ?>
                        <th class="text-end">Total</th>
                    </tr>
                </thead>
                <tbody>
                <?php for($m = 1; $m <= 12; $m++):
                    $isMes = ($m == (int)date('m') && $anoSel == (int)date('Y'));
                    $totalMes = 0;
                    foreach($cats as $cat) $totalMes += (float)($dados[$anoSel][$m][$cat] ?? 0);
                ?>
                <tr <?= $isMes ? 'style="background:rgba(79,142,247,.06)"' : '' ?>>
                    <td class="fw-bold <?= $isMes ? 'text-accent' : '' ?>">
                        <?= $isMes ? '<i class="bi bi-arrow-right me-1"></i>' : '' ?>
                        <?= $nomeMeses[$m] ?>
                    </td>
                    <?php foreach($cats as $cat):
                        $key = 'desp_'.$m.'_'.md5($cat);
                        $val = (float)($dados[$anoSel][$m][$cat] ?? 0);
                    ?>
                    <td>
                        <input type="text"
                               name="<?= $key ?>"
                               value="<?= $fmt($val) ?>"
                               class="form-control form-control-sm text-end pbi-meta-input"
                               placeholder="0,00"
                               style="border-color:var(--pbi-border);background:var(--pbi-surface);color:var(--pbi-text)">
                    </td>
                    <?php endforeach; ?>
                    <td class="text-end fw-bold <?= $totalMes > 0 ? 'text-danger' : 'text-muted' ?>">
                        <?= $totalMes > 0 ? 'R$ '.number_format($totalMes,2,',','.') : '—' ?>
                    </td>
                </tr>
                <?php endfor; ?>
                </tbody>
                <tfoot>
                <?php
                $totCats = [];
                foreach($cats as $cat) {
                    $s = 0;
                    for($m=1;$m<=12;$m++) $s += (float)($dados[$anoSel][$m][$cat] ?? 0);
                    $totCats[$cat] = $s;
                }
                $totalGeral = array_sum($totCats);
                ?>
                <tr class="pbi-table-total">
                    <td class="fw-bold">Total Anual</td>
                    <?php foreach($cats as $cat): ?>
                    <td class="text-end fw-bold">
                        <?= $totCats[$cat] > 0 ? 'R$ '.number_format($totCats[$cat],2,',','.') : '—' ?>
                    </td>
                    <?php endforeach; ?>
                    <td class="text-end fw-bold text-danger">
                        <?= $totalGeral > 0 ? 'R$ '.number_format($totalGeral,2,',','.') : '—' ?>
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>

        <div class="p-3 d-flex gap-2">
            <button type="submit" class="pbi-btn-filtrar btn">
                <i class="bi bi-save me-1"></i>Salvar Despesas <?= $anoSel ?>
            </button>
            <a href="/financeiro/dre?ano=<?= $anoSel ?>" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-file-earmark-bar-graph me-1"></i>Ver DRE
            </a>
        </div>
    </div>
</form>

<div class="pbi-card">
    <div class="pbi-card-header"><i class="bi bi-info-circle me-2"></i>Como usar</div>
    <div class="p-3 text-muted small">
        <p class="mb-2">Informe o valor de cada despesa por mês. Use vírgula como decimal (ex: <strong>15.000,00</strong>).</p>
        <p class="mb-0">O <strong>DRE</strong> usará esses valores para calcular o <strong>Resultado Operacional</strong>: Margem Bruta − Despesas.</p>
    </div>
</div>
