<?php
/**
 * Financeiro / Fluxo de Caixa — shell instantâneo.
 * KPIs e dados carregados via fetch() depois do DOM pronto.
 */
$actionUrl = '/financeiro/fluxo-caixa';
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-graph-up-arrow me-2 text-accent"></i>Financeiro</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<?php include __DIR__ . '/_filtro.php'; ?>

<!-- ── KPIs skeleton ─────────────────────────────────────────────────────── -->
<div class="pbi-kpi-grid mb-4" id="kpi-grid">
    <?php for ($i = 0; $i < 5; $i++): ?>
    <div class="pbi-kpi-card">
        <div class="pbi-kpi-label pbi-skeleton" style="width:60%;height:.8rem;border-radius:4px">&nbsp;</div>
        <div class="pbi-kpi-value pbi-skeleton mt-2" style="width:80%;height:1.6rem;border-radius:4px">&nbsp;</div>
    </div>
    <?php endfor; ?>
</div>
<div class="pbi-hint mb-3" style="margin-top:0">A Receber = o que clientes te devem · A Pagar = o que você deve a fornecedores · Saldo = a diferença (quanto sobraria se tudo fosse pago) · Vencidos = títulos fora do prazo. Clique em qualquer card para ver os detalhes.</div>

<!-- ── Gráfico anual (async) ─────────────────────────────────────────────── -->
<div class="pbi-card mb-4" id="card-grafico">
    <div class="pbi-card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-graph-up-arrow me-2"></i>Fluxo Mensal <span id="ano-label"><?= htmlspecialchars((string)($filtros['anoSel'] ?? date('Y'))) ?></span></span>
        <small class="text-muted" id="grafico-status">
            <span class="pbi-skeleton d-inline-block" style="width:100px;height:.75rem;border-radius:3px">&nbsp;</span>
        </small>
    </div>
    <div class="pbi-hint mb-2" style="margin-top:0">Entradas e saídas de dinheiro previstas mês a mês: barras verdes = entradas (a receber) · barras vermelhas = saídas (a pagar) · linha azul = saldo do mês (entradas menos saídas).</div>
    <div id="chartFluxo" style="height:340px">
        <div class="d-flex align-items-center justify-content-center h-100 text-muted">
            <div class="spinner-border spinner-border-sm text-accent me-2" role="status"></div>
            <span style="font-size:.85rem">Carregando gráfico…</span>
        </div>
    </div>
    <div class="pbi-chart-hint"><i class="bi bi-cursor"></i>Clique em Entradas → Contas a Receber · Clique em Saídas → Contas a Pagar do mês</div>
</div>

<!-- ── Tabela mensal (async) ──────────────────────────────────────────────── -->
<div class="pbi-card mb-4" id="card-mensal">
    <div class="pbi-card-header"><i class="bi bi-table me-2"></i>Resumo Mensal <span id="mensal-ano-label"><?= htmlspecialchars((string)($filtros['anoSel'] ?? date('Y'))) ?></span></div>
    <div id="mensal-body">
        <div class="pbi-hint mb-2" style="margin-top:0">Previsto = o que estava agendado para entrar/sair no mês · Realizado = o que de fato foi recebido/pago · Saldo Previsto = entradas previstas menos saídas previstas (verde sobra, vermelho falta).</div>
        <div class="table-responsive">
            <table class="pbi-table">
                <thead><tr>
                    <th>Mês</th>
                    <th class="text-end">Prev. Entradas</th>
                    <th class="text-end">Prev. Saídas</th>
                    <th class="text-end">Real. Entradas</th>
                    <th class="text-end">Real. Saídas</th>
                    <th class="text-end">Saldo Previsto</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 6; $i++): ?>
                <tr>
                    <?php for ($j = 0; $j < 6; $j++): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= [40,80,80,80,80,80][$j] ?>px;height:.75rem;border-radius:3px">&nbsp;</span></td>
                    <?php endfor; ?>
                </tr>
                <?php endfor; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
window.__FINANCEIRO = {
    dataIni: <?= json_encode($filtros['dataIni']) ?>,
    dataFim: <?= json_encode($filtros['dataFim']) ?>,
    anoSel:  <?= (int)($filtros['anoSel'] ?? date('Y')) ?>,
    actionUrl: <?= json_encode($actionUrl) ?>
};
</script>

