<?php /* Vendas > Comissões: UI completa (filtros, geração, painéis, exportação) */ ?>
<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;gap:1rem;">
  <div>
    <h1>Comissões de Vendas</h1>
    <p class="muted" id="statusText" aria-live="polite">Selecione filtros e gere comissões.</p>
  </div>
  <div>
    <a href="/dashboard" class="btn btn-secondary">Voltar</a>
  </div>
  
</div>

<div class="card" aria-labelledby="filtersTitle">
  <h2 id="filtersTitle" style="margin-top:0;">Filtros e Apuração</h2>
  <form id="filtersForm" aria-describedby="filtersDesc" style="display:grid;grid-template-columns:repeat(3,minmax(220px,1fr));gap:0.75rem;align-items:end;">
    <div>
      <label for="sellerSelect">Vendedores</label>
      <select id="sellerSelect" multiple size="4" aria-label="Selecione vendedores"></select>
    </div>
    <div>
      <label for="empresaSelect">Empresas</label>
      <select id="empresaSelect" multiple size="4" aria-label="Selecione empresas"></select>
    </div>
    <div>
      <label for="periodType">Período</label>
      <select id="periodType">
        <option value="mensal">Mensal</option>
        <option value="quinzenal">Quinzenal</option>
        <option value="semanal">Semanal</option>
      </select>
      <div style="display:flex;gap:0.5rem;margin-top:0.5rem;">
        <div>
          <label for="startDate">Início</label>
          <input type="date" id="startDate" />
        </div>
        <div>
          <label for="endDate">Fim</label>
          <input type="date" id="endDate" />
        </div>
      </div>
    </div>
    <div style="grid-column:1 / -1;display:flex;gap:0.5rem;margin-top:0.5rem;">
      <button type="button" id="btnAplicar" class="btn">Aplicar</button>
      <button type="button" id="btnGerar" class="btn btn-primary">Gerar comissões</button>
      <button type="button" id="btnCsv" class="btn btn-secondary">Exportar CSV</button>
      <button type="button" id="btnXlsx" class="btn btn-secondary">Exportar Excel</button>
      <button type="button" id="btnPdf" class="btn btn-secondary">Exportar PDF</button>
    </div>
    <p id="filtersDesc" class="muted" style="grid-column:1 / -1;margin:0;">Os filtros por empresa são aplicados quando suportados pelas tabelas.</p>
  </form>
</div>

<div class="card" style="margin-top:1rem;" aria-labelledby="kpisTitle">
  <h2 id="kpisTitle" style="margin-top:0;">KPIs</h2>
  <div style="display:grid;grid-template-columns:repeat(3,minmax(200px,1fr));gap:0.75rem;">
    <div class="kpi"><div class="kpi-label">Receita Total</div><div class="kpi-value" id="kpiRevenue">R$ 0,00</div></div>
    <div class="kpi"><div class="kpi-label">Comissão Total</div><div class="kpi-value" id="kpiCommission">R$ 0,00</div></div>
    <div class="kpi"><div class="kpi-label">Vendedores</div><div class="kpi-value" id="kpiSellers">0</div></div>
  </div>
</div>

<div class="card" style="margin-top:1rem;" aria-labelledby="chartTitle">
  <h2 id="chartTitle" style="margin-top:0;">Desempenho por Vendedor</h2>
  <div id="chartBars" role="img" aria-label="Gráfico de barras de comissão por vendedor" style="display:flex;align-items:flex-end;gap:8px;height:180px;border-bottom:1px solid #ddd;padding:8px 0;overflow-x:auto;"></div>
</div>

<div class="card" style="margin-top:1rem;">
  <h2 style="margin-top:0;">Tabela de Comissões</h2>
  <div id="commAlert" class="alert" role="alert" style="display:none;"></div>
  <table class="table" id="commTable" aria-describedby="commDesc">
    <caption id="commDesc">Tabela de comissões por vendedor. Valores em BRL.</caption>
    <thead>
      <tr><th>Vendedor</th><th>Email</th><th>Receita</th><th>Comissão (%)</th><th>Comissão</th></tr>
    </thead>
    <tbody></tbody>
  </table>
  <div id="runs" style="margin-top:1rem;">
    <h3 style="margin:0 0 0.5rem 0;">Histórico de apurações</h3>
    <ul id="runsList" aria-live="polite"></ul>
  </div>
</div>

