<?php
/**
 * Financeiro / DRE — shell instantâneo.
 * KPIs, gráfico e tabela carregados via fetch() depois do DOM pronto.
 */
$actionUrl = '/financeiro/dre';
$anoAtual  = (int)($filtros['anoSel'] ?? date('Y'));
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-file-earmark-bar-graph me-2 text-accent"></i>Financeiro</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<?php $mostrarDatePicker = false; include __DIR__ . '/_filtro.php'; ?>

<!-- ── Aviso: DRE indisponivel (CMV inconfiavel) ─────────────────────────── -->
<div id="dre-aviso" hidden class="pbi-card mb-4" style="border-left:4px solid #f59e0b">
    <div class="pbi-card-body" style="padding:16px 20px">
        <div style="display:flex;gap:14px;align-items:flex-start">
            <i class="bi bi-exclamation-triangle-fill" style="color:#f59e0b;font-size:24px;flex:0 0 auto;line-height:1.2"></i>
            <div style="flex:1">
                <strong style="color:#f59e0b;font-size:15.5px">DRE indisponível neste período</strong>
                <div style="color:var(--pbi-muted);font-size:13.5px;line-height:1.65;margin-top:6px">
                    O <strong>CMV (Custo da Mercadoria Vendida)</strong> que veio do ERP Fire Sistemas
                    ficou maior que a receita do período — isso não é real e impede o cálculo do lucro.
                    Pra não te passar um DRE com prejuízo falso, escondemos o gráfico, os KPIs e a tabela.
                </div>

                <details style="margin-top:12px">
                    <summary style="cursor:pointer;color:#f59e0b;font-weight:600;font-size:13.5px;list-style:none;display:inline-flex;align-items:center;gap:6px">
                        <i class="bi bi-chevron-right" style="transition:.2s"></i>
                        Ver por que isso acontece e como resolver
                    </summary>
                    <div style="color:var(--pbi-muted);font-size:13px;line-height:1.65;padding-top:10px;margin-top:6px;border-top:1px solid var(--pbi-border)">
                        <p style="margin:0 0 10px"><strong style="color:var(--pbi-text)">Por que acontece (típico em bar/distribuidora):</strong></p>
                        <ul style="margin:0 0 14px;padding-left:20px">
                            <li><strong>Produtos sem custo cadastrado</strong> — drinks, porções e combos compostos costumam não ter o custo unitário preenchido no ERP Fire Sistemas.</li>
                            <li><strong>Caixa lançada como unidade</strong> — caixa de cerveja entra com custo da caixa inteira em cada garrafa, em vez de dividir por 12 ou 24.</li>
                            <li><strong>Custo de compra inflado</strong> — quando a entrada da nota inclui ICMS + IPI + frete embutidos no custo unitário, o custo fica maior que o próprio preço de venda.</li>
                        </ul>

                        <p style="margin:0 0 10px"><strong style="color:var(--pbi-text)">Como resolver no ERP Fire Sistemas:</strong></p>
                        <ol style="margin:0 0 14px;padding-left:20px">
                            <li>Cadastro de Itens → preencher <strong>Custo Médio</strong> nos produtos mais vendidos.</li>
                            <li>Para caixas: ajustar a <strong>quantidade do fator de venda</strong> (12, 24, etc.) pra dividir o custo certo.</li>
                            <li>Ao lançar Nota de Entrada, conferir se o <strong>custo unitário</strong> está coerente com o preço de venda.</li>
                        </ol>

                        <p style="margin:0 0 6px"><strong style="color:var(--pbi-text)">Enquanto isso, pra acompanhar o resultado:</strong></p>
                        <ul style="margin:0;padding-left:20px">
                            <li><a href="/compras/compras-vendas" style="color:var(--pbi-accent)"><i class="bi bi-arrow-right-circle me-1"></i>Compras × Vendas</a> — mostra quanto entrou vs quanto saiu por período (não depende de custo unitário cadastrado).</li>
                            <li><a href="/vendas/mensais" style="color:var(--pbi-accent)"><i class="bi bi-arrow-right-circle me-1"></i>Vendas Mensais</a> — receita mensal continua 100% correta.</li>
                        </ul>
                    </div>
                </details>
            </div>
        </div>
    </div>