<style>
@keyframes pbi-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .4; } }
.pbi-skeleton {
  background: var(--pbi-border, #e2e8f0);
  animation: pbi-pulse 1.4s ease-in-out infinite;
  pointer-events: none;
  color: transparent !important;
}
</style>

<script src="/assets/js/echarts.min.js"></script>
<script>
(function () {
'use strict';

var ini    = window.__FINANCEIRO.dataIni;
var fim    = window.__FINANCEIRO.dataFim;
var anoSel = window.__FINANCEIRO.anoSel;
var qs     = '?data_ini=' + encodeURIComponent(ini) + '&data_fim=' + encodeURIComponent(fim) + '&ano=' + anoSel;

var mesesNomes = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];

function fmtR(v) {
    return 'R$ ' + parseFloat(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function fmtN(v, d) {
    d = d === undefined ? 0 : d;
    return parseFloat(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: d, maximumFractionDigits: d });
}
function esc(s) {
    var d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML;
}
function apiFetch(url) {
    return fetch(url, { credentials: 'same-origin' })
        .then(function (r) {
            if (!r.ok) return r.json().then(function (e) { throw new Error(e.erro || 'HTTP ' + r.status); });
            return r.json();
        });
}
function showErr(elId, msg) {
    var el = document.getElementById(elId);
    if (el) el.innerHTML = '<div class="px-3 py-3 alert alert-warning small">'
        + '<i class="bi bi-exclamation-triangle me-2"></i>' + esc(msg) + '</div>';
}

function renderKpis(kpis, anos) {
    var saldo = parseFloat(kpis.A_RECEBER || 0) - parseFloat(kpis.A_PAGAR || 0);
    var saldoCls = saldo >= 0 ? 'text-success' : 'text-danger';
    var defs = [
        { label: 'A Receber',         val: fmtR(kpis.A_RECEBER || 0),         cls: 'text-success', href: '/financeiro/contas-receber', sub: fmtN(kpis.QTD_RECEBER || 0, 0) + ' títulos →' },
        { label: 'A Pagar',           val: fmtR(kpis.A_PAGAR || 0),           cls: 'text-danger',  href: '/financeiro/contas-pagar',   sub: fmtN(kpis.QTD_PAGAR || 0, 0) + ' títulos →' },
        { label: 'Saldo',             val: fmtR(saldo),                        cls: saldoCls,       href: '/financeiro/dre',            sub: 'ver DRE →' },
        { label: 'Vencidos (Receber)',val: fmtR(kpis.VENCIDOS_RECEBER || 0),  cls: 'text-warning', href: '/financeiro/contas-receber?situacao=V', sub: 'ver vencidos →' },
        { label: 'Vencidos (Pagar)',  val: fmtR(kpis.VENCIDOS_PAGAR || 0),   cls: 'text-danger',  href: '/financeiro/contas-pagar?situacao=V',  sub: 'ver vencidos →' },
    ];
    var html = defs.map(function (d) {
        return '<a href="' + d.href + '" class="pbi-kpi-card">'
             + '<div class="pbi-kpi-label">' + d.label + '</div>'
             + '<div class="pbi-kpi-value ' + d.cls + '">' + d.val + '</div>'
             + '<div class="pbi-kpi-sub">' + d.sub + '</div>'
             + '</a>';
    }).join('');
    document.getElementById('kpi-grid').innerHTML = html;

    if (anos && anos.length) {
        var container = document.querySelector('.pbi-periodo-tabs');
        if (container) {
            var actionUrl = window.__FINANCEIRO.actionUrl;
            var html2 = anos.map(function (a) {
                a = parseInt(a);
                var ini2 = a + '-01-01', fim2 = a + '-12-31';
                var cls = (a === anoSel) ? ' active' : '';
                return '<a href="' + actionUrl + '?data_ini=' + ini2 + '&data_fim=' + fim2 + '&ano=' + a + '" '
                     + 'class="pbi-tab-ano' + cls + '" '
                     + 'onclick="setPeriodoSession(' + a + ', 0)">' + a + '</a>';
            }).join('');
            container.innerHTML = html2;
        }
    }
}

function renderFluxo(mensal, anoLabel) {
    document.getElementById('grafico-status').textContent = '';
    document.getElementById('ano-label').textContent = anoLabel;
    document.getElementById('mensal-ano-label').textContent = anoLabel;

    // Build arrays indexed by month 1-12
    var entradas = new Array(12).fill(0);
    var saidas   = new Array(12).fill(0);
    mensal.forEach(function (r) {
        var m = parseInt(r.MES) - 1;
        if (m >= 0 && m < 12) {
            entradas[m] = parseFloat(r.PREVISTO_RECEBER || 0);
            saidas[m]   = parseFloat(r.PREVISTO_PAGAR || 0);
        }
    });
    var saldo = entradas.map(function (e, i) { return Math.round((e - saidas[i]) * 100) / 100; });

    // Chart
    var chartEl = document.getElementById('chartFluxo');
    if (chartEl && typeof echarts !== 'undefined') {
        chartEl.innerHTML = '';
        var c = echarts.init(chartEl);
        c.setOption({
            backgroundColor: 'transparent',
            tooltip: { trigger: 'axis' },
            legend: { data: ['Entradas', 'Saídas', 'Saldo'], textStyle: { color: '#475569' } },
            xAxis: { type: 'category', data: mesesNomes, axisLabel: { color: '#64748b' } },
            yAxis: { type: 'value', axisLabel: { color: '#64748b', formatter: function (v) { return 'R$' + v.toLocaleString('pt-BR'); } } },
            series: [
                { name: 'Entradas', type: 'bar',  data: entradas, itemStyle: { color: '#22c55e' } },
                { name: 'Saídas',   type: 'bar',  data: saidas,   itemStyle: { color: '#ef4444' } },
                { name: 'Saldo',    type: 'line', data: saldo,    lineStyle: { color: '#4f8ef7' }, symbol: 'circle', itemStyle: { color: '#4f8ef7' } }
            ]
        });
        var mesesNum = ['01','02','03','04','05','06','07','08','09','10','11','12'];
        c.on('click', function (p) {
            var m  = mesesNum[p.dataIndex];
            var ld = new Date(anoLabel, p.dataIndex + 1, 0).getDate();
            var di = anoLabel + '-' + m + '-01';
            var df = anoLabel + '-' + m + '-' + String(ld).padStart(2, '0');
            if (p.seriesName === 'Entradas')      window.location.href = '/financeiro/contas-receber?data_ini=' + di + '&data_fim=' + df;
            else if (p.seriesName === 'Saídas')   window.location.href = '/financeiro/contas-pagar?data_ini=' + di + '&data_fim=' + df;
            else                                   window.location.href = '/financeiro/dre?ano=' + anoLabel;
        });
        window.addEventListener('resize', function () { c.resize(); });
    }

    // Table
    if (!mensal.length) {
        document.getElementById('mensal-body').innerHTML =
            '<p class="text-center text-muted py-3">Sem dados para o período.</p>';
        return;
    }
    var rows = mensal.map(function (r) {
        var saldoM = parseFloat(r.PREVISTO_RECEBER || 0) - parseFloat(r.PREVISTO_PAGAR || 0);
        var saldoCls = saldoM >= 0 ? 'text-success' : 'text-danger';
        return '<tr>'
            + '<td>' + (mesesNomes[parseInt(r.MES) - 1] || r.MES) + '</td>'
            + '<td class="text-end text-success">' + fmtR(r.PREVISTO_RECEBER || 0) + '</td>'
            + '<td class="text-end text-danger">' + fmtR(r.PREVISTO_PAGAR || 0) + '</td>'
            + '<td class="text-end">' + fmtR(r.REALIZADO_RECEBER || 0) + '</td>'
            + '<td class="text-end">' + fmtR(r.REALIZADO_PAGAR || 0) + '</td>'
            + '<td class="text-end fw-bold ' + saldoCls + '">' + fmtR(saldoM) + '</td>'
            + '</tr>';
    }).join('');

    document.getElementById('mensal-body').innerHTML =
        '<div class="pbi-hint mb-2" style="margin-top:0">Previsto = o que estava agendado para entrar/sair no mês · Realizado = o que de fato foi recebido/pago · Saldo Previsto = entradas previstas menos saídas previstas (verde sobra, vermelho falta).</div>'
        + '<div class="table-responsive">'
        + '<table class="pbi-table">'
        + '<thead><tr>'
        + '<th>Mês</th>'
        + '<th class="text-end">Prev. Entradas</th>'
        + '<th class="text-end">Prev. Saídas</th>'
        + '<th class="text-end">Real. Entradas</th>'
        + '<th class="text-end">Real. Saídas</th>'
        + '<th class="text-end">Saldo Previsto</th>'
        + '</tr></thead>'
        + '<tbody>' + rows + '</tbody>'
        + '</table></div>';
}

window.addEventListener('DOMContentLoaded', function () {
    // KPIs (also returns anos for tab update)
    apiFetch('/api/financeiro/kpis')
        .then(function (d) { renderKpis(d.kpis || {}, d.anos || []); })
        .catch(function (e) { showErr('kpi-grid', 'Erro ao carregar KPIs: ' + e.message); });

    // Fluxo data (mensal + diario)
    apiFetch('/api/financeiro/fluxo-caixa' + qs)
        .then(function (d) { renderFluxo(d.mensal || [], d.anoSel || anoSel); })
        .catch(function (e) {
            showErr('chartFluxo', 'Erro ao carregar fluxo: ' + e.message);
            showErr('mensal-body', 'Erro ao carregar resumo mensal: ' + e.message);
        });
});

})();
</script>
