<?php /** @var string $title */ ?>
<main class="container">
  <header class="page-header">
    <h1><?= htmlspecialchars($title ?? 'Serviços: Dashboard') ?></h1>
    <p class="muted">Acompanhe ordens de serviço em tempo real.</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="dashStart" type="date" />
      </div>
      <div>
        <label class="muted">Fim</label>
        <input id="dashEnd" type="date" />
      </div>
      <div style="display:flex; gap:.5rem;">
        <button id="dashApply">Aplicar</button>
      </div>
      <div></div>
    </div>
  </section>

  <section class="card">
    <h2>KPIs</h2>
    <div id="kpis" class="grid" style="grid-template-columns: repeat(4, minmax(0,1fr)); gap: .5rem;"></div>
  </section>

  <section class="card">
    <h2>Status das Ordens</h2>
    <div id="statusGrid" class="grid"></div>
  </section>

  <section class="card" style="display:grid; grid-template-columns: 1fr 1fr; gap: .75rem; align-items:start;">
    <div>
      <h2>Tendência e Previsão</h2>
      <canvas id="trendCanvas" width="600" height="240" style="max-width:100%; border:1px solid #eee; border-radius:.25rem;"></canvas>
    </div>
    <div>
      <h2>Vendas por Técnico</h2>
      <canvas id="techCanvas" width="600" height="240" style="max-width:100%; border:1px solid #eee; border-radius:.25rem;"></canvas>
    </div>
  </section>

  <section class="card">
    <h2>Últimas Ordens</h2>
    <table class="table">
      <thead>
        <tr><th>#</th><th>Placa</th><th>Modelo</th><th>Status</th><th>Valor</th><th>Abertura</th></tr>
      </thead>
      <tbody id="ordersRows"><tr><td colspan="6" class="muted">Carregando…</td></tr></tbody>
    </table>
  </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||{}; 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 drawLineChart(canvas, series, options){ const ctx=canvas.getContext('2d'); const w=canvas.width, h=canvas.height; ctx.clearRect(0,0,w,h); const pad=30; const ys = series.map(p=>p.y); const maxY = Math.max(1, ...ys); const stepX = (w - pad*2) / Math.max(1, (series.length-1)); ctx.strokeStyle = '#ddd'; ctx.beginPath(); ctx.moveTo(pad, pad); ctx.lineTo(pad, h-pad); ctx.lineTo(w-pad, h-pad); ctx.stroke(); ctx.strokeStyle = options?.color || '#2a7'; ctx.lineWidth = 2; ctx.beginPath(); series.forEach((p,i)=>{ const x = pad + i*stepX; const y = h-pad - (p.y / maxY) * (h - pad*2); if(i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y); }); ctx.stroke(); if(options?.forecast){ ctx.strokeStyle = '#999'; ctx.setLineDash([5,4]); ctx.beginPath(); const off = series.length - options.forecast.length; options.forecast.forEach((p,i)=>{ const x = pad + (off + i)*stepX; const y = h-pad - (p.y / maxY) * (h - pad*2); if(i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y); }); ctx.stroke(); ctx.setLineDash([]); } }
function drawBarChart(canvas, bars){ const ctx=canvas.getContext('2d'); const w=canvas.width, h=canvas.height; ctx.clearRect(0,0,w,h); const pad=30; const maxY=Math.max(1,...bars.map(b=>b.y)); const bw = Math.max(10, (w - pad*2) / (bars.length*1.2)); bars.forEach((b,i)=>{ const x = pad + i*(bw*1.2); const bh = (b.y / maxY) * (h - pad*2); ctx.fillStyle = '#348'; ctx.fillRect(x, h-pad-bh, bw, bh); ctx.fillStyle = '#666'; ctx.font = '12px sans-serif'; ctx.fillText(String(b.x).slice(0,12), x, h-pad+14); }); }

function getDashPeriodQuery(){ const s=document.getElementById('dashStart').value; const e=document.getElementById('dashEnd').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 {
    // KPIs e Status (com período)
    const ovResp = await apiRequest('/api/servicos/relatorios/overview'+getDashPeriodQuery());
    const ovJson = await ovResp.json(); const ovData = Array.isArray(ovJson.data) ? ovJson.data : [];
    const totalCents = Number(ovJson.total_cents||0); const byStatus = {}; ovData.forEach(r=>{ byStatus[r.status] = { c: (r.c||0), total: (r.total||0) }; });
    const kpiHtml = [
      `<div class="card"><strong>Total Faturado</strong><div>${fmtBRL(totalCents/100)}</div></div>`,
      `<div class="card"><strong>Abertas</strong><div>${(byStatus['aberta']?.c||0)}</div></div>`,
      `<div class="card"><strong>Em Andamento</strong><div>${(byStatus['em_andamento']?.c||0)}</div></div>`,
      `<div class="card"><strong>Concluídas</strong><div>${(byStatus['concluida']?.c||0)}</div></div>`
    ].join('');
    document.getElementById('kpis').innerHTML = kpiHtml;

    const resp = await apiRequest('/api/servicos/ordens');
    const json = await resp.json(); const data = Array.isArray(json.data) ? json.data : [];
    const rows = data.map(r => `<tr><td>${r.id}</td><td>${(r.placa||'-')}</td><td>${(r.modelo||'-')}</td><td>${(r.status||'-')}</td><td>${fmtBRL((r.valor_total_cents||0)/100)}</td><td>${(r.aberta_em||'-')}</td></tr>`).join('');
    document.getElementById('ordersRows').innerHTML = rows || '<tr><td colspan="6" class="muted">Sem dados</td></tr>';
    const byStatus2 = {}; data.forEach(r => { byStatus2[r.status] = (byStatus2[r.status]||0)+1; });
    document.getElementById('statusGrid').innerHTML = Object.keys(byStatus2).map(k => `<div class="chip">${k}: ${byStatus2[k]}</div>`).join('') || '<div class="muted">Sem ordens</div>';

    // Tendência e Previsão
    const tResp = await apiRequest('/api/servicos/relatorios/tendencia');
    const tJson = await tResp.json(); const tData = Array.isArray(tJson.data)?tJson.data:[]; const tForecast = Array.isArray(tJson.forecast)?tJson.forecast:[];
    const series = tData.map(r => ({ x: r.dia, y: Number(r.total||0)/100 })); // valor por dia
    const forecast = tForecast.map(r => ({ x: r.dia, y: Number(r.total||0)/100 }));
    drawLineChart(document.getElementById('trendCanvas'), series, { color:'#2a7', forecast });

    // Vendas por Técnico (em valor, com período)
    const techResp = await apiRequest('/api/servicos/relatorios/por_tecnico'+getDashPeriodQuery());
    const techJson = await techResp.json(); const techData = Array.isArray(techJson.data)?techJson.data:[];
    const bars = techData.map(r => ({ x: r.tecnico||'(não informado)', y: Number(r.total||0)/100 }));
    drawBarChart(document.getElementById('techCanvas'), bars);
  } catch(e){ document.getElementById('ordersRows').innerHTML = '<tr><td colspan="6" class="muted">Erro ao carregar</td></tr>'; }
}
setTimeout(load, 50);
document.getElementById('dashApply').addEventListener('click', ()=>{ load(); });
</script>