<?php
// Depto de Engenharia e Automacao - Master Automacao - Autor: Derlivon Silva
?>
<div class="pbi-page-header">
    <div class="pbi-page-icon"><i class="bi bi-people-fill"></i></div>
    <div>
        <div class="pbi-page-title">Top Conveniados</div>
        <div class="pbi-page-subtitle">Pessoas que mais consumiram via convênio no período</div>
    </div>
    <div class="ms-auto"><button class="btn btn-sm btn-outline-secondary" onclick="window.print()"><i class="bi bi-printer"></i> Imprimir / PDF</button></div>
</div>
<?php if (file_exists(__DIR__ . '/_submenu.php')) include __DIR__ . '/_submenu.php'; ?>
<?php if (file_exists(__DIR__ . '/../produtos/_filtro.php')) { $actionUrl='/convenios/top-conveniados'; include __DIR__ . '/../produtos/_filtro.php'; } ?>

<div class="pbi-card">
    <div class="pbi-card-header d-flex justify-content-between flex-wrap">
        <span><i class="bi bi-trophy me-2"></i>Ranking por total comprado via convênio</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-m-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');}
function esc(s){return String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
function fmtData(s){if(!s)return'—';return String(s).substring(8,10)+'/'+String(s).substring(5,7)+'/'+String(s).substring(0,4);}

fetch('/api/convenios/top-conveniados?data_ini='+encodeURIComponent(INI)+'&data_fim='+encodeURIComponent(FIM)+'&limite=100')
.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+' conveniado(s)';
    if(!rows.length){
        document.getElementById('tabela').innerHTML = '<div class="text-center text-muted py-4">Nenhuma compra via convênio 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>Conveniado</th>'
      + '<th>Convênio</th>'
      + '<th class="text-end">Compras</th>'
      + '<th class="text-end">Total comprado</th>'
      + '<th class="text-end">Em aberto</th>'
      + '<th class="text-end">Última</th>'
      + '</tr></thead><tbody>';
    rows.forEach((r,i)=>{
        h += '<tr>'
          + '<td class="text-muted">'+(i+1)+'</td>'
          + '<td><strong>'+esc(r.NOME)+'</strong>'
          + (r.FONE_PRINC?'<div class="text-muted small"><i class="bi bi-telephone me-1"></i>'+esc(r.FONE_PRINC)+'</div>':'')+'</td>'
          + '<td><span class="badge bg-primary-subtle text-primary">'+esc(r.CONVENIO||'—')+'</span></td>'
          + '<td class="text-end">'+num(r.QTD_COMPRAS)+'</td>'
          + '<td class="text-end fw-semibold">'+brl(r.TOTAL_COMPRADO)+'</td>'
          + '<td class="text-end" style="color:'+((+r.TOTAL_EM_ABERTO||0)>0?'#ef4444':'inherit')+'">'+brl(r.TOTAL_EM_ABERTO)+'</td>'
          + '<td class="text-end small text-muted">'+fmtData(r.ULTIMA_COMPRA)+'</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>
