<?php
/**
 * Estoque / Posição — shell instantâneo.
 * KPIs e tabela carregados via fetch() depois do DOM pronto.
 * TTFB = tempo de render PHP (<10ms), sem nenhuma query Firebird aqui.
 */
$actionUrl = '/estoque/posicao';
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-boxes me-2 text-accent"></i>Estoque</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"><strong>Valor ao Custo</strong> = quanto você pagou pelo estoque parado. <strong>Valor de Venda</strong> = quanto ele vale se vender tudo. <strong>Zerados</strong> = itens sem nenhuma unidade.</div>

<!-- ── Tabela de Posição de Estoque (async) ──────────────────────────────── -->
<div class="pbi-card" id="card-posicao">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-boxes me-2"></i>Posição de Estoque</span>
        <small class="text-muted" id="posicao-badge">
            <span class="pbi-skeleton d-inline-block" style="width:80px;height:.75rem;border-radius:3px">&nbsp;</span>
        </small>
        <div class="pbi-hint mb-2" style="margin-top:0">Lista o que você tem em estoque agora: quanto tem de cada produto e quanto vale. Ordenado do mais valioso para o menos.</div>
    </div>
    <div id="posicao-body">
        <div class="table-responsive">
            <table class="pbi-table">
                <thead><tr>
                    <th>#</th><th>Código</th><th>Produto</th><th>Un</th>
                    <th class="text-end">Qtd</th>
                    <th class="text-end">Reservado</th>
                    <th class="text-end">Custo</th>
                    <th class="text-end">Pr. Venda</th>
                    <th class="text-end">Valor Est.</th>
                    <th>Atualização</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 8; $i++): ?>
                <tr>
                    <?php for ($j = 0; $j < 10; $j++): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= [28,70,160,38,55,55,70,70,80,65][$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.__ESTOQUE = {
    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.__ESTOQUE.dataIni;
var fim = window.__ESTOQUE.dataFim;
var qs  = '?data_ini=' + encodeURIComponent(ini) + '&data_fim=' + encodeURIComponent(fim);

function fmtR(v) {
    return 'R$ ' + parseFloat(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function fmtN(v, d) {
    d = d === undefined ? 2 : d;
    return parseFloat(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: d, maximumFractionDigits: d });
}
function fmtData(s) {
    if (!s) return '—';
    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();
        });
}
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 defs = [
        { label: 'Total de Itens',   val: fmtN(kpis.TOTAL_ITENS || 0, 0),    cls: '',             href: '/estoque/posicao' },
        { label: 'Com Estoque',      val: fmtN(kpis.ITENS_POSITIVO || 0, 0), cls: 'text-success', href: '/estoque/inventario' },
        { label: 'Zerados',          val: fmtN(kpis.ITENS_ZERADO || 0, 0),   cls: 'text-warning', href: '/estoque/minimos' },
        { label: 'Valor ao Custo',   val: fmtR(kpis.VALOR_CUSTO || 0),       cls: '',             href: '/estoque/margem' },
        { label: 'Valor de Venda',   val: fmtR(kpis.VALOR_VENDA || 0),       cls: 'text-accent',  href: '/estoque/giro' },
    ];
    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>'
             + '</a>';
    }).join('');
    document.getElementById('kpi-grid').innerHTML = html;
}

function renderPosicao(linhas) {
    document.getElementById('posicao-badge').textContent = linhas.length + ' itens';
    if (!linhas.length) {
        document.getElementById('posicao-body').innerHTML =
            '<p class="text-center text-muted py-4">Nenhum produto encontrado.</p>';
        return;
    }
    var rows = linhas.map(function (r, i) {
        var qtd      = parseFloat(r.QTD || 0);
        var qtdCls   = qtd <= 0 ? 'text-danger' : '';
        var valEst   = qtd * parseFloat(r.PRECO_VENDA || 0);
        var dtUpd    = r.DT_ATUALIZACAO ? fmtData(r.DT_ATUALIZACAO.substring(0, 10)) : '—';
        return '<tr>'
            + '<td class="text-muted">' + (i + 1) + '</td>'
            + '<td class="fw-semibold">' + esc(r.COD_ITEM || '') + '</td>'
            + '<td>' + esc(r.DESCRICAO || '') + '</td>'
            + '<td><span class="badge bg-secondary">' + esc(r.COD_UNIDADE || '-') + '</span></td>'
            + '<td class="text-end fw-bold ' + qtdCls + '">' + fmtN(r.QTD, 3) + '</td>'
            + '<td class="text-end text-muted">' + fmtN(r.QTD_RESERVADA || 0, 3) + '</td>'
            + '<td class="text-end">' + fmtR(r.CUSTO_FINAL || 0) + '</td>'
            + '<td class="text-end">' + fmtR(r.PRECO_VENDA || 0) + '</td>'
            + '<td class="text-end text-accent">' + fmtR(valEst) + '</td>'
            + '<td class="text-muted small">' + dtUpd + '</td>'
            + '</tr>';
    }).join('');

    document.getElementById('posicao-body').innerHTML =
        '<div class="table-responsive">'
        + '<table class="pbi-table">'
        + '<thead><tr>'
        + '<th>#</th><th>Código</th><th>Produto</th><th>Un</th>'
        + '<th class="text-end">Qtd</th>'
        + '<th class="text-end">Reservado</th>'
        + '<th class="text-end">Custo</th>'
        + '<th class="text-end">Pr. Venda</th>'
        + '<th class="text-end">Valor Est.</th>'
        + '<th>Atualização</th>'
        + '</tr></thead>'
        + '<tbody>' + rows + '</tbody>'
        + '</table></div>';
}

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

    apiFetch('/api/estoque/posicao' + qs)
        .then(function (d) { renderPosicao(d.linhas || []); })
        .catch(function (e) { showErr('posicao-body', 'Erro ao carregar posição: ' + e.message); });
});

})();
</script>
