<?php /** @var string $title */ ?>
<main class="container">
  <header class="page-header">
    <h1><?= htmlspecialchars($title ?? 'Serviços: Checklists') ?></h1>
    <p class="muted">Templates e registro de checklists por veículo.</p>
  </header>

  <section class="card">
    <div class="grid" style="grid-template-columns: repeat(3, minmax(0,1fr)); gap: .5rem; align-items: end;">
      <div>
        <label class="muted">Veículo ID</label>
        <input id="vehicleId" type="number" placeholder="ID do veículo" />
      </div>
      <div>
        <label class="muted">Tipo</label>
        <select id="tipo"><option value="carro">Carro</option><option value="moto">Moto</option><option value="pesado">Veículo Pesado</option><option value="outro">Outro</option></select>
      </div>
      <div style="display:flex; gap:.5rem;">
        <button id="btnLoad">Carregar Templates</button>
        <button id="btnReset">Limpar Itens</button>
      </div>
    </div>
  </section>

  <section class="card">
    <h2>Itens do Checklist</h2>
    <div id="itemsBox" class="grid" style="grid-template-columns: repeat(3, minmax(0,1fr)); gap:.5rem;"></div>
    <div class="grid" style="grid-template-columns: 1fr auto; gap:.5rem; margin-top:.5rem;">
      <input id="novoItem" type="text" placeholder="Adicionar outro item" />
      <button id="btnAddItem">Adicionar</button>
    </div>
    <p class="muted">Marque os itens conforme verificação. Adicione "Outros" quando necessário.</p>
  </section>

  <section class="card">
    <h2>Histórico do Veículo</h2>
    <table class="table">
      <thead><tr><th>#</th><th>Tipo</th><th>Itens marcados</th><th>Observações</th><th>Criado em</th></tr></thead>
      <tbody id="histRows"><tr><td colspan="5" class="muted">Informe veículo e carregue templates para ver histórico</td></tr></tbody>
    </table>
  </section>

  <section class="card">
    <h2>Observações</h2>
    <textarea id="obs" rows="3" placeholder="Opcional"></textarea>
    <div style="display:flex; gap:.5rem; justify-content:flex-end; margin-top:.5rem;"><button id="btnSave">Salvar Checklist</button></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 escapeHtml(s){ return String(s||'').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }
let templatesCache = [];
let itemsState = [];
function renderItems(){ const box=document.getElementById('itemsBox'); box.innerHTML = itemsState.map((it,idx)=>`<label class="chip" style="display:flex; align-items:center; gap:.5rem;"><input type="checkbox" data-idx="${idx}" ${it.checked? 'checked':''}> <span>${escapeHtml(it.label)}</span> <button class="btnSmall" data-rm="${idx}" title="Remover">×</button></label>`).join(''); box.querySelectorAll('input[type=checkbox]').forEach(el=>el.addEventListener('change',e=>{ const i=Number(e.target.getAttribute('data-idx')); itemsState[i].checked = !!e.target.checked; })); box.querySelectorAll('.btnSmall').forEach(el=>el.addEventListener('click',e=>{ const i=Number(e.target.getAttribute('data-rm')); itemsState.splice(i,1); renderItems(); })); }
async function loadTemplates(){ try { const resp=await apiRequest('/api/servicos/checklist/templates'); const json=await resp.json(); templatesCache=json.data||[]; const tipo=document.getElementById('tipo').value; const tpl=templatesCache.find(t=>t.tipo===tipo); itemsState = (tpl?.itens||[]).map(l=>({label:l, checked:false})); renderItems(); } catch(e){ itemsState=[]; renderItems(); } }
async function loadHistory(){ const vehicleId = Number(document.getElementById('vehicleId').value||0); const rowsEl=document.getElementById('histRows'); if (!vehicleId){ rowsEl.innerHTML = '<tr><td colspan="5" class="muted">Informe veículo para ver histórico</td></tr>'; return; } try { const resp=await apiRequest(`/api/servicos/checklists/${vehicleId}`); const j=await resp.json(); const rows=(j.data||[]).map(r=>{ const itens=Array.isArray(r.items)?r.items:[]; const marked=itens.filter(i=>!!i.checked).length; return `<tr><td>${r.id}</td><td>${escapeHtml(r.tipo||'-')}</td><td>${marked}</td><td>${escapeHtml(r.observacoes||'-')}</td><td>${escapeHtml(r.created_at||'-')}</td></tr>`; }).join(''); rowsEl.innerHTML = rows || '<tr><td colspan="5" class="muted">Sem histórico</td></tr>'; } catch(e){ rowsEl.innerHTML = '<tr><td colspan="5" class="muted">Erro ao carregar histórico</td></tr>'; } }
document.getElementById('btnLoad').addEventListener('click', loadTemplates);
document.getElementById('tipo').addEventListener('change', ()=>{ const tipo=document.getElementById('tipo').value; if (tipo==='outro'){ itemsState=[]; renderItems(); } else { const tpl=templatesCache.find(t=>t.tipo===tipo); itemsState = (tpl?.itens||[]).map(l=>({label:l, checked:false})); renderItems(); }});
document.getElementById('btnReset').addEventListener('click', ()=>{ itemsState=[]; renderItems(); });
document.getElementById('btnAddItem').addEventListener('click', ()=>{ const v=document.getElementById('novoItem').value.trim(); if(!v) return; itemsState.push({label:v, checked:false}); document.getElementById('novoItem').value=''; renderItems(); });
document.getElementById('btnSave').addEventListener('click', async ()=>{
  const vehicleId = Number(document.getElementById('vehicleId').value||0);
  const tipo = document.getElementById('tipo').value;
  const observacoes = document.getElementById('obs').value||'';
  if (!vehicleId) { alert('Informe veículo ID'); return; }
  const resp = await apiRequest('/api/servicos/checklists', { method:'POST', body: JSON.stringify({ vehicle_id: vehicleId, tipo, items: itemsState, observacoes }) });
  if (resp.ok) { alert('Checklist salvo'); loadHistory(); } else { alert('Falha ao salvar'); }
});
// Carrega templates ao abrir
setTimeout(()=>{ loadTemplates(); loadHistory(); }, 50);
// Atualiza histórico quando veículo muda
document.getElementById('vehicleId').addEventListener('input', ()=>{ clearTimeout(window.__vh); window.__vh=setTimeout(loadHistory, 250); });
</script>