<style>
.kpi .kpi-label{font-size:12px;color:#666;margin-bottom:4px}
.kpi .kpi-value{font-size:20px;font-weight:600}
.bar{background:#4c8bf5;width:28px;border-radius:3px 3px 0 0;position:relative}
.bar:hover{background:#3a73d4}
.bar-label{position:absolute;bottom:100%;white-space:nowrap;transform:translateY(-4px);font-size:12px;color:#333}
.bar-value{position:absolute;bottom:4px;left:0;right:0;text-align:center;color:#fff;font-size:12px}
</style>

<script>
// Utilitários
function fmtBRL(cents){ const v = (Number(cents||0)/100).toFixed(2); return new Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'}).format(v); }
function escapeHtml(s){ return String(s||'').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c])); }
function authHeaders(){ const t=(localStorage.getItem('auth_token')||'').trim(); const base={'Accept':'application/json','Content-Type':'application/json'}; return t?Object.assign(base,{Authorization:`Bearer ${t}`}):base; }
function selValues(sel){ return Array.from(sel.options).filter(o=>o.selected).map(o=>o.value); }
let lastItems = [];

async function loadConfig(){
  const res = await fetch('/api/vendas/comissoes/config', { headers: authHeaders(), credentials: 'include' });
  if (!res.ok) return;
  const json = await res.json();
  const sellers = Array.isArray(json.vendors)?json.vendors:[];
  const empresas = Array.isArray(json.companies)?json.companies:[];
  const selSeller = document.getElementById('sellerSelect');
  const selEmpresa = document.getElementById('empresaSelect');
  selSeller.innerHTML = sellers.map(v => `<option value="${escapeHtml(v.email||'')}">${escapeHtml(v.nome||v.email||'-')} (${Number(v.comissao_percent||0).toFixed(2)}%)</option>`).join('');
  selEmpresa.innerHTML = empresas.map(e => `<option value="${String(e.id||'')}">${escapeHtml(e.nome||('- #'+e.id))}</option>`).join('');
  // datas padrão
  const end = new Date(); const start = new Date(end.getTime() - 29*24*3600*1000);
  document.getElementById('startDate').value = start.toISOString().slice(0,10);
  document.getElementById('endDate').value = end.toISOString().slice(0,10);
}

function renderTable(items){
  const tbody = document.querySelector('#commTable tbody');
  if (!items || items.length===0){ tbody.innerHTML = '<tr><td colspan="5">Sem dados no período.</td></tr>'; return; }
  tbody.innerHTML = items.map(r => {
    const name = escapeHtml(r.seller_name||'-');
    const email = escapeHtml(r.seller_email||'-');
    const revenue = fmtBRL(r.revenue_cents);
    const percent = (Number(r.commission_percent||0)).toFixed(2)+'%';
    const comm = fmtBRL(r.commission_cents);
    return `<tr><td>${name}</td><td>${email}</td><td>${revenue}</td><td>${percent}</td><td>${comm}</td></tr>`;
  }).join('');
}

function renderKpis(items){
  let totalR=0, totalC=0; const sellers = items?items.length:0;
  for (const it of (items||[])){ totalR+=Number(it.revenue_cents||0); totalC+=Number(it.commission_cents||0); }
  document.getElementById('kpiRevenue').textContent = fmtBRL(totalR);
  document.getElementById('kpiCommission').textContent = fmtBRL(totalC);
  document.getElementById('kpiSellers').textContent = String(sellers);
}

function renderBars(items){
  const cont = document.getElementById('chartBars');
  cont.innerHTML = '';
  if (!items || items.length===0) return;
  const max = Math.max(...items.map(i=>Number(i.commission_cents||0)), 1);
  for (const it of items){
    const h = Math.max(12, Math.round((Number(it.commission_cents||0)/max) * 160));
    const bar = document.createElement('div'); bar.className='bar'; bar.style.height = h+'px';
    const lab = document.createElement('div'); lab.className='bar-label'; lab.textContent = String(it.seller_name||'-');
    const val = document.createElement('div'); val.className='bar-value'; val.textContent = fmtBRL(it.commission_cents);
    bar.appendChild(val); bar.appendChild(lab); cont.appendChild(bar);
  }
}

async function applyFilters(){
  const alertEl = document.getElementById('commAlert');
  const status = document.getElementById('statusText');
  alertEl.style.display='none'; alertEl.textContent=''; status.textContent='Carregando...';
  const seller_emails = selValues(document.getElementById('sellerSelect'));
  const empresa_ids = selValues(document.getElementById('empresaSelect'));
  const start = document.getElementById('startDate').value; const end = document.getElementById('endDate').value;
  try {
    const res = await fetch('/api/vendas/comissoes/generate', {
      method:'POST', headers: authHeaders(), credentials:'include', body: JSON.stringify({ seller_emails, empresa_ids, period_type: document.getElementById('periodType').value, start, end })
    });
    if (!res.ok){ throw new Error('API retornou '+res.status); }
    const json = await res.json();
    const items = Array.isArray(json.items)?json.items:[];
    lastItems = items;
    renderTable(items); renderKpis(items); renderBars(items);
    status.textContent = 'Apuração '+(json.status||'')+' • '+(json.period?json.period.start+' a '+json.period.end:'');
    await loadRuns();
  } catch (e) {
    alertEl.textContent = 'Falha ao aplicar filtros: '+(e && e.message ? e.message : 'erro desconhecido');
    alertEl.style.display='block';
    status.textContent = 'Falha ao carregar.';
  }
}

async function loadRuns(){
  try {
    const res = await fetch('/api/vendas/comissoes/runs', { headers: authHeaders(), credentials:'include' });
    const json = await res.json();
    const list = document.getElementById('runsList');
    const rows = Array.isArray(json.data)?json.data:[];
    list.innerHTML = rows.map(r => `<li>Run #${String(r.id||'?')} — ${escapeHtml(r.period_type||'-')} • ${escapeHtml(r.start_date||'?')} a ${escapeHtml(r.end_date||'?')} • Comissão: ${fmtBRL(r.total_commission_cents||0)}</li>`).join('');
  } catch {}
}

document.addEventListener('DOMContentLoaded', async () => {
  await loadConfig();
  await applyFilters();
  document.getElementById('btnAplicar').addEventListener('click', applyFilters);
  document.getElementById('btnGerar').addEventListener('click', applyFilters);
  document.getElementById('btnCsv').addEventListener('click', async () => {
    const seller_emails = selValues(document.getElementById('sellerSelect'));
    const empresa_ids = selValues(document.getElementById('empresaSelect'));
    const start = document.getElementById('startDate').value; const end = document.getElementById('endDate').value;
    const q = new URLSearchParams();
    for (const e of seller_emails) q.append('seller_emails[]', e);
    for (const i of empresa_ids) q.append('empresa_ids[]', i);
    q.append('start', start); q.append('end', end);
    window.open('/api/vendas/comissoes/report.csv?'+q.toString(), '_blank');
  });
  document.getElementById('btnXlsx').addEventListener('click', async () => {
    const seller_emails = selValues(document.getElementById('sellerSelect'));
    const empresa_ids = selValues(document.getElementById('empresaSelect'));
    const start = document.getElementById('startDate').value; const end = document.getElementById('endDate').value;
    const q = new URLSearchParams();
    for (const e of seller_emails) q.append('seller_emails[]', e);
    for (const i of empresa_ids) q.append('empresa_ids[]', i);
    q.append('start', start); q.append('end', end);
    window.open('/api/vendas/comissoes/report.xlsx?'+q.toString(), '_blank');
  });
  document.getElementById('btnPdf').addEventListener('click', () => {
    try {
      if (!window.jspdf || typeof window.jspdf.jsPDF !== 'function') {
        alert('Biblioteca jsPDF não está carregada'); return;
      }
      const { jsPDF } = window.jspdf;
      const doc = new jsPDF({ unit: 'mm', format: 'a4' });
      const margin = 12; const pageW = 210; const pageH = 297; let y = margin;
      // Cabeçalho simples
      doc.setFontSize(14); doc.text('Relatório de Comissões de Vendas', margin, y); y += 8;
      doc.setFontSize(10);
      const start = document.getElementById('startDate').value; const end = document.getElementById('endDate').value;
      const periodType = document.getElementById('periodType').value;
      doc.text(`Período: ${start} a ${end} • Tipo: ${periodType}`, margin, y); y += 6;
      // Totais
      let totalR=0, totalC=0; for (const it of (lastItems||[])){ totalR+=Number(it.revenue_cents||0); totalC+=Number(it.commission_cents||0); }
      doc.text(`Receita Total: ${fmtBRL(totalR)} • Comissão Total: ${fmtBRL(totalC)} • Vendedores: ${String((lastItems||[]).length)}`, margin, y); y += 10;
      // Tabela
      const cols = [
        { key:'seller_name', title:'Vendedor', w:60 },
        { key:'seller_email', title:'Email', w:60 },
        { key:'revenue_cents', title:'Receita', w:30, fmt:(v)=>fmtBRL(v) },
        { key:'commission_percent', title:'% Comissão', w:20, fmt:(v)=> (Number(v||0)).toFixed(2)+'%' },
        { key:'commission_cents', title:'Comissão', w:30, fmt:(v)=>fmtBRL(v) },
      ];
      // Cabeçalho da tabela
      doc.setFontSize(10); doc.setTextColor(30);
      let x = margin;
      for (const c of cols){ doc.text(c.title, x, y); x += c.w; }
      y += 6; doc.setDrawColor(180); doc.line(margin, y-4, pageW-margin, y-4);
      doc.setTextColor(60);
      for (const row of (lastItems||[])){
        // Quebra de página se necessário
        if (y > pageH - margin - 8){ doc.addPage(); y = margin; doc.setTextColor(30); x = margin; for (const c of cols){ doc.text(c.title, x, y); x += c.w; } y += 6; doc.setDrawColor(180); doc.line(margin, y-4, pageW-margin, y-4); doc.setTextColor(60); }
        x = margin;
        for (const c of cols){
          let v = row[c.key]; if (typeof c.fmt === 'function') v = c.fmt(v);
          doc.text(String(v ?? ''), x, y, { maxWidth: c.w - 2 });
          x += c.w;
        }
        y += 6;
      }
      // Rodapé
      doc.setFontSize(9); doc.setTextColor(100); doc.text('Gerado por GestorEasy • Relatório de Comissões', margin, pageH - margin);
      const fname = `comissoes_${start}_${end}.pdf`;
      doc.save(fname);
    } catch (e){ alert('Falha ao gerar PDF: ' + (e && e.message ? e.message : e)); }
  });
});
</script>