<?php
/**
 * Compras / Compras × Vendas — shell instantâneo.
 * KPIs, gráfico e tabela carregados via fetch() após o DOM pronto.
 * TTFB = tempo de render PHP (<10ms), sem nenhuma query Firebird aqui.
 */
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-bar-chart-steps me-2 text-accent"></i>Compras</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<?php $actionUrl = '/compras/compras-vendas'; include __DIR__ . '/_filtro.php'; ?>

<!-- ── KPIs skeleton ─────────────────────────────────────────────────────── -->
<div class="pbi-kpi-grid mb-4" id="kpi-grid">
    <?php for ($i = 0; $i < 4; $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>
<!-- ── Caixa de explicação ────────────────────────────────────────────────── -->
<div class="pbi-card mb-3" style="background:#f8fafc">
    <div style="padding:.75rem 1.25rem">
        <div class="mb-2"><strong>⚖️ O que mostra esta tela:</strong> comparativo mês a mês entre <strong>o que você comprou</strong> (entrou de mercadoria) e <strong>o que você vendeu</strong> (saiu). Resposta de uma pergunta básica: estou comprando demais? de menos?</div>
        <div class="row g-2" style="font-size:.85rem">
            <div class="col-md-6"><strong>Vendas</strong> = soma do faturamento do mês</div>
            <div class="col-md-6"><strong>Compras</strong> = soma das notas de entrada do mês</div>
            <div class="col-md-6"><strong>Saldo</strong> = Vendas − Compras (margem bruta antes das despesas operacionais)</div>
            <div class="col-md-6"><strong>CMV % (Compras ÷ Vendas)</strong> = Compras ÷ Vendas. <span style="color:#16a34a">Abaixo de 70% é saudável</span>; entre 70-85% atenção; acima de 85% sinal de prejuízo</div>
        </div>
    </div>
</div>

<!-- ── Gráfico skeleton ──────────────────────────────────────────────────── -->
<div class="pbi-card mb-4" id="card-chart">
    <div class="pbi-card-header"><i class="bi bi-bar-chart-steps me-2"></i>Compras × Vendas <span id="ano-label"></span></div>
    <div class="pbi-hint mb-2" style="margin-top:0;padding:8px 12px 0">Compara, mês a mês, o que entrou (compras) com o que saiu (vendas). Clique numa barra para ver os detalhes do mês.</div>
    <div id="chartCV" style="height:350px">
        <div class="d-flex align-items-center justify-content-center h-100 text-muted small">
            <div class="spinner-border spinner-border-sm me-2 text-accent"></div>Carregando…
        </div>
    </div>
</div>

<!-- ── Tabela skeleton ───────────────────────────────────────────────────── -->
<div class="pbi-card" id="card-mensal">
    <div class="pbi-card-header"><i class="bi bi-table me-2"></i>Detalhamento Mensal</div>
    <div class="pbi-hint mb-2" style="margin-top:0;padding:8px 12px 0">Vendas e Compras de cada mês. Saldo = Vendas − Compras. CMV % (Compras ÷ Vendas) = compras ÷ vendas; abaixo de 70% é saudável.</div>
    <div id="mensal-body">
        <div class="table-responsive">
            <table class="pbi-table">
                <thead><tr>
                    <th>Mês</th>
                    <th class="text-end">Vendas</th>
                    <th class="text-end">Compras</th>
                    <th class="text-end">Saldo</th>
                    <th class="text-end">CMV % (Compras ÷ Vendas)</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 6; $i++): ?>
                <tr>
                    <?php $widths = [55, 90, 90, 90, 55]; ?>
                    <?php foreach ($widths as $w): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= $w ?>px;height:.75rem;border-radius:3px">&nbsp;</span></td>
                    <?php endforeach; ?>
                </tr>
                <?php endfor; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ── Config injetada pelo PHP para o JS usar ──────────────────────────── -->
