<div class="card">
  <h1>Relatórios de Compras</h1>
  <p>Acompanhe compras por fornecedor, período, status e itens mais comprados.</p>
  <div class="form-group" style="display:flex; gap:12px; align-items:end; flex-wrap:wrap;">
    <div>
      <label>Início</label>
      <input id="f-start" type="date" />
    </div>
    <div>
      <label>Fim</label>
      <input id="f-end" type="date" />
    </div>
    <div>
      <label>Limite</label>
      <input id="f-limit" type="number" min="1" max="100" value="20" />
    </div>
    <div>
      <button id="btn-aplicar" class="btn">Aplicar filtros</button>
      <a id="btn-export-csv" class="btn btn-secondary" href="#" target="_blank">Exportar por fornecedor (CSV)</a>
    </div>
  </div>

  <div id="alert" class="alert alert-warning" style="display:none"></div>

  <hr />

  <h3>Compras por Fornecedor</h3>
  <div style="overflow:auto">
    <table id="tbl-fornecedores" class="table">
      <thead>
        <tr>
          <th>Fornecedor</th>
          <th>Ordens</th>
          <th>Total (R$)</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>

  <h3>Ordens por Status</h3>
  <div style="overflow:auto">
    <table id="tbl-status" class="table">
      <thead>
        <tr>
          <th>Status</th>
          <th>Ordens</th>
          <th>Total estimado (R$)</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>

  <h3>Top Itens Comprados</h3>
  <div style="overflow:auto">
    <table id="tbl-itens" class="table">
      <thead>
        <tr>
          <th>Produto</th>
          <th>Código</th>
          <th>Quantidade</th>
          <th>Total (R$)</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>

  <h3>Curva ABC de Compras</h3>
  <div class="form-group" style="display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
    <div>
      <label>Métrica</label>
      <select id="abc-metric">
        <option value="valor" selected>Valor</option>
        <option value="quantidade">Quantidade</option>
      </select>
    </div>
    <div>
      <label>Classe A (%)</label>
      <input id="abc-a-pct" type="number" min="1" max="95" value="80" />
    </div>
    <div>
      <label>Classe B (%)</label>
      <input id="abc-b-pct" type="number" min="1" max="95" value="15" />
    </div>
    <div>
      <label>Classe C (%)</label>
      <input id="abc-c-pct" type="number" min="1" max="95" value="5" />
    </div>
    <div>
      <small id="abc-threshold-label">Classificação: A=80%, B=15%, C=5%</small>
    </div>
    <div>
      <button id="btn-export-abc-csv" class="btn">Exportar ABC (CSV)</button>
    </div>
    <div>
      <button id="btn-export-abc-pdf" class="btn btn-secondary">Exportar ABC (PDF)</button>
    </div>
  </div>
  <div style="overflow:auto">
    <table id="tbl-abc" class="table">
      <thead>
        <tr>
          <th>Produto</th>
          <th>Código</th>
          <th>Quantidade</th>
          <th>Total (R$)</th>
          <th>Participação (%)</th>
          <th>Cumulativo (%)</th>
          <th>Categoria</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>

  <p>
  </p>
</div>

