<?php
/**
 * Estoque / Inventário — shell instantâneo.
 * KPIs e tabela carregados via fetch() depois do DOM pronto.
 */
$actionUrl = '/estoque/inventario';
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-clipboard-check me-2 text-accent"></i>Estoque</h1>
</div>
<?php include __DIR__ . '/_submenu.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 (legenda visual) ────────────────────────────── -->
<div class="pbi-card mb-3" style="background:#f8fafc">
    <div style="padding:.75rem 1.25rem">
        <div class="mb-2"><strong>📋 Como ler esta tela:</strong></div>
        <div class="row g-2" style="font-size:.85rem">
            <div class="col-md-6"><strong>Quantidade</strong> = quanto tem na prateleira/geladeira agora</div>
            <div class="col-md-6"><strong>Reservado</strong> = quanto já está prometido (pedido em aberto)</div>
            <div class="col-md-6"><strong>Custo Médio</strong> = preço médio que você paga pra comprar essa unidade</div>
            <div class="col-md-6"><strong>Custo Final</strong> = custo da última compra (mais recente)</div>
            <div class="col-md-6"><strong>Preço de Venda</strong> = por quanto você revende essa unidade</div>
            <div class="col-md-6"><strong>Valor a Custo</strong> = Quantidade × Custo Final (quanto vale o estoque atual no preço de compra)</div>
            <div class="col-md-6"><strong>Valor de Venda</strong> = Quantidade × Preço de Venda (quanto renderia se vendesse tudo)</div>
            <div class="col-md-6"><strong>Atualização</strong> = última vez que o estoque desse item foi alterado</div>
        </div>
        <hr class="my-2">
        <div class="d-flex flex-wrap gap-3" style="font-size:.85rem">
            <div><span class="badge" style="background:#fde68a;color:#7c2d12">linha amarela</span> <strong>Sem preço de venda</strong> — produto cadastrado mas não tem preço para vender (Pr. Venda = R$ 0)</div>
            <div><span class="badge" style="background:#e2e8f0;color:#475569">linha cinza</span> <strong>Sem custo cadastrado</strong> — comum em bar (drinks compostos por ingredientes)</div>
        </div>
    </div>
</div>

