<?php
// Depto de Engenharia e Automacao - Master Automacao - Autor: Derlivon Silva
// Produtos / Mais Vendidos (Qtd + Faturamento) + Margem Negativa
$actionUrl = '/produtos/ranking';
?>
<div class="pbi-page-header">
    <div class="pbi-page-icon"><i class="bi bi-trophy"></i></div>
    <div>
        <div class="pbi-page-title">Mais Vendidos &amp; Margem Negativa</div>
        <div class="pbi-page-subtitle">Top produtos por quantidade vendida e por faturamento — e produtos vendendo abaixo do custo no período</div>
    </div>
</div>
<?php if (file_exists(__DIR__ . '/_submenu.php')) include __DIR__ . '/_submenu.php'; ?>
<?php if (file_exists(__DIR__ . '/_filtro.php')) include __DIR__ . '/_filtro.php'; ?>

<div class="row g-3">
    <div class="col-12 col-xl-6">
        <div class="pbi-card h-100">
            <div class="pbi-card-header d-flex justify-content-between flex-wrap">
                <span><i class="bi bi-stack me-2"></i>Top Produtos por <strong>Quantidade</strong> vendida</span>
                <small class="text-muted" id="qtd-badge">—</small>
            </div>
            <div class="pbi-card-body">
                <div id="qtd-tabela"><div class="text-center py-4"><div class="spinner-border text-accent"></div></div></div>
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-6">
        <div class="pbi-card h-100">
            <div class="pbi-card-header d-flex justify-content-between flex-wrap">
                <span><i class="bi bi-cash-coin me-2"></i>Top Produtos por <strong>Faturamento</strong></span>
                <small class="text-muted" id="fat-badge">—</small>
            </div>
            <div class="pbi-card-body">
                <div id="fat-tabela"><div class="text-center py-4"><div class="spinner-border text-accent"></div></div></div>
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="pbi-card">
            <div class="pbi-card-header d-flex justify-content-between flex-wrap">
                <span><i class="bi bi-exclamation-triangle-fill me-2" style="color:#ef4444"></i>Produtos com <strong>Margem Negativa</strong> no período</span>
                <small class="text-muted" id="margem-badge">—</small>
            </div>
            <div class="pbi-card-body">
                <div class="pbi-hint mb-2" style="margin-top:0">
                    Lista produtos onde o <strong>preço médio de venda</strong> no período ficou abaixo do <strong>custo do cadastro</strong> — você perdeu dinheiro em cada unidade vendida. Ordenado pelo maior prejuízo total. Considera apenas produtos com custo > 0 cadastrado.
                </div>
                <div id="margem-tabela"><div class="text-center py-4"><div class="spinner-border text-accent"></div></div></div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
'use strict';
var FILTROS = {
    ini: <?= json_encode($filtros['dataIni'] ?? date('Y-01-01')) ?>,
    fim: <?= json_encode($filtros['dataFim'] ?? date('Y-m-d')) ?>
};

function brl(v) {
    if (v === null || v === undefined || isNaN(+v)) return '—';
    return (+v).toLocaleString('pt-BR', {style:'currency',currency:'BRL'});
}
function num(v) {
    if (v === null || v === undefined || isNaN(+v)) return '—';
    return (+v).toLocaleString('pt-BR', {minimumFractionDigits: 0, maximumFractionDigits: 2});
}
function esc(s) { return String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }

function tabelaTop(rows, colValor, fnFmt, labelValor) {
    if (!rows || !rows.length) return '<div class="text-center text-muted py-4">Sem dados no período.</div>';
    var html = '<div class="table-responsive"><table class="table table-sm table-hover mb-0 pbi-table">';
    html += '<thead><tr><th style="width:40px">#</th><th>Produto</th><th class="text-end" style="width:120px">Qtd</th><th class="text-end" style="width:140px">' + labelValor + '</th></tr></thead><tbody>';
    rows.forEach(function (r, i) {
        html += '<tr><td class="text-muted">' + (i+1) + '</td><td>' + esc(r.DESCRICAO) +
                '</td><td class="text-end">' + num(r.QTD_TOTAL) +
                '</td><td class="text-end fw-semibold">' + fnFmt(r[colValor]) + '</td></tr>';
    });
    html += '</tbody></table></div>';
    return html;
}

function tabelaMargem(rows) {
    if (!rows || !rows.length) return '<div class="text-center text-success py-4"><i class="bi bi-check-circle-fill me-2"></i>Nenhum produto vendendo abaixo do custo no período.</div>';
    var html = '<div class="table-responsive"><table class="table table-sm table-hover mb-0 pbi-table">';
    html += '<thead><tr>' +
            '<th style="width:40px">#</th>' +
            '<th>Produto</th>' +
            '<th class="text-end" style="width:90px">Qtd</th>' +
            '<th class="text-end" style="width:120px">Preço médio</th>' +
            '<th class="text-end" style="width:120px">Custo</th>' +
            '<th class="text-end" style="width:130px">Margem/un</th>' +
            '<th class="text-end" style="width:150px">Prejuízo total</th>' +
            '</tr></thead><tbody>';
    rows.forEach(function (r, i) {
        html += '<tr>' +
                '<td class="text-muted">' + (i+1) + '</td>' +
                '<td>' + esc(r.DESCRICAO) + '</td>' +
                '<td class="text-end">' + num(r.QTD_VENDIDA) + '</td>' +
                '<td class="text-end">' + brl(r.PRECO_MEDIO) + '</td>' +
                '<td class="text-end">' + brl(r.CUSTO_UNIT) + '</td>' +
                '<td class="text-end" style="color:#ef4444">' + brl(r.MARGEM_UNIT) + '</td>' +
                '<td class="text-end fw-semibold" style="color:#ef4444">' + brl(r.LUCRO_PERIODO) + '</td>' +
                '</tr>';
    });
    html += '</tbody></table></div>';
    return html;
}

function carregar(url, alvoId, badgeId, render) {
    var qs = '?data_ini=' + encodeURIComponent(FILTROS.ini) + '&data_fim=' + encodeURIComponent(FILTROS.fim);
    fetch(url + qs).then(function (r) { return r.json(); })
    .then(function (j) {
        if (!j.ok) throw new Error(j.erro || 'erro');
        document.getElementById(alvoId).innerHTML = render(j.rows);
        document.getElementById(badgeId).textContent = (j.rows || []).length + ' produtos';
    })
    .catch(function (e) {
        document.getElementById(alvoId).innerHTML = '<div class="alert alert-danger">Erro: ' + esc(e.message) + '</div>';
    });
}

carregar('/api/produtos/top-qtd',         'qtd-tabela',    'qtd-badge',    function (rows) { return tabelaTop(rows, 'FATURAMENTO', brl, 'Faturamento'); });
carregar('/api/produtos/top-fat',         'fat-tabela',    'fat-badge',    function (rows) { return tabelaTop(rows, 'FATURAMENTO', brl, 'Faturamento'); });
carregar('/api/produtos/margem-negativa', 'margem-tabela', 'margem-badge', tabelaMargem);
})();
</script>