<script>
  (function(){
    const qs = (s) => document.querySelector(s);
    const fmtMoney = (v) => {
      const n = Number(v||0);
      return n.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
    };
    const showError = (err) => {
      const el = qs('#alert');
      if (el) {
        el.textContent = err && err.message ? err.message : 'Erro ao carregar relatórios.';
        el.style.display = '';
      }
      const exp = qs('#btn-export-csv');
      if (exp) exp.style.display = 'none';
    };

    function showLoading(tbody, colspan){
      if (!tbody) return;
      const col = colspan||3; tbody.innerHTML = `<tr><td colspan="${col}" style="text-align:center;padding:1.25rem;">Carregando...</td></tr>`;
    }

    // Defaults: últimos 30 dias
    const today = new Date();
    const startDt = new Date(today.getTime() - 29*24*3600*1000);
    const toISO = (d) => d.toISOString().slice(0,10);
    qs('#f-start').value = toISO(startDt);
    qs('#f-end').value = toISO(today);

    async function fetchJson(url) {
      const resp = await fetch(url, { headers: { 'accept': 'application/json' } });
      if (!resp.ok) {
        const msg = resp.status === 401
          ? 'Não autorizado. Faça login com acesso a Compras > Relatórios.'
          : ('Falha ao carregar ' + url);
        const err = new Error(msg);
        err.status = resp.status;
        throw err;
      }
      return await resp.json();
    }

    async function loadReports() {
      const alertEl = qs('#alert');
      if (alertEl) alertEl.style.display = 'none';
      const start = qs('#f-start').value;
      const end = qs('#f-end').value;
      const limit = parseInt(qs('#f-limit').value || '20', 10);
      const params = `start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&limit=${limit}`;

      // Atualiza link de export CSV
      qs('#btn-export-csv').href = `/api/compras/relatorios/por-fornecedor/export.csv?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&limit=${limit}`;
      qs('#btn-export-csv').style.display = '';

      // Por fornecedor
      const fData = await fetchJson(`/api/compras/relatorios/por-fornecedor?${params}`);
      const fTbody = qs('#tbl-fornecedores tbody');
      showLoading(fTbody, 3);
      fTbody.innerHTML = '';
      (fData.items||[]).forEach(row => {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${row.fornecedor_nome || ''}</td><td>${row.ordens || 0}</td><td style="text-align:right">${fmtMoney(row.total || 0)}</td>`;
        fTbody.appendChild(tr);
      });

      // Ordens por status
      const sData = await fetchJson(`/api/compras/relatorios/ordens-por-status?${params}`);
      const sTbody = qs('#tbl-status tbody');
      showLoading(sTbody, 3);
      sTbody.innerHTML = '';
      (sData.items||[]).forEach(row => {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${row.status || ''}</td><td>${row.ordens || 0}</td><td style="text-align:right">${fmtMoney(row.total || 0)}</td>`;
        sTbody.appendChild(tr);
      });

      // Itens top
      const iData = await fetchJson(`/api/compras/relatorios/itens-top?${params}`);
      const iTbody = qs('#tbl-itens tbody');
      showLoading(iTbody, 4);
      iTbody.innerHTML = '';
      (iData.items||[]).forEach(row => {
        const code = row.product_code || '';
        const name = row.product_name || '';
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${name}</td><td>${code}</td><td>${Number(row.quantidade_total || 0).toLocaleString('pt-BR')}</td><td style="text-align:right">${fmtMoney(row.valor_total || 0)}</td>`;
        iTbody.appendChild(tr);
      });

      // Curva ABC
      const metric = qs('#abc-metric').value || 'valor';
      // thresholds configuráveis A/B (% -> decimal)
      const aIn = parseFloat((qs('#abc-a-pct')?.value||'80'))/100;
      const bIn = parseFloat((qs('#abc-b-pct')?.value||'15'))/100;
      const cIn = parseFloat((qs('#abc-c-pct')?.value||'5'))/100;
      const aRaw = (isFinite(aIn) && aIn>0) ? aIn : 0.8;
      const bRaw = (isFinite(bIn) && bIn>0) ? bIn : 0.15;
      const cRaw = (isFinite(cIn) && cIn>0) ? cIn : 0.05;
      const sumRaw = aRaw + bRaw + cRaw;
      const norm = sumRaw > 0 ? sumRaw : 1.0;
      const aPct = aRaw / norm;
      const bPct = bRaw / norm;
      const cPct = cRaw / norm;
      const lbl = qs('#abc-threshold-label');
      if (lbl) lbl.textContent = `Classificação: A=${(aPct*100).toFixed(0)}%, B=${(bPct*100).toFixed(0)}%, C=${(cPct*100).toFixed(0)}%`;

      const abcData = await fetchJson(`/api/compras/relatorios/abc?metric=${encodeURIComponent(metric)}&${params}&a_pct=${aPct}&b_pct=${bPct}`);
      const aTbody = qs('#tbl-abc tbody');
      showLoading(aTbody, 7);
      aTbody.innerHTML = '';
      const items = (abcData.items||[]);
      window.__comprasAbcRows = items;
      items.forEach(row => {
        const cat = String(row.categoria||'').toUpperCase();
        const catColor = cat==='A' ? '#d9480f' : (cat==='B' ? '#2b8a3e' : '#364fc7');
        const catStyle = `display:inline-block;padding:.15rem .35rem;border-radius:10px;color:#fff;background:${catColor};font-size:.8em;`;
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${row.product_name || ''}</td>`+
                       `<td>${row.product_code || ''}</td>`+
                       `<td>${Number(row.quantidade_total || 0).toLocaleString('pt-BR')}</td>`+
                       `<td style="text-align:right">${fmtMoney(row.valor_total || 0)}</td>`+
                       `<td style="text-align:right">${Number(row.share_pct || 0).toFixed(2)}%</td>`+
                       `<td style="text-align:right">${Number(row.cumulative_pct || 0).toFixed(2)}%</td>`+
                       `<td><span style="${catStyle}">${cat}</span></td>`;
        aTbody.appendChild(tr);
      });
    }

    qs('#btn-aplicar').addEventListener('click', () => {
      loadReports().catch(showError);
    });

    qs('#abc-metric').addEventListener('change', () => {
      loadReports().catch(showError);
    });
    qs('#abc-a-pct').addEventListener('change', () => {
      loadReports().catch(showError);
    });
    qs('#abc-b-pct').addEventListener('change', () => {
      loadReports().catch(showError);
    });
    qs('#abc-c-pct').addEventListener('change', () => {
      loadReports().catch(showError);
    });

    function exportAbcCsv(){
      const rows = window.__comprasAbcRows||[];
      if(!rows.length){ alert('Sem dados para exportação'); return; }
      const bom = '\uFEFF';
      const header = ['Produto','Código','Quantidade','Total (BRL)','Participação (%)','Cumulativo (%)','Categoria'];
      const lines = [header.join(';')].concat(rows.map(r=>[
        (r.product_name||''),
        (r.product_code||''),
        String(Number(r.quantidade_total||0)),
        fmtMoney(Number(r.valor_total||0)),
        Number(r.share_pct||0).toFixed(2)+'%',
        Number(r.cumulative_pct||0).toFixed(2)+'%',
        (r.categoria||'')
      ].join(';')));
      const csv = bom + lines.join('\n');
      const blob = new Blob([csv], {type:'text/csv;charset=utf-8'});
      const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='curva_abc_compras.csv'; document.body.appendChild(a); a.click(); a.remove();
    }
    qs('#btn-export-abc-csv').addEventListener('click', exportAbcCsv);

    function escapeHtml(s){
      return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[c]));
    }
    function exportAbcPdf(){
      const rows = window.__comprasAbcRows||[];
      if(!rows.length){ alert('Sem dados para exportação'); return; }
      const metric = qs('#abc-metric').value || 'valor';
      const thresholdsText = (qs('#abc-threshold-label')?.textContent)||'';
      const start = qs('#f-start').value || '';
      const end = qs('#f-end').value || '';
      const w = window.open('', '_blank');
      const title = `Curva ABC de Compras (${metric})`;
      w.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>${title}</title><style>body{font-family:Arial,sans-serif;padding:24px;}h1{font-size:20px;margin:0 0 8px;}table{width:100%;border-collapse:collapse;}th,td{border:1px solid #ccc;padding:6px;}th{background:#f4f6f8;text-align:left;}td:last-child{text-align:center}</style></head><body>`);
      w.document.write(`<h1>${title}</h1><div>${escapeHtml(thresholdsText)}</div><div>Período: ${escapeHtml(start)} a ${escapeHtml(end)}</div>`);
      w.document.write(`<table><thead><tr><th>Produto</th><th>Código</th><th>Quantidade</th><th>Total (R$)</th><th>Participação (%)</th><th>Cumulativo (%)</th><th>Categoria</th></tr></thead><tbody>`);
      rows.forEach(r=>{
        w.document.write(`<tr><td>${escapeHtml(r.product_name||'')}</td><td>${escapeHtml(r.product_code||'')}</td><td>${Number(r.quantidade_total||0).toLocaleString('pt-BR')}</td><td>${fmtMoney(Number(r.valor_total||0))}</td><td>${Number(r.share_pct||0).toFixed(2)}%</td><td>${Number(r.cumulative_pct||0).toFixed(2)}%</td><td>${escapeHtml(String(r.categoria||''))}</td></tr>`);
      });
      w.document.write(`</tbody></table></body></html>`);
      w.document.close();
      w.focus();
      w.print();
    }
    qs('#btn-export-abc-pdf').addEventListener('click', exportAbcPdf);

    // Carregar ao abrir
    loadReports().catch(showError);
  })();
</script>