</div>
<style>
#dre-aviso details[open] > summary > .bi-chevron-right { transform: rotate(90deg); }
#dre-aviso summary::-webkit-details-marker { display:none }
</style>

<!-- ── KPIs skeleton ─────────────────────────────────────────────────────── -->
<div class="pbi-kpi-grid mb-4" id="kpi-grid">
    <?php for ($i = 0; $i < 3; $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">DRE (Demonstrativo de Resultado) mostra se a loja deu lucro. Receita Bruta = total vendido · CMV (Custo da Mercadoria Vendida) = quanto custou comprar o que foi vendido · Margem Bruta = o que sobra das vendas depois do custo da mercadoria (antes das despesas).</div>

<!-- ── Gráfico DRE (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-bar-chart me-2"></i>DRE Mensal — <span id="dre-ano-label"><?= $anoAtual ?></span></span>
        <a href="/financeiro/despesas?ano=<?= $anoAtual ?>" class="btn btn-sm btn-outline-secondary" id="despesas-link">
            <i class="bi bi-wallet2 me-1"></i>Despesas
        </a>
    </div>
    <div class="pbi-hint mb-2" style="margin-top:0">Mês a mês: barras azuis = Receita Bruta (total vendido) · barras vermelhas = CMV (custo do que foi vendido) · linha verde = Margem Bruta (o que sobra). Quanto maior a distância entre a barra azul e a vermelha, melhor.</div>
    <div id="chartDre" 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 DRE…</span>
        </div>
    </div>
</div>

<!-- ── Tabela DRE (async) ────────────────────────────────────────────────── -->
<div class="pbi-card" id="card-dre">
    <div class="pbi-card-header"><i class="bi bi-table me-2"></i>DRE Detalhado por Mês — <span id="dre-tabela-ano"><?= $anoAtual ?></span></div>
    <div id="dre-body">
        <div class="pbi-hint mb-2" style="margin-top:0">Leia da esquerda para a direita: Receita Bruta − Descontos = Receita Líquida; − CMV (custo da mercadoria) = Margem Bruta. Mg% é quanto da venda virou margem — quanto maior, melhor. Depois é só subtrair as Despesas para chegar ao resultado final.</div>
        <div class="table-responsive">
            <table class="pbi-table">
                <thead><tr>
                    <th>Mês</th>
                    <th class="text-end">Rec. Bruta</th>
                    <th class="text-end">(-) Desc.</th>
                    <th class="text-end">Rec. Líquida</th>
                    <th class="text-end">(-) CMV</th>
                    <th class="text-end">Margem Bruta</th>
                    <th class="text-end">Mg%</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 6; $i++): ?>
                <tr>
                    <?php for ($j = 0; $j < 7; $j++): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= [35,80,70,80,70,80,45][$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:    <?= $anoAtual ?>,
    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 anoSel = window.__FINANCEIRO.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 fmtP(v) {
    return parseFloat(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + '%';
}
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>';
}

// Load despesas from /config/despesas.json via API if available, otherwise skip
function getDespesasMes(anoLabel) {
    // Attempt to load from a known endpoint; if not available resolve empty
    return Promise.resolve({});
}

function renderDRE(linhas, anoLabel) {
    document.getElementById('dre-ano-label').textContent = anoLabel;
    document.getElementById('dre-tabela-ano').textContent = anoLabel;
    document.getElementById('despesas-link').href = '/financeiro/despesas?ano=' + anoLabel;

    // Index by month
    var byMes = {};
    linhas.forEach(function (r) { byMes[parseInt(r.MES)] = r; });

    // Totals
    var totalRec = 0, totalDes = 0, totalCMV = 0;
    linhas.forEach(function (r) {
        totalRec += parseFloat(r.RECEITA_BRUTA || 0);
        totalDes += parseFloat(r.DESCONTOS || 0);
        totalCMV += parseFloat(r.CMV || 0);
    });
    var recLiq   = totalRec - totalDes;
    var margBruta = recLiq - totalCMV;

    // KPIs
    var defs = [
        { label: 'Receita Bruta', val: fmtR(totalRec),   cls: 'text-accent' },
        { label: '(-) CMV',       val: fmtR(totalCMV),   cls: 'text-danger',
          sub: recLiq > 0 ? fmtP(totalCMV / recLiq * 100) + ' da rec. líq.' : '' },
        { label: '= Margem Bruta',val: fmtR(margBruta),  cls: margBruta >= 0 ? 'text-primary' : 'text-danger',
          sub: recLiq > 0 ? fmtP(margBruta / recLiq * 100) + ' margem' : '',
          border: '#4f8ef7' },
    ];
    var kpiHtml = defs.map(function (d) {
        return '<div class="pbi-kpi-card"' + (d.border ? ' style="border-color:' + d.border + '"' : '') + '>'
             + '<div class="pbi-kpi-label">' + d.label + '</div>'
             + '<div class="pbi-kpi-value ' + d.cls + '">' + d.val + '</div>'
             + (d.sub ? '<div class="pbi-kpi-sub">' + d.sub + '</div>' : '')
             + '</div>';
    }).join('');
    document.getElementById('kpi-grid').innerHTML = kpiHtml;

    // Chart arrays (12 months)
    var gRec = [], gCMV = [], gMargem = [];
    for (var m = 1; m <= 12; m++) {
        var r   = byMes[m] || { RECEITA_BRUTA: 0, DESCONTOS: 0, CMV: 0 };
        var rb  = parseFloat(r.RECEITA_BRUTA || 0);
        var dc  = parseFloat(r.DESCONTOS || 0);
        var cmv = parseFloat(r.CMV || 0);
        var rl  = rb - dc;
        gRec.push(Math.round(rb * 100) / 100);
        gCMV.push(Math.round(cmv * 100) / 100);
        gMargem.push(Math.round((rl - cmv) * 100) / 100);
    }

    var chartEl = document.getElementById('chartDre');
    if (chartEl && typeof echarts !== 'undefined') {
        chartEl.innerHTML = '';
        var c = echarts.init(chartEl);
        c.setOption({
            backgroundColor: 'transparent',
            tooltip: {
                trigger: 'axis',
                formatter: function (p) {
                    return p[0].axisValue + '<br>' + p.map(function (s) {
                        return s.marker + s.seriesName + ': R$ ' + parseFloat(s.data || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2 });
                    }).join('<br>');
                }
            },
            legend: { data: ['Receita Bruta', 'CMV', 'Margem Bruta'], textStyle: { color: '#475569' } },
            xAxis: { type: 'category', data: mesesNomes, axisLabel: { color: '#64748b', fontSize: 11 } },
            yAxis: { type: 'value', axisLabel: { color: '#64748b', formatter: function (v) { return 'R$' + (v / 1000).toFixed(0) + 'k'; } } },
            series: [
                { name: 'Receita Bruta', type: 'bar',  data: gRec,    itemStyle: { color: '#4f8ef7' } },
                { name: 'CMV',           type: 'bar',  data: gCMV,    itemStyle: { color: '#ef4444' } },
                { name: 'Margem Bruta',  type: 'line', data: gMargem, lineStyle: { color: '#22c55e', width: 2 }, symbol: 'circle', symbolSize: 6,
                  itemStyle: { color: function (p) { return p.data >= 0 ? '#22c55e' : '#ef4444'; } } }
            ]
        });
        window.addEventListener('resize', function () { c.resize(); });
    }

    // Table
    var rows = '';
    for (var m2 = 1; m2 <= 12; m2++) {
        var rd   = byMes[m2] || { RECEITA_BRUTA: 0, DESCONTOS: 0, CMV: 0 };
        var rb2  = parseFloat(rd.RECEITA_BRUTA || 0);
        var dc2  = parseFloat(rd.DESCONTOS || 0);
        var cmv2 = parseFloat(rd.CMV || 0);
        var rl2  = rb2 - dc2;
        var mb2  = rl2 - cmv2;
        var mgp  = rl2 > 0 ? mb2 / rl2 * 100 : 0;
        var vazio = rb2 === 0 && cmv2 === 0;
        var mbCls = mb2 >= 0 ? 'text-primary' : 'text-danger';
        var mgCls = mgp >= 30 ? 'text-success' : (mgp >= 0 ? 'text-warning' : 'text-danger');
        rows += '<tr' + (vazio ? ' style="opacity:.4"' : '') + '>'
            + '<td class="fw-bold">' + mesesNomes[m2 - 1] + '</td>'
            + '<td class="text-end">' + (rb2 > 0 ? fmtR(rb2) : '—') + '</td>'
            + '<td class="text-end text-warning">' + (dc2 > 0 ? fmtR(dc2) : '—') + '</td>'
            + '<td class="text-end">' + (rl2 > 0 ? fmtR(rl2) : '—') + '</td>'
            + '<td class="text-end text-danger">' + (cmv2 > 0 ? fmtR(cmv2) : '—') + '</td>'
            + '<td class="text-end fw-bold ' + mbCls + '">' + (rl2 > 0 ? fmtR(mb2) : '—') + '</td>'
            + '<td class="text-end ' + mgCls + '">' + (rl2 > 0 ? fmtP(mgp) : '—') + '</td>'
            + '</tr>';
    }

    var tfoot = '<tfoot><tr class="pbi-table-total">'
        + '<td class="fw-bold">Total</td>'
        + '<td class="text-end fw-bold">' + fmtR(totalRec) + '</td>'
        + '<td class="text-end fw-bold text-warning">' + fmtR(totalDes) + '</td>'
        + '<td class="text-end fw-bold">' + fmtR(recLiq) + '</td>'
        + '<td class="text-end fw-bold text-danger">' + fmtR(totalCMV) + '</td>'
        + '<td class="text-end fw-bold ' + (margBruta >= 0 ? 'text-primary' : 'text-danger') + '">' + fmtR(margBruta) + '</td>'
        + '<td class="text-end fw-bold">' + (recLiq > 0 ? fmtP(margBruta / recLiq * 100) : '—') + '</td>'
        + '</tr></tfoot>';

    document.getElementById('dre-body').innerHTML =
        '<div class="pbi-hint mb-2" style="margin-top:0">Leia da esquerda para a direita: Receita Bruta − Descontos = Receita Líquida; − CMV (custo da mercadoria) = Margem Bruta. Mg% é quanto da venda virou margem — quanto maior, melhor. Depois é só subtrair as Despesas para chegar ao resultado final.</div>'
        + '<div class="table-responsive">'
        + '<table class="pbi-table">'
        + '<thead><tr>'
        + '<th>Mês</th>'
        + '<th class="text-end">Rec. Bruta</th>'
        + '<th class="text-end">(-) Desc.</th>'
        + '<th class="text-end">Rec. Líquida</th>'
        + '<th class="text-end">(-) CMV</th>'
        + '<th class="text-end">Margem Bruta</th>'
        + '<th class="text-end">Mg%</th>'
        + '</tr></thead>'
        + '<tbody>' + rows + '</tbody>'
        + tfoot
        + '</table></div>';
}

function desabilitarDre() {
    // ERP nao grava custo direito → DRE inteiro nao faz sentido. Mostra aviso e esconde tudo.
    ['kpi-grid','card-grafico','card-dre'].forEach(function(id){
        var el = document.getElementById(id); if(el) el.style.display = 'none';
    });
    var av = document.getElementById('dre-aviso'); if(av) av.hidden = false;
}

window.addEventListener('DOMContentLoaded', function () {
    apiFetch('/api/financeiro/dre?ano=' + anoSel)
        .then(function (d) {
            // Backend marca confiavel=false quando CMV agregado >= receita
            // (ERP nao cadastra custo nos itens ou soma compras superiores as vendas).
            if (d && d.confiavel === false) { desabilitarDre(); return; }
            renderDRE(d.linhas || [], d.anoSel || anoSel);
        })
        .catch(function (e) {
            showErr('kpi-grid', 'Erro ao carregar DRE: ' + e.message);
            showErr('dre-body', 'Erro ao carregar DRE: ' + e.message);
            showErr('chartDre', 'Erro ao carregar DRE: ' + e.message);
        });
});

})();
</script>
