<?php /** @var string $title */ ?>
<main class="container">
  <header class="page-header">
    <h1><?= htmlspecialchars($title ?? 'Serviços: Emissão de NFS-e') ?></h1>
    <p class="muted">Emita notas fiscais de serviço a partir de ordens elegíveis.</p>
  </header>

  <section class="card">
    <h2>Filtrar Ordens</h2>
    <div class="grid" style="grid-template-columns: repeat(4, minmax(0,1fr)); gap:.5rem; align-items:end;">
      <div>
        <label class="muted" for="q">Buscar</label>
        <input id="q" type="text" placeholder="Placa, modelo, status ou #ID" />
      </div>
      <div>
        <label class="muted" for="onlyEligible">Apenas elegíveis</label>
        <select id="onlyEligible">
          <option value="1" selected>Sim</option>
          <option value="0">Não</option>
        </select>
      </div>
      <div style="display:flex; gap:.5rem;">
        <button id="btnReload">Recarregar</button>
        <button id="btnClear" class="btn btn-outline">Limpar</button>
        <a class="btn btn-outline" href="/servicos/ordens?new=1">Nova OS</a>
      </div>
      <div></div>
    </div>
    <p class="muted" style="margin-top:.5rem;">Regras: cliente obrigatório; OS não pode estar faturada/cancelada.</p>
  </section>

  <section class="card">
    <h2>Ordens para Emissão</h2>
    <div id="ordersError" style="display:none;margin:.5rem 0;padding:.5rem;border:1px solid #b00;color:#b00;background:#fee;border-radius:.25rem;"></div>
    <table class="table">
      <thead>
        <tr><th>#</th><th>Placa</th><th>Modelo</th><th>Status</th><th>Cliente</th><th>Valor</th><th>Abertura</th><th>Ações</th></tr>
      </thead>
      <tbody id="rows"><tr><td colspan="8" class="muted">Carregando…</td></tr></tbody>
    </table>
    <div id="ordersPager" style="display:flex; gap:.5rem; align-items:center; justify-content:flex-end; margin-top:.5rem;">
      <label class="muted">Itens por página</label>
      <select id="ordersPerPage" style="min-width:5rem;">
        <option value="10" selected>10</option>
        <option value="20">20</option>
        <option value="50">50</option>
      </select>
      <button id="ordersPrev" class="btn btn-outline">Anterior</button>
      <span id="ordersPageInfo" class="muted">Página 1 de 1</span>
      <button id="ordersNext" class="btn btn-outline">Próxima</button>
    </div>
  </section>

  <section class="card">
    <h2>Últimas NFS-e</h2>
    <div id="docsError" style="display:none;margin:.5rem 0;padding:.5rem;border:1px solid #b00;color:#b00;background:#fee;border-radius:.25rem;"></div>
    <table class="table">
      <thead><tr><th>#Doc</th><th>OS</th><th>Título</th><th>Tipo</th><th>Status</th><th>Arquivo</th><th>Criado em</th></tr></thead>
      <tbody id="docsRows"><tr><td colspan="7" class="muted">Carregando…</td></tr></tbody>
    </table>
    <div id="docsPager" style="display:flex; gap:.5rem; align-items:center; justify-content:flex-end; margin-top:.5rem;">
      <label class="muted">Itens por página</label>
      <select id="docsPerPage" style="min-width:5rem;">
        <option value="10" selected>10</option>
        <option value="20">20</option>
        <option value="50">50</option>
      </select>
      <button id="docsPrev" class="btn btn-outline">Anterior</button>
      <span id="docsPageInfo" class="muted">Página 1 de 1</span>
      <button id="docsNext" class="btn btn-outline">Próxima</button>
    </div>
  </section>

  <section class="card">
    <h2>Cancelar NFS-e</h2>
    <p class="muted">Informe o número da NFS-e e a justificativa do cancelamento.</p>
    <div class="grid" style="grid-template-columns: repeat(2, minmax(0,1fr)); gap:.5rem; align-items:end;">
      <div>
        <label class="muted" for="cancelNumero">Número da NFS-e</label>
        <input id="cancelNumero" type="text" placeholder="Ex.: 2025-000123" />
      </div>
      <div>
        <label class="muted" for="cancelJustificativa">Justificativa</label>
        <input id="cancelJustificativa" type="text" placeholder="Descreva o motivo do cancelamento" />
      </div>
    </div>
    <div style="display:flex; gap:.5rem; margin-top:.5rem; align-items:center;">
      <button id="btnCancelarNfse" class="btn btn-warning">Cancelar NFS-e</button>
      <span id="cancelStatus" class="muted"></span>
    </div>
  </section>

  <!-- Modal de confirmação -->
  <div id="cancelModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.4); align-items:center; justify-content:center;">
    <div style="background:#fff; padding:1rem; border-radius:.25rem; width:min(520px, 92vw); box-shadow:0 10px 30px rgba(0,0,0,.2);">
      <h3>Confirmar cancelamento</h3>
      <p class="muted">Revise os dados antes de confirmar:</p>
      <div style="display:grid; grid-template-columns: 1fr 2fr; gap:.5rem;">
        <div class="muted">Número</div>
        <div id="cancelModalNumero">-</div>
        <div class="muted">Justificativa</div>
        <div id="cancelModalJust">-</div>
      </div>
      <div style="display:flex; gap:.5rem; margin-top:1rem; justify-content:flex-end;">
        <button id="btnCancelNo" class="btn btn-outline">Voltar</button>
        <button id="btnCancelYes" class="btn btn-warning">Confirmar cancelamento</button>
      </div>
    </div>
  </div>
