<?php
// Depto de Engenharia e Automacao - Master Automacao - Autor: Derlivon Silva
$actionUrl = '/produtos/top-quantidade';
?>
<div class="pbi-page-header">
    <div class="pbi-page-icon"><i class="bi bi-stack"></i></div>
    <div>
        <div class="pbi-page-title">Top por Quantidade</div>
        <div class="pbi-page-subtitle">Produtos com maior quantidade vendida 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="pbi-card">
    <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="badge">—</small>
    </div>
    <div class="pbi-card-body">
        <div id="tabela"><div class="text-center py-4"><div class="spinner-border text-accent"></div></div></div>
    </div>
</div>

<script>
(function () {
'use strict';
var INI = <?= json_encode($filtros['dataIni'] ?? date('Y-01-01')) ?>;
var FIM = <?= json_encode($filtros['dataFim'] ?? date('Y-m-d')) ?>;
function brl(v){return (v==null||isNaN(+v))?'—':(+v).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});}
function num(v){return (v==null||isNaN(+v))?'—':(+v).toLocaleString('pt-BR',{minimumFractionDigits:0,maximumFractionDigits:2});}
function esc(s){return String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}

fetch('/api/produtos/top-qtd?data_ini='+encodeURIComponent(INI)+'&data_fim='+encodeURIComponent(FIM)+'&limite=50')
.then(r=>r.json()).then(j=>{
    if(!j.ok) throw new Error(j.erro||'erro');
    var rows = j.rows||[];
    document.getElementById('badge').textContent = rows.length+' produtos';
    if(!rows.length){
        document.getElementById('tabela').innerHTML = '<div class="text-center text-muted py-4">Sem dados no período.</div>';
        return;
    }
    var h = '<div class="table-responsive"><table class="table table-sm table-hover mb-0 pbi-table">';
    h += '<thead><tr><th style="width:40px">#</th><th>Produto</th><th class="text-end" style="width:140px">Qtd vendida</th><th class="text-end" style="width:140px">Faturamento</th></tr></thead><tbody>';
    rows.forEach((r,i)=>{
        h += '<tr><td class="text-muted">'+(i+1)+'</td><td>'+esc(r.DESCRICAO)+'</td><td class="text-end fw-semibold">'+num(r.QTD_TOTAL)+'</td><td class="text-end">'+brl(r.FATURAMENTO)+'</td></tr>';
    });
    h += '</tbody></table></div>';
    document.getElementById('tabela').innerHTML = h;
}).catch(e=>{
    document.getElementById('tabela').innerHTML = '<div class="alert alert-danger">Erro: '+esc(e.message)+'</div>';
});
})();
</script>
