<?php /** @var string $title */ ?>
<main class="container">
  <header class="page-header">
    <h1><?= htmlspecialchars($title ?? 'Serviços: Relatórios') ?></h1>
    <p class="muted">Visão geral de ordens e faturamento.</p>
  </header>

  <section class="card">
    <h2>Período</h2>
    <div class="grid" style="grid-template-columns: repeat(4, minmax(0,1fr)); gap: .5rem; align-items:end;">
      <div>
        <label class="muted">Início</label>
        <input id="startDate" type="date" />
      </div>
      <div>
        <label class="muted">Fim</label>
        <input id="endDate" type="date" />
      </div>
      <div style="display:flex; gap:.5rem;">
        <button id="btnReload">Aplicar</button>
        <button id="btnExport" class="btn btn-outline">Exportar CSV</button>
      </div>
      <div></div>
    </div>
  </section>

  <section class="card">
    <h2>Resumo por Status</h2>
    <div id="statusGrid" class="grid" style="grid-template-columns: repeat(3, minmax(0,1fr)); gap: .5rem;"></div>
  </section>

  <section class="card">
    <h2>Total</h2>
    <div id="totalBox" class="chip">Carregando…</div>
  </section>
</main>

<script>
async function apiRequest(url, options){ if (typeof window.apiRequest === 'function') { return window.apiRequest(url, options); } const base='/api'; const opts=options||{}; const headers=opts.headers||{}; if(!(opts.body instanceof FormData)) headers['Content-Type']=headers['Content-Type']||'application/json'; return fetch(base+url,{...opts, headers, credentials:'include'}); }
function fmtBRL(v){ try { return (new Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'})).format(v); } catch(e){ return 'R$ '+Number(v).toFixed(2); } }
function getPeriodQuery(){ const s=document.getElementById('startDate').value; const e=document.getElementById('endDate').value; const qs=[]; if(s) qs.push('start='+encodeURIComponent(s)); if(e) qs.push('end='+encodeURIComponent(e)); return qs.length?('?'+qs.join('&')):''; }
async function load(){ try { const resp=await apiRequest('/api/servicos/relatorios/overview'+getPeriodQuery()); const json=await resp.json(); const rows=json.data||[]; const html = rows.map(r=>`<div class="card"><strong>${r.status||'-'}</strong><div>${r.c||0} ordens</div><div>${fmtBRL((r.total||0)/100)}</div></div>`).join(''); document.getElementById('statusGrid').innerHTML = html || '<div class="muted">Sem dados</div>'; document.getElementById('totalBox').textContent = 'Total: '+fmtBRL((json.total_cents||0)/100); } catch(e){ document.getElementById('statusGrid').innerHTML = '<div class="muted">Erro ao carregar</div>'; document.getElementById('totalBox').textContent = 'Erro ao carregar'; } }
function exportCsv(rows, total){ const header = ['status','ordens','total_centavos']; const lines = [header.join(',')].concat((rows||[]).map(r=>[String(r.status||'-'), String(r.c||0), String(r.total||0)].join(','))); lines.push(['TOTAL','',''+(total||0)].join(',')); const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8;' }); const a = document.createElement('a'); const url = URL.createObjectURL(blob); a.href = url; a.download = 'relatorio_overview.csv'; document.body.appendChild(a); a.click(); setTimeout(()=>{ document.body.removeChild(a); URL.revokeObjectURL(url); }, 50); }
document.getElementById('btnReload').addEventListener('click', load);
document.getElementById('btnExport').addEventListener('click', async ()=>{ try { const resp=await apiRequest('/api/servicos/relatorios/overview'+getPeriodQuery()); const json=await resp.json(); exportCsv(json.data||[], Number(json.total_cents||0)); } catch(e){} });
setTimeout(load, 50);
</script>