</main>

<script>
async function apiRequest(url, options){
  // Usa helper global quando disponível; caso contrário, fallback com credenciais
  if (typeof window.apiRequest === 'function') { return window.apiRequest(url, options); }
  const opts = options || {};
  const isForm = (opts.body && typeof FormData !== 'undefined' && opts.body instanceof FormData);
  const headers = opts.headers || {};
  if (!isForm) { headers['Content-Type'] = headers['Content-Type'] || 'application/json'; }
  // Prefixo consistente da API
  const base = '/api';
  const method = opts.method || 'GET';
  const body = isForm ? opts.body : (opts.body ? JSON.stringify(opts.body) : undefined);
  return fetch(base + url, { method, headers, body, credentials: 'include', cache: 'no-store' });
}
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 setError(id, msg){ const el=document.getElementById(id); if(!el) return; if(msg){ el.textContent = msg; el.style.display='block'; } else { el.textContent=''; el.style.display='none'; } }

// Estado inicial via URL
const __params = new URLSearchParams(window.location.search||'');
let ordersPage = Number(__params.get('orders_page')||1) || 1;
let ordersPerPage = Number(__params.get('orders_per_page')||10) || 10;
let ordersTotalPages = 1;
let docsPage = Number(__params.get('docs_page')||1) || 1;
let docsPerPage = Number(__params.get('docs_per_page')||10) || 10;
let docsTotalPages = 1;
const initialQ = __params.get('q') || '';
const initialOnly = __params.get('only') || (__params.get('onlyEligible')||'1');
document.getElementById('q').value = initialQ;
document.getElementById('onlyEligible').value = (initialOnly==='0'?'0':'1');
document.getElementById('ordersPerPage').value = String(ordersPerPage);
document.getElementById('docsPerPage').value = String(docsPerPage);

function updateUrl(){
  const p = new URLSearchParams(window.location.search||'');
  p.set('q', document.getElementById('q').value.trim());
  p.set('only', document.getElementById('onlyEligible').value);
  p.set('orders_page', String(ordersPage));
  p.set('orders_per_page', String(ordersPerPage));
  p.set('docs_page', String(docsPage));
  p.set('docs_per_page', String(docsPerPage));
  const url = window.location.pathname + '?' + p.toString();
  window.history.replaceState(null, '', url);
}

