<?php /* Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva */ ?>
<?php
/** Relatório de Vendas configurável. $lookups = listas para os selects. */
$lk = $lookups ?? [];
$opt = function (array $itens, string $codKey = 'COD', string $nomeKey = 'NOME') {
    $h = '';
    foreach ($itens as $i) {
        $cod = htmlspecialchars((string)($i[$codKey] ?? ''), ENT_QUOTES);
        $nom = htmlspecialchars((string)($i[$nomeKey] ?? $cod), ENT_QUOTES);
        $h .= "<option value=\"{$cod}\">{$nom}</option>";
    }
    return $h;
};
$hoje = date('Y-m-d'); $ini = date('Y-m-01');
?>
<div class="pbi-page-header">
    <div class="pbi-page-icon"><i class="bi bi-file-earmark-bar-graph"></i></div>
    <div>
        <div class="pbi-page-title">Relatório de Vendas</div>
        <div class="pbi-page-subtitle">Filtros completos · sintético e analítico · exportável</div>
    </div>
    <div class="ms-auto"><a href="/relatorios" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left"></i> Relatórios</a></div>
</div>

<!-- ── Filtros ───────────────────────────────────────────────────────────── -->
<div class="pbi-card mb-3">
    <div class="pbi-card-header"><i class="bi bi-funnel me-2"></i>Filtros</div>
    <div class="pbi-card-body">
        <div class="pbi-hint mb-3" style="margin-top:0">Preencha o que precisar e clique em <strong>Gerar</strong>. Campos vazios não filtram. O período é obrigatório.</div>
        <form id="relForm" onsubmit="return false">
            <div class="row g-2">
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Data por</label>
                    <select name="data_campo" class="form-select form-select-sm">
                        <option value="emissao">Emissão</option><option value="cancel">Cancelamento</option><option value="datahora">Data/Hora venda</option>
                    </select></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">De</label><input type="date" name="data_ini" value="<?= $ini ?>" class="form-control form-control-sm"></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Até</label><input type="date" name="data_fim" value="<?= $hoje ?>" class="form-control form-control-sm"></div>
                <div class="col-6 col-md-3"><label class="form-label small mb-1">Vendedor</label>
                    <select name="vendedor" class="form-select form-select-sm"><option value="">Todos</option><?= $opt($lk['vendedores'] ?? []) ?></select></div>
                <div class="col-6 col-md-3"><label class="form-label small mb-1">Usuário (operador)</label>
                    <select name="usuario" class="form-select form-select-sm"><option value="">Todos</option><?= $opt($lk['usuarios'] ?? []) ?></select></div>

                <div class="col-6 col-md-3"><label class="form-label small mb-1">Natureza</label>
                    <select name="naturezas" class="form-select form-select-sm"><option value="">Todas</option><?= $opt($lk['naturezas'] ?? []) ?></select></div>
                <div class="col-6 col-md-3"><label class="form-label small mb-1">Condição de pagamento</label>
                    <select name="cond" class="form-select form-select-sm"><option value="">Todas</option><?= $opt($lk['condicoes'] ?? []) ?></select></div>
                <div class="col-6 col-md-3"><label class="form-label small mb-1">Forma de pagamento</label>
                    <select name="forma" class="form-select form-select-sm"><option value="">Todas</option><?= $opt($lk['formas'] ?? []) ?></select></div>
                <div class="col-6 col-md-3"><label class="form-label small mb-1">Agente de vendas</label>
                    <select name="agente" class="form-select form-select-sm"><option value="">Todos</option><?= $opt($lk['agentes'] ?? []) ?></select></div>

                <div class="col-6 col-md-2"><label class="form-label small mb-1">Série</label>
                    <select name="serie" class="form-select form-select-sm"><option value="">Todas</option><?= $opt($lk['series'] ?? [], 'COD', 'COD') ?></select></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Nº Nota (de)</label><input type="number" name="nota_ini" class="form-control form-control-sm"></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Nº Nota (até)</label><input type="number" name="nota_fim" class="form-control form-control-sm"></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Cliente cód. (de)</label><input type="number" name="cli_ini" class="form-control form-control-sm"></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Cliente cód. (até)</label><input type="number" name="cli_fim" class="form-control form-control-sm"></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Canceladas</label>
                    <select name="canceladas" class="form-select form-select-sm"><option value="excluir">Excluir</option><option value="incluir">Incluir</option><option value="somente">Somente canceladas</option></select></div>
            </div>

            <hr class="my-3">
            <div class="pbi-hint mb-2" style="margin-top:0">Opções (marque o que quiser incluir no resultado):</div>
            <div class="row g-2">
                <?php
                $checks = [
                    ['custos','Mostrar custos / lucro / margem',0],
                    ['produtos','Detalhar por produto',0],
                    ['nfce','Somente NFCe',0],
                    ['nfe','Somente NFe',0],
                    ['so_servicos','Somente vendas de serviço',0],
                    ['so_promocao','Somente com itens em promoção',0],
                    ['so_gera_financeiro','Somente naturezas que geram financeiro',0],
                    ['ignora_naodre','Ignorar naturezas fora do DRE',0],
                    ['inc_mov_interna','Incluir movimentação interna',0],
                    ['inc_transferencias','Incluir transferências',0],
                    ['inc_devolucoes','Incluir devoluções',0],
                ];
                foreach ($checks as $c): ?>
                <div class="col-12 col-md-4 col-lg-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="<?= $c[0] ?>" id="chk_<?= $c[0] ?>" <?= $c[2] ? 'checked' : '' ?>>
                        <label class="form-check-label small" for="chk_<?= $c[0] ?>"><?= $c[1] ?></label>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="row g-2 mt-1 align-items-end">
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Ordenar por</label>
                    <select name="ordenar" class="form-select form-select-sm">
                        <option value="data">Data</option><option value="nota">Nº Nota</option><option value="cliente">Cliente</option><option value="vendedor">Vendedor</option><option value="valor">Maior valor</option>
                    </select></div>
                <div class="col-6 col-md-2"><label class="form-label small mb-1">Máx. notas</label>
                    <select name="limite" class="form-select form-select-sm"><option>500</option><option selected>1000</option><option>2000</option><option>5000</option></select></div>
                <div class="col-12 col-md-8 d-flex gap-2 justify-content-md-end">
                    <button class="btn btn-primary btn-sm" id="btnGerar"><i class="bi bi-search me-1"></i>Gerar relatório</button>
                    <button class="btn btn-outline-secondary btn-sm" id="btnCsv" disabled><i class="bi bi-filetype-csv"></i> CSV</button>
                    <button class="btn btn-outline-secondary btn-sm" id="btnPrint" disabled><i class="bi bi-printer"></i></button>
                </div>
            </div>
        </form>
    </div>