<script>
window.__COMPRAS_CV = {
    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.__COMPRAS_CV.dataIni;
var fim    = window.__COMPRAS_CV.dataFim;
var anoSel = window.__COMPRAS_CV.anoSel;
var qs     = '?ano=' + encodeURIComponent(anoSel);

var MESES = ['','Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
var MESES_NUM = ['01','02','03','04','05','06','07','08','09','10','11','12'];

function fmtR(v) {
    return 'R$ ' + parseFloat(v || 0).toLocaleString('pt-BR', {minimumFractionDigits:2, maximumFractionDigits:2});
}
function fmtPct(v) {
    return parseFloat(v || 0).toLocaleString('pt-BR', {minimumFractionDigits:1, maximumFractionDigits:1}) + '%';
}
function esc(s) {
    var d = document.createElement('div');
    d.textContent = s == null ? '' : String(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 atualizarAnosAbas(anos, anoAtual) {
    var container = document.querySelector('.pbi-periodo-tabs');
    if (!container) return;
    var actionUrl = window.__COMPRAS_CV.actionUrl;
    var html = anos.map(function(a) {
        a = parseInt(a);
        var ini2 = a + '-01-01', fim2 = a + '-12-31';
        var cls = (a === anoAtual) ? ' active' : '';
        return '<a href="' + actionUrl + '?data_ini=' + ini2 + '&data_fim=' + fim2 + '" '
             + 'class="pbi-tab-ano' + cls + '" '
             + 'onclick="setPeriodoSession(' + a + ', 0)">' + a + '</a>';
    }).join('');
    container.innerHTML = html;
}

function renderCV(linhas, anos, ano) {
    if (anos && anos.length) atualizarAnosAbas(anos, ano);

    var el = document.getElementById('ano-label');
    if (el) el.textContent = ano;

    var totalVend = linhas.reduce(function(s, r) { return s + parseFloat(r.VENDAS || 0); }, 0);
    var totalComp = linhas.reduce(function(s, r) { return s + parseFloat(r.COMPRAS || 0); }, 0);
    var saldo = totalVend - totalComp;
    var cmvPct = totalVend > 0 ? totalComp / totalVend * 100 : 0;

    // KPIs
    document.getElementById('kpi-grid').innerHTML =
        '<div class="pbi-kpi-card">'
        + '<div class="pbi-kpi-label">Total Vendas</div>'
        + '<div class="pbi-kpi-value text-accent">' + fmtR(totalVend) + '</div>'
        + '</div>'
        + '<div class="pbi-kpi-card">'
        + '<div class="pbi-kpi-label">Total Compras</div>'
        + '<div class="pbi-kpi-value text-danger">' + fmtR(totalComp) + '</div>'
        + '</div>'
        + '<div class="pbi-kpi-card">'
        + '<div class="pbi-kpi-label">Saldo</div>'
        + '<div class="pbi-kpi-value ' + (saldo >= 0 ? 'text-success' : 'text-danger') + '">' + fmtR(saldo) + '</div>'
        + '</div>'
        + '<div class="pbi-kpi-card">'
        + '<div class="pbi-kpi-label">CMV % (Compras ÷ Vendas)</div>'
        + '<div class="pbi-kpi-value">' + (totalVend > 0 ? fmtPct(cmvPct) : '—') + '</div>'
        + '</div>';

    // Gráfico
    var gMeses  = linhas.map(function(r) { return MESES[parseInt(r.MES)] || r.MES; });
    var gVendas = linhas.map(function(r) { return Math.round(parseFloat(r.VENDAS || 0) * 100) / 100; });
    var gCompras= linhas.map(function(r) { return Math.round(parseFloat(r.COMPRAS || 0) * 100) / 100; });

    var c = echarts.init(document.getElementById('chartCV'));
    c.setOption({
        backgroundColor: 'transparent',
        tooltip: {trigger: 'axis'},
        legend: {data: ['Vendas', 'Compras'], textStyle: {color: '#475569'}},
        xAxis: {type: 'category', data: gMeses, axisLabel: {color: '#64748b'}},
        yAxis: {type: 'value', axisLabel: {color: '#64748b', formatter: function(v) { return 'R$' + v.toLocaleString('pt-BR'); }}},
        series: [
            {name:'Vendas',  type:'bar', data:gVendas,  itemStyle:{color:'#4f8ef7'}, emphasis:{itemStyle:{color:'#3a6fd8'}}, cursor:'pointer'},
            {name:'Compras', type:'bar', data:gCompras, itemStyle:{color:'#ef4444'}, emphasis:{itemStyle:{color:'#b91c1c'}}, cursor:'pointer'}
        ]
    });
    c.on('click', function(p) {
        var m = MESES_NUM[p.dataIndex];
        var ld = new Date(ano, p.dataIndex + 1, 0).getDate();
        var dIni = ano + '-' + m + '-01';
        var dFim = ano + '-' + m + '-' + String(ld).padStart(2, '0');
        if (p.seriesName === 'Compras') window.location.href = '/compras/notas-entrada?data_ini=' + dIni + '&data_fim=' + dFim;
        else window.location.href = '/financeiro/fluxo-caixa?data_ini=' + dIni + '&data_fim=' + dFim + '&ano=' + ano;
    });
    window.addEventListener('resize', function() { c.resize(); });

    // Tabela
    if (!linhas.length) {
        document.getElementById('mensal-body').innerHTML =
            '<p class="text-center text-muted py-4">Sem dados para o ano ' + ano + '.</p>';
        return;
    }

    var rows = linhas.map(function(r) {
        var v = parseFloat(r.VENDAS || 0);
        var comp = parseFloat(r.COMPRAS || 0);
        var s = v - comp;
        var cmvp = v > 0 ? comp / v * 100 : 0;
        var cmvCls = cmvp < 70 ? 'text-success' : (cmvp < 90 ? 'text-warning' : 'text-danger');
        var saldoCls = s >= 0 ? 'text-success' : 'text-danger';
        return '<tr>'
            + '<td>' + (MESES[parseInt(r.MES)] || r.MES) + '</td>'
            + '<td class="text-end text-accent">' + fmtR(v) + '</td>'
            + '<td class="text-end text-danger">' + fmtR(comp) + '</td>'
            + '<td class="text-end fw-bold ' + saldoCls + '">' + fmtR(s) + '</td>'
            + '<td class="text-end ' + cmvCls + '">' + fmtPct(cmvp) + '</td>'
            + '</tr>';
    }).join('');

    document.getElementById('mensal-body').innerHTML =
        '<div class="table-responsive">'
        + '<table class="pbi-table">'
        + '<thead><tr><th>Mês</th>'
        + '<th class="text-end">Vendas</th><th class="text-end">Compras</th>'
        + '<th class="text-end">Saldo</th><th class="text-end">CMV % (Compras ÷ Vendas)</th>'
        + '</tr></thead><tbody>' + rows + '</tbody></table></div>';
}

window.addEventListener('DOMContentLoaded', function () {
    apiFetch('/api/compras/compras-vendas' + qs)
        .then(function (d) {
            renderCV(d.linhas || [], d.anos || [], d.anoSel || anoSel);
        })
        .catch(function (e) {
            document.getElementById('kpi-grid').innerHTML =
                '<div class="alert alert-warning small col-span-4"><i class="bi bi-exclamation-triangle me-2"></i>' + esc(e.message) + '</div>';
            document.getElementById('mensal-body').innerHTML =
                '<div class="px-3 py-3 alert alert-warning small"><i class="bi bi-exclamation-triangle me-2"></i>' + esc(e.message) + '</div>';
        });
});

})();
</script>