async function loadOrders(){ try {
  document.getElementById('rows').innerHTML = '<tr><td colspan="8" class="muted">Carregando…</td></tr>';
  setError('ordersError','');
  const q = document.getElementById('q').value.trim();
  const only = document.getElementById('onlyEligible').value === '1';
  const params = new URLSearchParams();
  params.set('page', String(ordersPage));
  params.set('per_page', String(ordersPerPage));
  if (q) params.set('q', q);
  const resp = await apiRequest('/api/servicos/ordens?' + params.toString());
  if (!resp.ok){ const txt = await resp.text().catch(()=> ''); setError('ordersError', `Erro ${resp.status}: ${txt.slice(0,200)}`); document.getElementById('rows').innerHTML = '<tr><td colspan="8" class="muted">Erro ao carregar</td></tr>'; return; }
  const j = await resp.json(); const data = Array.isArray(j.data)? j.data: [];
  const rows = data.filter(r => {
    const okStatus = !['faturada','cancelada'].includes(String(r.status||''));
    const okCliente = Number(r.cliente_id||0) > 0;
    let ok = okStatus && okCliente;
    if (!only) ok = true;
    if (q){ const s = String(q).toLowerCase(); ok = ok && (
      String(r.id||'').includes(q) || String(r.placa||'').toLowerCase().includes(s) || String(r.modelo||'').toLowerCase().includes(s) || String(r.status||'').toLowerCase().includes(s)
    ); }
    return ok;
  }).map(r => {
    const canEmit = !['faturada','cancelada'].includes(String(r.status||'')) && Number(r.cliente_id||0) > 0;
    const clienteNome = r.cliente_nome || r.cliente_id || '-';
    return `<tr>
      <td>${r.id}</td>
      <td>${r.placa||'-'}</td>
      <td>${r.modelo||'-'}</td>
      <td>${r.status||'-'}</td>
      <td>${clienteNome}</td>
      <td>${fmtBRL((r.valor_total_cents||0)/100)}</td>
      <td>${r.aberta_em||'-'}</td>
      <td>${canEmit? `<button onclick="emitirNfse(${r.id})">Emitir NFS-e</button>`: '<span class="muted">Indisponível</span>'}</td>
    </tr>`;
  }).join('');
  document.getElementById('rows').innerHTML = rows || '<tr><td colspan="8" class="muted">Sem ordens para emissão</td></tr>';
  // Atualiza paginação
  ordersTotalPages = Number(j.total_pages || j.totalPages || 1) || 1;
  const curPage = Number(j.page || ordersPage || 1) || 1;
  ordersPage = curPage;
  document.getElementById('ordersPageInfo').textContent = `Página ${ordersPage} de ${ordersTotalPages}`;
  document.getElementById('ordersPrev').disabled = ordersPage <= 1;
  document.getElementById('ordersNext').disabled = ordersPage >= ordersTotalPages;
  updateUrl();
} catch(e){ document.getElementById('rows').innerHTML = '<tr><td colspan="8" class="muted">Erro ao carregar</td></tr>'; }
}

async function loadDocs(){ try {
  document.getElementById('docsRows').innerHTML = '<tr><td colspan="6" class="muted">Carregando…</td></tr>';
  setError('docsError','');
  const params = new URLSearchParams();
  params.set('page', String(docsPage));
  params.set('per_page', String(docsPerPage));
  const resp = await apiRequest('/api/servicos/documentos?' + params.toString());
  if (!resp.ok){ const txt = await resp.text().catch(()=> ''); setError('docsError', `Erro ${resp.status}: ${txt.slice(0,200)}`); document.getElementById('docsRows').innerHTML = '<tr><td colspan="6" class="muted">Erro ao carregar</td></tr>'; return; }
  const j = await resp.json(); const rows = Array.isArray(j.data)? j.data: [];
  const html = rows.filter(d => String(d.tipo||'').toLowerCase() === 'nfse' || String(d.titulo||'').toLowerCase().includes('nfse')).map(d => {
    const nome = d.arquivo_nome || '-'; const url = d.url || '#';
    const status = d.status || '-';
    return `<tr><td>${d.id}</td><td>${d.order_id||'-'}</td><td>${(d.titulo||'-')}</td><td>${(d.tipo||'-')}</td><td>${status}</td><td>${url? `<a href="${url}" target="_blank">${nome}</a>`: nome}</td><td>${d.created_at||'-'}</td></tr>`;
  }).join('');
  document.getElementById('docsRows').innerHTML = html || '<tr><td colspan="7" class="muted">Sem NFS-e emitidas</td></tr>';
  // Atualiza paginação
  docsTotalPages = Number(j.total_pages || j.totalPages || 1) || 1;
  const curPage = Number(j.page || docsPage || 1) || 1;
  docsPage = curPage;
  document.getElementById('docsPageInfo').textContent = `Página ${docsPage} de ${docsTotalPages}`;
  document.getElementById('docsPrev').disabled = docsPage <= 1;
  document.getElementById('docsNext').disabled = docsPage >= docsTotalPages;
  updateUrl();
} catch(e){ document.getElementById('docsRows').innerHTML = '<tr><td colspan="6" class="muted">Erro ao carregar</td></tr>'; }
}

