<?php
/**
 * Compras / Notas de Entrada — shell instantâneo.
 * KPIs, tabela e card de itens são carregados via fetch() depois do 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-truck me-2 text-accent"></i>Compras</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<?php $actionUrl = '/compras/notas-entrada'; 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> cada <strong>nota de entrada</strong> é a mercadoria que o fornecedor entregou pra você. Lista nota por nota, com detalhe dos itens recebidos.</div>
        <div class="row g-2" style="font-size:.85rem">
            <div class="col-md-6"><strong>Total Comprado</strong> = soma do valor de todas as notas do período</div>
            <div class="col-md-6"><strong>Descontos</strong> = quanto foi abatido pelo fornecedor nas compras</div>
            <div class="col-md-6"><strong>Tipo de Operação</strong> = código que o ERP Fire Sistemas usa pra classificar a nota (compra normal, devolução, transferência, etc.)</div>
            <div class="col-md-6"><strong>Total dos Produtos</strong> = valor antes do desconto · <strong>Total da Nota</strong> = valor final pago</div>
        </div>
    </div>
</div>

<!-- ── Card: Itens Mais Caros por Marca (async) ───────────────────────────── -->
<div class="pbi-card mb-4" id="card-itens-caros">
  <div class="pbi-card-header d-flex justify-content-between align-items-center">
    <span><i class="bi bi-award me-2 text-warning"></i>Itens Mais Caros por Marca</span>
    <small class="text-muted" id="itens-caros-badge"><span class="pbi-skeleton d-inline-block" style="width:120px;height:.75rem;border-radius:3px">&nbsp;</span></small>
  </div>
  <div class="pbi-hint mb-2" style="margin-top:0;padding:8px 12px 0">Itens com o maior preço unitário pago no período. Preço Máx. = maior valor pago pela unidade; Preço Médio = média paga.</div>
  <div id="itens-caros-body">
    <div class="px-3 py-4 text-center text-muted">
      <div class="spinner-border spinner-border-sm text-accent me-2" role="status"></div>
      <span style="font-size:.85rem">Carregando itens…</span>
    </div>
  </div>
</div>

<!-- ── Tabela de Notas de Entrada (async) ───────────────────────────────── -->
<div class="pbi-card" id="card-notas">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-file-earmark-arrow-down me-2"></i>Notas de Entrada</span>
        <small class="text-muted" id="notas-badge">
            <span class="pbi-skeleton d-inline-block" style="width:80px;height:.75rem;border-radius:3px">&nbsp;</span>
        </small>
    </div>
    <div class="pbi-hint mb-2" style="margin-top:0;padding:8px 12px 0">Cada nota de mercadoria recebida do fornecedor. Tipo de Operação = tipo de operação no ERP Fire Sistemas; Total dos Produtos = valor antes do desconto; Total da Nota = valor final pago.</div>
    <div id="notas-body">
        <!-- Skeleton table -->
        <div class="table-responsive">
            <table class="pbi-table">
                <thead><tr>
                    <th>Nota</th><th>Emissão</th><th>Fornecedor</th>
                    <th>Tipo de Operação</th>
                    <th class="text-end">Total dos Produtos</th>
                    <th class="text-end">Desconto</th>
                    <th class="text-end">Total da Nota</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 8; $i++): ?>
                <tr>
                    <?php for ($j = 0; $j < 7; $j++): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= [55,65,140,90,75,60,80][$j] ?>px;height:.75rem;border-radius:3px">&nbsp;</span></td>
                    <?php endfor; ?>
                </tr>
                <?php endfor; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ── Config injetada pelo PHP para o JS usar ──────────────────────────── -->
<script>
window.__COMPRAS = {
    dataIni: <?= json_encode($filtros['dataIni']) ?>,
    dataFim: <?= json_encode($filtros['dataFim']) ?>,
    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>
(function () {
'use strict';

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

// ── Formatadores ──────────────────────────────────────────────────────────
function fmtR(v, d) {
    d = d === undefined ? 2 : d;
    return 'R$ ' + parseFloat(v || 0).toLocaleString('pt-BR', {
        minimumFractionDigits: d, maximumFractionDigits: d
    });
}
function fmtN(v, d) {
    return parseFloat(v || 0).toLocaleString('pt-BR', {
        minimumFractionDigits: d === undefined ? 2 : d,
        maximumFractionDigits: d === undefined ? 2 : d
    });
}
function fmtData(s) {
    if (!s) return '—';
    // "2026-05-22" → "22/05/2026"
    return s.substring(8, 10) + '/' + s.substring(5, 7) + '/' + s.substring(0, 4);
}
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();
        });
}

// ── Render KPIs ───────────────────────────────────────────────────────────
function renderKpis(kpis, anos) {
    var defs = [
        { label: 'Notas de Entrada', val: fmtN(kpis.QTD_NOTAS || 0, 0),     cls: '' },
        { label: 'Fornecedores',     val: fmtN(kpis.QTD_FORNECEDORES || 0, 0), cls: '' },
        { label: 'Total Comprado',   val: fmtR(kpis.TOTAL_COMPRAS || 0),     cls: 'text-accent' },
        { label: 'Descontos',        val: fmtR(kpis.TOTAL_DESCONTO || 0),    cls: 'text-success' },
    ];
    var html = defs.map(function (d) {
        return '<div class="pbi-kpi-card">'
             + '<div class="pbi-kpi-label">' + d.label + '</div>'
             + '<div class="pbi-kpi-value ' + d.cls + '">' + d.val + '</div>'
             + '</div>';
    }).join('');
    document.getElementById('kpi-grid').innerHTML = html;

    // Atualiza abas de anos com os anos reais do banco
    if (anos && anos.length) atualizarAnosAbas(anos);
}

// ── Atualiza abas de anos com dados reais do banco ────────────────────────
function atualizarAnosAbas(anos) {
    var container = document.querySelector('.pbi-periodo-tabs');
    if (!container) return;
    var actionUrl = window.__COMPRAS.actionUrl;
    var anoAtual = parseInt(ini.substring(0, 4));
    var html = anos.map(function (a) {
        var 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;
}

// ── Render tabela de notas ────────────────────────────────────────────────
function renderNotas(notas) {
    document.getElementById('notas-badge').textContent = notas.length + ' registros';
    if (!notas.length) {
        document.getElementById('notas-body').innerHTML =
            '<p class="text-center text-muted py-4">Nenhuma nota encontrada no período.</p>';
        return;
    }
    var rows = notas.map(function (r) {
        var serie = (r.SERIE || '').trim();
        var nota  = r.NR_NOTA + (serie ? '/' + serie : '');
        return '<tr>'
            + '<td>' + esc(nota) + '</td>'
            + '<td>' + fmtData(r.DATA_EMISSAO) + '</td>'
            + '<td>' + esc((r.FORNECEDOR || '—').substring(0, 35)) + '</td>'
            + '<td class="text-muted small">' + esc((r.TIPO_OP || '').substring(0, 30)) + '</td>'
            + '<td class="text-end">' + fmtR(r.TOTAL_PRODUTOS) + '</td>'
            + '<td class="text-end text-success">' + fmtR(r.DESCONTO) + '</td>'
            + '<td class="text-end fw-bold">' + fmtR(r.TOTAL_NOTA) + '</td>'
            + '</tr>';
    }).join('');

    document.getElementById('notas-body').innerHTML =
        '<div class="table-responsive">'
        + '<table class="pbi-table">'
        + '<thead><tr>'
        + '<th>Nota</th><th>Emissão</th><th>Fornecedor</th>'
        + '<th>Tipo de Operação</th>'
        + '<th class="text-end">Total dos Produtos</th>'
        + '<th class="text-end">Desconto</th>'
        + '<th class="text-end">Total da Nota</th>'
        + '</tr></thead>'
        + '<tbody>' + rows + '</tbody>'
        + '</table></div>';
}

// ── Render card itens mais caros ──────────────────────────────────────────
function renderItensMaisCaros(itens) {
    document.getElementById('itens-caros-badge').textContent =
        itens.length + ' itens · maior preço unitário pago no período';

    if (!itens.length) {
        document.getElementById('itens-caros-body').innerHTML =
            '<p class="text-center text-muted py-4">Nenhum item encontrado.</p>';
        return;
    }

    var rows = itens.map(function (r, i) {
        var marca = (r.MARCA || '').trim();
        var marcaHtml = marca
            ? '<span class="badge" style="background:#1e2a45;color:#60a5fa;font-weight:500;font-size:.78rem">'
              + esc(marca) + '</span>'
            : '<span class="text-muted small">—</span>';
        return '<tr>'
            + '<td class="text-muted small">' + (i + 1) + '</td>'
            + '<td>' + marcaHtml + '</td>'
            + '<td class="text-muted small" style="white-space:nowrap">' + esc(r.COD_ITEM || '—') + '</td>'
            + '<td class="small" style="max-width:260px">' + esc((r.ITEM || '—').substring(0, 60)) + '</td>'
            + '<td class="text-end fw-bold" style="color:#f472b6">' + fmtR(r.PRECO_MAX) + '</td>'
            + '<td class="text-end text-muted small">' + fmtR(r.PRECO_MEDIO) + '</td>'
            + '<td class="text-end small">' + fmtN(r.QTD_TOTAL, 0) + '</td>'
            + '<td class="text-end text-muted small">' + parseInt(r.QTD_NOTAS || 0) + '</td>'
            + '</tr>';
    }).join('');

    document.getElementById('itens-caros-body').innerHTML =
        '<div class="px-3 pt-3 pb-1">'
        + '<input type="text" id="filtro-itens-caros" class="form-control form-control-sm" '
        + 'style="max-width:320px;background:#0f1117;border-color:#2d3452;color:#e2e8f0" '
        + 'placeholder="🔍 Filtrar marca ou item…" oninput="filtrarItensMaisCaros(this.value)">'
        + '</div>'
        + '<div class="table-responsive">'
        + '<table class="pbi-table" id="tabela-itens-caros">'
        + '<thead><tr>'
        + '<th style="width:36px">#</th><th>Marca</th><th>Cód.</th><th>Item</th>'
        + '<th class="text-end">Preço Máx.</th><th class="text-end">Preço Médio</th>'
        + '<th class="text-end">Qtd. Comprada</th><th class="text-end">Notas</th>'
        + '</tr></thead>'
        + '<tbody>' + rows + '</tbody>'
        + '</table></div>';
}

// ── Exibe erro inline ─────────────────────────────────────────────────────
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>';
}

// ── Bootstrap: dispara 3 fetches em paralelo ao carregar o DOM ───────────
window.addEventListener('DOMContentLoaded', function () {
    // 1. KPIs (também retorna anos reais)
    apiFetch('/api/compras/kpis' + qs)
        .then(function (d) { renderKpis(d.kpis || {}, d.anos || []); })
        .catch(function (e) {
            showErr('kpi-grid', 'Erro ao carregar KPIs: ' + e.message);
        });

    // 2. Tabela de notas
    apiFetch('/api/compras/notas' + qs)
        .then(function (d) { renderNotas(d.notas || []); })
        .catch(function (e) {
            showErr('notas-body', 'Erro ao carregar notas: ' + e.message);
        });

    // 3. Itens mais caros
    apiFetch('/api/compras/itens-mais-caros' + qs)
        .then(function (d) { renderItensMaisCaros(d.itens || []); })
        .catch(function (e) {
            showErr('itens-caros-body', 'Erro ao carregar itens: ' + e.message);
        });
});

// ── Filtro de tabela de itens ─────────────────────────────────────────────
window.filtrarItensMaisCaros = function (q) {
    q = q.toLowerCase();
    document.querySelectorAll('#tabela-itens-caros tbody tr').forEach(function (tr) {
        tr.style.display = tr.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
};

})();
</script>