<!-- ── Tabela de Inventário (async) ──────────────────────────────────────── -->
<div class="pbi-card" id="card-inventario">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-clipboard-check me-2"></i>Inventário Completo</span>
        <small class="text-muted" id="inventario-badge">
            <span class="pbi-skeleton d-inline-block" style="width:80px;height:.75rem;border-radius:3px">&nbsp;</span>
        </small>
    </div>
    <div id="inventario-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 Médio</th>
                    <th class="text-end">Custo Final</th>
                    <th class="text-end">Pr. Venda</th>
                    <th class="text-end">Val. Custo</th>
                    <th class="text-end">Val. Venda</th>
                    <th>Atualização</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 8; $i++): ?>
                <tr>
                    <?php for ($j = 0; $j < 12; $j++): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= [28,70,140,38,50,55,70,70,70,80,80,60][$j] ?>px;height:.75rem;border-radius:3px">&nbsp;</span></td>
                    <?php endfor; ?>
                </tr>
                <?php endfor; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<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';

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(linhas) {
    var totalItens   = linhas.length;
    var comEstoque   = linhas.filter(function (r) { return parseFloat(r.QTD || 0) > 0; }).length;
    var semPreco     = linhas.filter(function (r) { return parseFloat(r.QTD || 0) > 0 && parseFloat(r.PRECO_VENDA || 0) <= 0; }).length;
    var totalCusto   = linhas.reduce(function (s, r) { return s + parseFloat(r.QTD || 0) * parseFloat(r.CUSTO_FINAL || 0); }, 0);
    var totalVenda   = linhas.reduce(function (s, r) { return s + parseFloat(r.QTD || 0) * parseFloat(r.PRECO_VENDA || 0); }, 0);
    var saldo        = totalVenda - totalCusto;
    var saldoCls     = saldo < 0 ? 'text-danger' : 'text-success';
    var saldoTitulo  = saldo < 0
        ? 'Atenção: o estoque atual ao preço de venda rende MENOS do que o custo. Geralmente significa produto sem preço de venda cadastrado.'
        : 'Lucro bruto potencial se vender todo o estoque atual.';

    var defs = [
        { label: 'Total de Itens cadastrados', val: fmtN(totalItens, 0),  cls: '',             titulo: 'Quantos itens diferentes existem no cadastro (com ou sem estoque).' },
        { label: 'Produtos em estoque',        val: fmtN(comEstoque, 0),  cls: 'text-success', titulo: 'Itens que têm quantidade maior que zero na prateleira.' },
        { label: 'Valor Total a Custo',        val: fmtR(totalCusto),     cls: '',             titulo: 'Quanto você pagou por tudo que está em estoque agora (Custo × Quantidade).' },
        { label: 'Valor Total de Venda',       val: fmtR(totalVenda),     cls: 'text-accent',  titulo: 'Quanto renderia se vendesse todo o estoque ao preço de venda cadastrado.' },
        { label: 'Saldo (Venda − Custo)',      val: fmtR(saldo),          cls: saldoCls,       titulo: saldoTitulo },
    ];
    if (semPreco > 0) {
        defs.push({ label: 'Sem preço de venda', val: fmtN(semPreco, 0), cls: 'text-warning', titulo: 'Produtos com estoque mas SEM preço de venda cadastrado — corrigir no ERP Fire Sistemas pra calcular faturamento corretamente.' });
    }

    var html = defs.map(function (d) {
        return '<div class="pbi-kpi-card" title="' + d.titulo + '" style="cursor:help">'
             + '<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;
}

function renderInventario(linhas) {
    document.getElementById('inventario-badge').textContent = linhas.length + ' itens';
    if (!linhas.length) {
        document.getElementById('inventario-body').innerHTML =
            '<p class="text-center text-muted py-4">Nenhum item encontrado.</p>';
        return;
    }
    var totalCusto = linhas.reduce(function (s, r) { return s + parseFloat(r.QTD || 0) * parseFloat(r.CUSTO_FINAL || 0); }, 0);
    var totalVenda = linhas.reduce(function (s, r) { return s + parseFloat(r.QTD || 0) * parseFloat(r.PRECO_VENDA || 0); }, 0);

    var rows = linhas.map(function (r, i) {
        var qtd       = parseFloat(r.QTD || 0);
        var preco     = parseFloat(r.PRECO_VENDA || 0);
        var custo     = parseFloat(r.CUSTO_FINAL || 0);
        var qtdCls    = qtd <= 0 ? 'text-muted' : '';
        var valC      = qtd * custo;
        var valV      = qtd * preco;
        var dtUpd     = r.DT_ATUALIZACAO ? fmtData(r.DT_ATUALIZACAO.substring(0, 10)) : '—';

        // Linha com problema (só pra itens que TÊM estoque)
        var trStyle = '';
        var trTitle = '';
        if (qtd > 0) {
            if (preco <= 0) {
                trStyle = 'background:#fef9c3';
                trTitle = 'title="Atenção: produto com estoque MAS sem preço de venda cadastrado no ERP Fire Sistemas."';
            } else if (custo <= 0) {
                trStyle = 'background:#f1f5f9';
                trTitle = 'title="Custo não cadastrado — comum em bar (drinks compostos). Margem do produto fica distorcida (aparece quase 100%)."';
            }
        }

        return '<tr style="' + trStyle + '" ' + trTitle + '>'
            + '<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 ' + qtdCls + '">' + fmtN(r.QTD || 0, 3) + '</td>'
            + '<td class="text-end text-muted">' + fmtN(r.QTD_RESERVADA || 0, 3) + '</td>'
            + '<td class="text-end">' + fmtR(r.CUSTO_MEDIO || 0) + '</td>'
            + '<td class="text-end">' + fmtR(custo) + '</td>'
            + '<td class="text-end">' + fmtR(preco) + '</td>'
            + '<td class="text-end">' + fmtR(valC) + '</td>'
            + '<td class="text-end text-accent">' + fmtR(valV) + '</td>'
            + '<td class="text-muted small">' + dtUpd + '</td>'
            + '</tr>';
    }).join('');

    var tfoot = '<tfoot>'
        + '<tr class="pbi-table-total">'
        + '<td colspan="9" class="text-end fw-bold">Total:</td>'
        + '<td class="text-end fw-bold">' + fmtR(totalCusto) + '</td>'
        + '<td class="text-end fw-bold text-accent">' + fmtR(totalVenda) + '</td>'
        + '<td></td>'
        + '</tr></tfoot>';

    document.getElementById('inventario-body').innerHTML =
        '<div class="table-responsive">'
        + '<table class="pbi-table">'
        + '<thead><tr>'
        + '<th>#</th><th>Código</th><th>Produto</th><th title="Unidade de medida (UND, CXA, KG, etc.)">Unidade</th>'
        + '<th class="text-end" title="Quantidade que tem na prateleira agora">Quantidade</th>'
        + '<th class="text-end" title="Quantidade já prometida em pedidos abertos">Reservado</th>'
        + '<th class="text-end" title="Preço médio que você paga por unidade ao comprar">Custo Médio</th>'
        + '<th class="text-end" title="Custo da última compra dessa unidade">Custo Final</th>'
        + '<th class="text-end" title="Por quanto você revende cada unidade">Preço de Venda</th>'
        + '<th class="text-end" title="Quantidade × Custo Final — quanto você pagou pelo estoque atual">Valor a Custo</th>'
        + '<th class="text-end" title="Quantidade × Preço de Venda — quanto renderia se vendesse tudo">Valor de Venda</th>'
        + '<th title="Última data em que o estoque desse item foi alterado">Atualização</th>'
        + '</tr></thead>'
        + '<tbody>' + rows + '</tbody>'
        + tfoot
        + '</table></div>';
}

window.addEventListener('DOMContentLoaded', function () {
    apiFetch('/api/estoque/inventario')
        .then(function (d) {
            var linhas = d.linhas || [];
            renderKpis(linhas);
            renderInventario(linhas);
        })
        .catch(function (e) {
            showErr('kpi-grid', 'Erro ao carregar inventário: ' + e.message);
            showErr('inventario-body', 'Erro ao carregar inventário: ' + e.message);
        });
});

})();
</script>