async function emitirNfse(id){ try {
  const resp = await apiRequest(`/api/servicos/ordens/${id}/emitir-nfs-e`, { method: 'POST' });
  if (resp.ok){ const j = await resp.json(); alert('NFS-e emitida. Nº: '+(j.nfse?.numero||'-')); loadOrders(); loadDocs(); }
  else { const e = await resp.json().catch(()=>({})); alert('Falha: '+(e.error?.message||resp.status)); }
} catch(err){ alert('Erro ao emitir NFS-e'); }
}

async function cancelarNfse(){
  try {
    const numero = (document.getElementById('cancelNumero').value||'').trim();
    const justificativa = (document.getElementById('cancelJustificativa').value||'').trim();
    const statusEl = document.getElementById('cancelStatus');
    statusEl.textContent = '';
    if (!numero || !justificativa){ statusEl.textContent = 'Informe número e justificativa.'; statusEl.className='text-error'; return; }
    // Mostrar modal de confirmação
    document.getElementById('cancelModalNumero').textContent = numero;
    document.getElementById('cancelModalJust').textContent = justificativa;
    const modal = document.getElementById('cancelModal');
    modal.style.display = 'flex';
    // Bind botões
    const no = document.getElementById('btnCancelNo');
    const yes = document.getElementById('btnCancelYes');
    const off = ()=>{ modal.style.display='none'; no.removeEventListener('click', onNo); yes.removeEventListener('click', onYes); };
    const onNo = ()=>{ off(); };
    const onYes = async ()=>{
      try {
        const resp = await apiRequest('/servicos/nfse/cancelar', { method:'POST', body: { numero, justificativa } });
        off();
        if (resp && resp.ok){ const j = await resp.json().catch(()=>({})); statusEl.textContent = j.canceled? 'Cancelada com sucesso' : 'Solicitação registrada'; statusEl.className='text-success'; loadDocs(); }
        else { const e = await resp.json().catch(()=>({})); statusEl.textContent = 'Falha: ' + (e.error?.message||resp.status||'erro'); statusEl.className='text-error'; }
      } catch(err){ statusEl.textContent = 'Erro ao cancelar'; statusEl.className='text-error'; off(); }
    };
    no.addEventListener('click', onNo);
    yes.addEventListener('click', onYes);
    const resp = await apiRequest('/servicos/nfse/cancelar', { method:'POST', body: { numero, justificativa } });
    // chamada redundante removida (usaremos confirmação acima)
  } catch(err){ const statusEl = document.getElementById('cancelStatus'); statusEl.textContent = 'Erro ao cancelar'; statusEl.className='text-error'; }
}

document.getElementById('btnReload').addEventListener('click', ()=>{ loadOrders(); });
document.getElementById('btnClear').addEventListener('click', ()=>{ try { document.getElementById('q').value=''; document.getElementById('onlyEligible').value='1'; ordersPage=1; docsPage=1; updateUrl(); loadOrders(); loadDocs(); } catch(e){ loadOrders(); loadDocs(); } });
document.getElementById('q').addEventListener('input', ()=>{ clearTimeout(window.__nfse_q_t); window.__nfse_q_t=setTimeout(()=>{ ordersPage=1; loadOrders(); }, 250); });
document.getElementById('onlyEligible').addEventListener('change', ()=>{ ordersPage=1; loadOrders(); });
// Eventos de paginação Ordens
document.getElementById('ordersPerPage').addEventListener('change', (e)=>{ ordersPerPage = Number(e.target.value||10); ordersPage = 1; loadOrders(); });
document.getElementById('ordersPrev').addEventListener('click', ()=>{ if (ordersPage > 1) { ordersPage--; loadOrders(); } });
document.getElementById('ordersNext').addEventListener('click', ()=>{ if (ordersPage < ordersTotalPages) { ordersPage++; loadOrders(); } });
// Eventos de paginação Docs
document.getElementById('docsPerPage').addEventListener('change', (e)=>{ docsPerPage = Number(e.target.value||10); docsPage = 1; loadDocs(); });
document.getElementById('docsPrev').addEventListener('click', ()=>{ if (docsPage > 1) { docsPage--; loadDocs(); } });
document.getElementById('docsNext').addEventListener('click', ()=>{ if (docsPage < docsTotalPages) { docsPage++; loadDocs(); } });
document.getElementById('btnCancelarNfse').addEventListener('click', cancelarNfse);
setTimeout(()=>{ loadOrders(); loadDocs(); }, 50);
</script>