</div>

<div id="rel-status" class="pbi-hint mb-3" style="margin-top:0;display:none"></div>

<script type="application/json" id="relatorio-meta"><?= json_encode([
    'titulo'  => 'Relatório Avançado de Vendas',
    'empresa' => $empresa ?? '',
    'totais'  => [],
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?></script>

<!-- ── Resumo (KPIs) ─────────────────────────────────────────────────────── -->
<div class="pbi-kpi-grid mb-3" id="rel-kpis" style="display:none" data-export-secao="kpis"></div>

<!-- ── Sintético ─────────────────────────────────────────────────────────── -->
<div class="row g-3 mb-3" id="rel-sintetico" style="display:none">
    <div class="col-12 col-lg-3"><div class="pbi-card h-100"><div class="pbi-card-header"><i class="bi bi-person-badge me-2"></i>Por Vendedor</div><div class="pbi-card-body"><div id="rel-vend"></div></div></div></div>
    <div class="col-12 col-lg-3"><div class="pbi-card h-100"><div class="pbi-card-header"><i class="bi bi-tags me-2"></i>Por Natureza</div><div class="pbi-card-body"><div id="rel-nat"></div></div></div></div>
    <div class="col-12 col-lg-3"><div class="pbi-card h-100"><div class="pbi-card-header"><i class="bi bi-receipt me-2"></i>Por Série</div><div class="pbi-card-body"><div class="pbi-hint mb-2" style="margin-top:0">NFCe = cupom; NFe = nota; SN = sem nota.</div><div id="rel-serie"></div></div></div></div>
    <div class="col-12 col-lg-3"><div class="pbi-card h-100"><div class="pbi-card-header"><i class="bi bi-wallet2 me-2"></i>Por Forma de Pgto</div><div class="pbi-card-body"><div id="rel-forma"></div></div></div></div>
</div>

<!-- ── Analítico: produtos ───────────────────────────────────────────────── -->
<div class="pbi-card mb-3" id="rel-card-produtos" style="display:none">
    <div class="pbi-card-header"><i class="bi bi-box-seam me-2"></i>Produtos Vendidos</div>
    <div class="pbi-card-body"><div class="pbi-hint mb-2" style="margin-top:0">Itens vendidos no filtro, somados por produto.</div><div id="rel-produtos"></div></div>
</div>

<!-- ── Analítico: notas ──────────────────────────────────────────────────── -->
<div class="pbi-card" id="rel-card-notas" style="display:none" data-export-secao="dados">
    <div class="pbi-card-header d-flex justify-content-between flex-wrap"><span><i class="bi bi-table me-2"></i>Notas (analítico)</span><small class="text-muted" id="rel-notas-badge"></small></div>
    <div class="pbi-card-body"><div id="rel-notas"></div></div>
</div>

<script src="/assets/js/echarts.min.js"></script>
<script>
(function () {
'use strict';
var ST = { dados: null };

function brl(v){ return 'R$ '+parseFloat(v||0).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2}); }
function n0(v){ return parseInt(v||0).toLocaleString('pt-BR'); }
function pct(v){ return parseFloat(v||0).toFixed(1).replace('.',',')+'%'; }
function esc(s){ var d=document.createElement('div'); d.textContent=s==null?'':String(s); return d.innerHTML; }
function status(msg, tipo){ var el=document.getElementById('rel-status'); el.style.display='block'; el.innerHTML=(tipo==='erro'?'<i class="bi bi-exclamation-triangle text-danger me-1"></i>':'<i class="bi bi-info-circle me-1"></i>')+esc(msg); }

function filtros(){
    var f=document.getElementById('relForm');
    var p=new URLSearchParams();
    Array.prototype.forEach.call(f.elements, function(el){
        if(!el.name) return;
        if(el.type==='checkbox'){ if(el.checked) p.set(el.name,'1'); }
        else if(el.value!=='') p.set(el.name, el.value);
    });
    return p.toString();
}

function tabela(itens, cols){
    if(!itens || !itens.length) return '<div class="text-muted small py-2">Sem dados.</div>';
    var th=cols.map(function(c){return '<th'+(c.end?' class="text-end"':'')+'>'+esc(c.lbl)+'</th>';}).join('');
    var tr=itens.map(function(r){
        return '<tr>'+cols.map(function(c){ var v=c.fmt?c.fmt(r[c.k],r):esc(r[c.k]); return '<td'+(c.end?' class="text-end"':'')+(c.cls?' class="'+c.cls+'"':'')+'>'+v+'</td>'; }).join('')+'</tr>';
    }).join('');
    return '<div class="table-responsive"><table class="pbi-table"><thead><tr>'+th+'</tr></thead><tbody>'+tr+'</tbody></table></div>';
}

function render(d){
    ST.dados=d;
    var r=d.resumo||{}, tem=parseInt(r.QTD||0)>0;
    var custos = document.getElementById('chk_custos').checked;
    var temProd = document.getElementById('chk_produtos').checked;

    // KPIs
    var fat=parseFloat(r.TOTAL||0), custo=d.custo_total, lucro=(custo!=null)?fat-custo:null, marg=(lucro!=null&&fat>0)?lucro/fat*100:null;
    var kpis=[
        {l:'Notas', v:n0(r.QTD)}, {l:'Faturamento', v:brl(r.TOTAL), c:'text-accent'},
        {l:'Produtos', v:brl(r.PRODUTOS)}, {l:'Descontos', v:brl(r.DESCONTOS)},
        {l:'Serviços', v:brl(r.SERVICOS)}, {l:'ICMS', v:brl(r.ICMS)}
    ];
    if(custos && custo!=null){ kpis.push({l:'CMV (custo)',v:brl(custo)}); kpis.push({l:'Lucro Bruto',v:brl(lucro),c:'text-success'}); kpis.push({l:'Margem',v:pct(marg)}); }
    var gk=document.getElementById('rel-kpis');
    gk.innerHTML=kpis.map(function(k){return '<div class="pbi-kpi-card"><div class="pbi-kpi-label">'+k.l+'</div><div class="pbi-kpi-value '+(k.c||'')+'">'+k.v+'</div></div>';}).join('');
    gk.style.display = tem ? '' : 'none';

    // Sintético
    document.getElementById('rel-sintetico').style.display = tem ? '' : 'none';
    var fmtTot=function(v){return brl(v);}, fmtQ=function(v){return n0(v);};
    document.getElementById('rel-vend').innerHTML  = tabela(d.por_vendedor, [{k:'NOME',lbl:'Vendedor'},{k:'QTD',lbl:'Notas',end:1,fmt:fmtQ},{k:'TOTAL',lbl:'Total',end:1,fmt:fmtTot}]);
    document.getElementById('rel-nat').innerHTML   = tabela(d.por_natureza, [{k:'NOME',lbl:'Natureza'},{k:'QTD',lbl:'Qtd',end:1,fmt:fmtQ},{k:'TOTAL',lbl:'Total',end:1,fmt:fmtTot}]);
    document.getElementById('rel-serie').innerHTML = tabela(d.por_serie,   [{k:'NOME',lbl:'Série'},{k:'QTD',lbl:'Qtd',end:1,fmt:fmtQ},{k:'TOTAL',lbl:'Total',end:1,fmt:fmtTot}]);
    document.getElementById('rel-forma').innerHTML = tabela(d.por_forma,   [{k:'NOME',lbl:'Forma'},{k:'TOTAL',lbl:'Total',end:1,fmt:fmtTot}]);

    // Produtos
    var cp=document.getElementById('rel-card-produtos');
    if(temProd && d.produtos && d.produtos.length){
        cp.style.display='';
        document.getElementById('rel-produtos').innerHTML = tabela(d.produtos, [
            {k:'COD_ITEM',lbl:'Cód.'},{k:'DESCRICAO',lbl:'Produto'},{k:'QTD',lbl:'Qtd',end:1,fmt:function(v){return parseFloat(v||0).toLocaleString('pt-BR');}},
            {k:'TOTAL',lbl:'Faturamento',end:1,fmt:fmtTot},{k:'CUSTO',lbl:'Custo',end:1,fmt:fmtTot},
            {k:'_m',lbl:'Margem',end:1,fmt:function(_,row){var t=parseFloat(row.TOTAL||0),c=parseFloat(row.CUSTO||0);return t>0?pct((t-c)/t*100):'—';}}
        ]);
    } else cp.style.display='none';

    // Notas (analítico)
    document.getElementById('rel-card-notas').style.display = tem ? '' : 'none';
    document.getElementById('rel-notas-badge').textContent = n0((d.notas||[]).length)+' notas'+(d.capado?(' (limitado a '+d.limite+')'):'');
    var colsN=[
        {k:'NR_NOTA',lbl:'Nota'},{k:'SERIE',lbl:'Série'},{k:'DATA_REF',lbl:'Data',fmt:function(v){return v?String(v).split('-').reverse().join('/'):'';}},
        {k:'CLIENTE',lbl:'Cliente'},{k:'VENDEDOR',lbl:'Vendedor'},{k:'OPERACAO',lbl:'Operação'},
        {k:'DESCONTO',lbl:'Desc.',end:1,fmt:fmtTot},{k:'TOTAL_NOTA',lbl:'Total',end:1,fmt:fmtTot,cls:'text-end fw-semibold'}
    ];
    if(custos) colsN.push({k:'CUSTO',lbl:'Custo',end:1,fmt:fmtTot},{k:'_l',lbl:'Lucro',end:1,fmt:function(_,row){return brl(parseFloat(row.TOTAL_NOTA||0)-parseFloat(row.CUSTO||0));}});
    document.getElementById('rel-notas').innerHTML = tabela(d.notas, colsN);

    if(!tem) status('Nenhuma venda encontrada com esses filtros.','info');
    else { document.getElementById('rel-status').style.display='none'; }
    document.getElementById('btnCsv').disabled=!tem;
    document.getElementById('btnPrint').disabled=!tem;
}

function gerar(){
    var btn=document.getElementById('btnGerar'); btn.disabled=true; var ico=btn.querySelector('i'); var old=ico?ico.className:'';
    if(ico) ico.className='spinner-border spinner-border-sm me-1';
    status('Gerando relatório… (custos/produtos podem levar alguns segundos)','info');
    fetch('/api/relatorios/vendas-avancado?'+filtros(),{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(); })
        .then(function(d){ render(d); })
        .catch(function(e){ status('Erro ao gerar: '+e.message,'erro'); })
        .finally(function(){ btn.disabled=false; if(ico) ico.className=old; });
}

function csv(){
    var d=ST.dados; if(!d) return;
    var custos=document.getElementById('chk_custos').checked;
    var head=['Nota','Serie','Data','Cliente','Vendedor','Operacao','Desconto','Total'];
    if(custos) head.push('Custo','Lucro');
    var nz=function(v){return String(parseFloat(v||0).toFixed(2)).replace('.',',');};
    var linhas=[head.join(';')];
    (d.notas||[]).forEach(function(r){
        var row=[r.NR_NOTA,r.SERIE,r.DATA_REF,'"'+String(r.CLIENTE||'').replace(/"/g,'""')+'"','"'+String(r.VENDEDOR||'').replace(/"/g,'""')+'"','"'+String(r.OPERACAO||'').replace(/"/g,'""')+'"',nz(r.DESCONTO),nz(r.TOTAL_NOTA)];
        if(custos) row.push(nz(r.CUSTO), nz(parseFloat(r.TOTAL_NOTA||0)-parseFloat(r.CUSTO||0)));
        linhas.push(row.join(';'));
    });
    var blob=new Blob(["﻿"+linhas.join('\r\n')],{type:'text/csv;charset=utf-8'});
    var a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='relatorio-vendas.csv'; document.body.appendChild(a); a.click(); document.body.removeChild(a);
}

function fillSelect(name, itens, codKey, nomeKey){
    var sel=document.querySelector('[name="'+name+'"]'); if(!sel || !itens) return;
    var first=sel.options[0];
    sel.innerHTML=''; sel.appendChild(first);
    itens.forEach(function(i){ var o=document.createElement('option'); o.value=i[codKey]; o.textContent=i[nomeKey]!=null?i[nomeKey]:i[codKey]; sel.appendChild(o); });
}
function carregarLookups(){
    fetch('/api/relatorios/vendas-avancado/lookups',{credentials:'same-origin'})
        .then(function(r){ return r.json(); })
        .then(function(d){
            if(!d || d.erro) return;
            fillSelect('vendedor', d.vendedores, 'COD','NOME');
            fillSelect('usuario',  d.usuarios,   'COD','NOME');
            fillSelect('naturezas',d.naturezas,  'COD','NOME');
            fillSelect('cond',     d.condicoes,  'COD','NOME');
            fillSelect('forma',    d.formas,     'COD','NOME');
            fillSelect('agente',   d.agentes,    'COD','NOME');
            fillSelect('serie',    d.series,     'COD','COD');
        }).catch(function(){});
}

document.getElementById('btnGerar').addEventListener('click', gerar);
document.getElementById('btnCsv').addEventListener('click', csv);
document.getElementById('btnPrint').addEventListener('click', function(){ window.print(); });
// Abre instantâneo: gera o mês atual e carrega os filtros em paralelo
window.addEventListener('DOMContentLoaded', function(){ gerar(); carregarLookups(); });
})();
</script>
