<?php /** @var string $title */ ?>
<main class="container">
  <header class="page-header">
    <h1><?= htmlspecialchars($title ?? 'Notas Fiscais') ?></h1>
    <p class="muted">Histórico de emissões de NFC-e, com filtros e ações.</p>
  </header>

  <section class="card">
    <div class="grid" style="grid-template-columns: 1fr auto auto auto; gap: .5rem; align-items: end;">
      <div>
        <label class="muted" for="q">Buscar</label>
        <input id="q" type="text" placeholder="Chave, protocolo ou status" />
      </div>
      <div>
        <label class="muted" for="status">Status</label>
        <select id="status" class="input">
          <option value="">Todos</option>
          <option value="authorized">Autorizada</option>
          <option value="canceled">Cancelada</option>
          <option value="error">Erro</option>
        </select>
      </div>
      <div>
        <label class="muted" for="env">Ambiente</label>
        <select id="env" class="input">
          <option value="">Todos</option>
          <option value="homolog">Homologação</option>
          <option value="production">Produção</option>
        </select>
      </div>
      <div style="display:flex;gap:.5rem;">
        <button id="btnReload" class="btn">Recarregar</button>
        <button id="btnExport" class="btn btn-secondary">Exportar CSV</button>
      </div>
    </div>
  </section>

  <section class="card">
    <div class="table-responsive">
      <table class="table" aria-label="Emissões NFC-e">
        <thead>
          <tr>
            <th>#</th>
            <th>Status</th>
            <th>Chave</th>
            <th>Protocolo</th>
            <th>Ambiente</th>
            <th>Pedido</th>
            <th>Data</th>
            <th style="text-align:right;">Ações</th>
          </tr>
        </thead>
        <tbody id="rows"><tr><td colspan="8" class="muted">Carregando…</td></tr></tbody>
      </table>
    </div>
    <div id="pager" class="muted" style="margin-top:.5rem;display:flex;gap:.5rem;align-items:center;">
      <button id="prev" class="btn btn-secondary">Anterior</button>
      <span id="pageInfo">Página 1</span>
      <button id="next" class="btn btn-secondary">Próxima</button>
    </div>
  </section>

  <dialog id="cancelDialog">
    <form method="dialog" id="cancelForm">
      <h3>Cancelar NFC-e</h3>
      <p class="muted">Informe uma justificativa para o cancelamento.</p>
      <input type="hidden" id="cancelChave" />
      <div style="display:flex;flex-direction:column;gap:.5rem;">
        <label class="muted" for="cancelJust">Justificativa</label>
        <textarea id="cancelJust" rows="4" placeholder="Ex.: Venda em duplicidade"></textarea>
      </div>
      <div style="display:flex;gap:.5rem;margin-top:.5rem;">
        <button id="confirmCancel" class="btn" type="submit">Confirmar</button>
        <button class="btn btn-secondary" type="button" onclick="document.getElementById('cancelDialog').close()">Fechar</button>
      </div>
    </form>
  </dialog>
</main>

<script>
(function(){
  const apiReq = window.apiRequest || (async (url, method = 'GET', body = null) => {
    const headers = { 'content-type': 'application/json' };
    try { return await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined }); } catch (e) { console.error(e); return null; }
  });

  let page = 1; const perPage = 20; let totalPages = 1;

  function formatDate(d) {
    if (!d) return '';
    try { const dt = new Date(d); return dt.toLocaleString('pt-BR'); } catch(_) { return String(d); }
  }

  function renderRows(list) {
    const tbody = document.getElementById('rows');
    if (!Array.isArray(list) || list.length === 0) {
      tbody.innerHTML = '<tr><td colspan="8" class="muted">Sem dados</td></tr>';
      return;
    }
    const esc = s => String(s ?? '').replace(/[&<>]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]));
    tbody.innerHTML = list.map(r => {
      const id = esc(r.id);
      const st = esc(r.status);
      const chave = esc(r.chave);
      const prot = esc(r.protocolo);
      const env = esc(r.environment);
      const sale = esc(r.sale_id ?? '');
      const dt = esc(formatDate(r.created_at));
      const canBtn = (st === 'authorized')
        ? `<button class="btn btn-secondary" data-action="cancel" data-chave="${chave}">Cancelar</button>`
        : `<span class="muted">—</span>`;
      return `<tr>
        <td>${id}</td>
        <td>${st}</td>
        <td style="font-family:monospace">${chave}</td>
        <td>${prot}</td>
        <td>${env}</td>
        <td>${sale}</td>
        <td>${dt}</td>
        <td style="text-align:right;">${canBtn}</td>
      </tr>`;
    }).join('');

    // Wire cancel buttons
    tbody.querySelectorAll('button[data-action="cancel"]').forEach(btn => {
      btn.addEventListener('click', () => {
        const chave = btn.getAttribute('data-chave');
        document.getElementById('cancelChave').value = chave;
        document.getElementById('cancelJust').value = '';
        document.getElementById('cancelDialog').showModal();
      });
    });
  }

  async function reload() {
    const q = document.getElementById('q').value.trim();
    const status = document.getElementById('status').value;
    const env = document.getElementById('env').value;
    const url = `/api/fiscal/nfce/emissions?page=${page}&per_page=${perPage}` +
                (q ? `&q=${encodeURIComponent(q)}` : '') +
                (status ? `&status=${encodeURIComponent(status)}` : '') +
                (env ? `&environment=${encodeURIComponent(env)}` : '');
    const resp = await apiReq(url);
    if (!resp || !resp.ok) {
      document.getElementById('rows').innerHTML = '<tr><td colspan="8" class="muted">Falha ao carregar</td></tr>';
      return;
    }
    const js = await resp.json();
    totalPages = parseInt(js.total_pages || 1, 10) || 1;
    renderRows(js.data || []);
    document.getElementById('pageInfo').textContent = `Página ${page} de ${totalPages}`;
  }

  document.getElementById('btnReload').addEventListener('click', () => { page = 1; reload(); });
  document.getElementById('prev').addEventListener('click', () => { if (page > 1) { page--; reload(); } });
  document.getElementById('next').addEventListener('click', () => { if (page < totalPages) { page++; reload(); } });
  ['q','status','env'].forEach(id => { document.getElementById(id).addEventListener('change', () => { page = 1; reload(); }); });

  document.getElementById('cancelForm').addEventListener('submit', async (ev) => {
    ev.preventDefault();
    const chave = document.getElementById('cancelChave').value;
    const justificativa = document.getElementById('cancelJust').value.trim();
    if (!chave) { alert('Chave inválida'); return; }
    if (!justificativa || justificativa.length < 10) {
      alert('Justificativa deve conter ao menos 10 caracteres');
      return;
    }
    const resp = await apiReq('/api/fiscal/nfce/cancelar', 'POST', { chave, justificativa });
    if (!resp || !resp.ok) {
      alert('Falha ao cancelar NFC-e');
      return;
    }
    const js = await resp.json();
    alert('Cancelamento registrado: ' + (js.protocolo || ''));
    document.getElementById('cancelDialog').close();
    reload();
  });

  // Exportar CSV dos dados atuais da tabela
  document.getElementById('btnExport').addEventListener('click', () => {
    const rows = Array.from(document.querySelectorAll('#rows tr'));
    const cols = ['id','status','chave','protocolo','ambiente','pedido','data'];
    const getText = (td) => td.textContent.replace(/\s+/g,' ').trim();
    const csv = [cols.join(';')].concat(rows.map(tr => {
      const tds = Array.from(tr.querySelectorAll('td'));
      if (tds.length < 7) return null;
      return [0,1,2,3,4,5,6].map(i => getText(tds[i])).join(';');
    }).filter(Boolean)).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'emissoes_nfce.csv'; a.click();
    setTimeout(() => URL.revokeObjectURL(url), 5000);
  });

  // Inicialização
  reload();
})();
</script>