<?php /* Ordens de Compra */ ?>
<div class="card">
  <h1><?= htmlspecialchars($title ?? 'Ordens de Compra') ?></h1>
  <div style="display:grid; grid-template-columns: 1fr 1fr 1fr 1fr auto; gap:0.5rem; align-items:end; margin-bottom:1rem;">
    <div>
      <label class="muted" for="q">Busca</label>
      <input id="q" type="text" placeholder="Número, fornecedor ou status" style="width:100%; padding:0.5rem;">
    </div>
    <div>
      <label class="muted" for="fEmpresa">Empresa</label>
      <select id="fEmpresa" style="width:100%;"></select>
    </div>
    <div>
      <label class="muted" for="fDeposito">Depósito</label>
      <select id="fDeposito" style="width:100%;"></select>
    </div>
    <div>
      <label class="muted" for="fSituacao">Situação</label>
      <select id="fSituacao" style="width:100%;">
        <option value="">Todas</option>
        <option value="aberto">Aberto</option>
        <option value="aprovado">Aprovado</option>
        <option value="cancelado">Cancelado</option>
      </select>
    </div>
    <div>
      <label class="muted" for="fOperacao">Operação</label>
      <select id="fOperacao" style="width:100%;">
        <option value="">Todas</option>
        <option value="compra">Compra</option>
        <option value="reposicao">Reposição</option>
        <option value="producao">Produção</option>
      </select>
    </div>
    <div style="display:flex; gap:.5rem; align-items:center;">
      <button id="btnReload" class="btn btn-secondary">Recarregar</button>
      <button id="btnNew" class="btn">Nova Ordem</button>
    </div>
  </div>
  <div id="feedback" class="muted" aria-live="polite"></div>
  <table class="table" id="tbl">
    <thead>
      <tr><th>Número</th><th>Fornecedor</th><th>Status</th><th>Data</th><th style="text-align:right;">Ações</th></tr>
    </thead>
    <tbody id="rows"></tbody>
  </table>
</div>

<script>
async function apiRequest(url, opts = {}) {
  const res = await fetch(url, { ...opts, headers: { 'Content-Type': 'application/json' } });
  return res;
}
let currentRows = [];
function renderRows(rows) {
  const tbody = document.getElementById('rows');
  tbody.innerHTML = '';
  for (const r of rows) {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.numero ?? r.id}</td>
      <td>${r.supplier_id ?? '-'}</td>
      <td><span class="badge">${r.situacao ?? r.status ?? '-'}</span></td>
      <td>${(r.created_at||'').replace('T',' ').slice(0,19)}</td>
      <td style="text-align:right;">
        <button class="btn btn-sm" data-id="${r.id}" data-action="detail">Detalhes</button>
        ${r.status==='draft' ? `<button class="btn btn-sm" data-id="${r.id}" data-action="submit">Enviar</button>` : ''}
        ${r.status==='submitted' ? `<button class="btn btn-sm" data-id="${r.id}" data-action="approve">Aprovar</button><button class="btn btn-sm" data-id="${r.id}" data-action="reject">Rejeitar</button>` : ''}
        ${String(r.situacao||'')!=='cancelado' ? `<button class="btn btn-sm" data-id="${r.id}" data-action="cancel">Cancelar</button>` : ''}
        <button class="btn btn-sm" data-id="${r.id}" data-action="print">Imprimir</button>
      </td>`;
    tbody.appendChild(tr);
    const detailRow = document.createElement('tr');
    detailRow.className = 'detail-row';
    detailRow.innerHTML = `<td colspan="5"><div id="detail-${r.id}" class="muted" style="display:none; padding:0.75rem; border-top:1px solid #eee;">Carregando detalhes…</div></td>`;
    tbody.appendChild(detailRow);
  }
}
async function loadOrders() {
  const fb = document.getElementById('feedback'); fb.textContent = 'Carregando…';
  try {
    const qs = new URLSearchParams();
    const situacao = document.getElementById('fSituacao').value || '';
    const empresa = document.getElementById('fEmpresa').value || '';
    const deposito = document.getElementById('fDeposito').value || '';
    const operacao = document.getElementById('fOperacao').value || '';
    const q = document.getElementById('q').value.trim();
    if (situacao) qs.set('situacao', situacao);
    if (empresa) qs.set('empresa_id', empresa);
    if (deposito) qs.set('warehouse_id', deposito);
    if (operacao) qs.set('operacao', operacao);
    if (q) qs.set('q', q);
    const res = await apiRequest('/api/compras/ordens' + (qs.toString() ? `?${qs.toString()}` : ''));
    if (!res.ok) throw new Error('Falha ao carregar');
    const json = await res.json();
    currentRows = json.data || [];
    renderRows(currentRows);
    fb.textContent = `${currentRows.length} ordem(ns) carregadas.`;
  } catch (e) { fb.textContent = 'Erro: ' + e.message; }
}
// Carregar opções de filtros
async function loadFilters(){
  try {
    const [empRes, whRes] = await Promise.all([
      apiRequest('/api/cadastros/empresas'),
      apiRequest('/api/wms/warehouses')
    ]);
    const emp = (empRes.ok ? ((await empRes.json()).data||[]) : []);
    const whs = (whRes.ok ? ((await whRes.json()).data||[]) : []);
    const fEmpresa = document.getElementById('fEmpresa');
    const fDeposito = document.getElementById('fDeposito');
    fEmpresa.innerHTML = '<option value="">Todas</option>' + emp.map(e => `<option value="${e.id}">${e.nome||e.name||('ID '+e.id)}</option>`).join('');
    fDeposito.innerHTML = '<option value="">Todos</option>' + whs.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  } catch(_){ /* silencioso */ }
}
// Criar nova ordem (prompt simples)
document.getElementById('btnNew').addEventListener('click', () => {
  const dlg = document.getElementById('newDialog'); dlg.showModal();
});
document.addEventListener('click', async (ev) => {
  const btn = ev.target.closest('button'); if (!btn) return;
  const act = btn.getAttribute('data-action'); const id = btn.getAttribute('data-id');
  if (act === 'submit' && id) {
    const res = await apiRequest(`/api/compras/ordens/${id}/enviar`, { method: 'POST' });
    if (res.ok) { await loadOrders(); } else { alert('Falha ao enviar'); }
  } else if (act === 'detail' && id) {
    const el = document.getElementById(`detail-${id}`);
    if (!el) return;
    const visible = el.style.display === 'block';
    if (visible) { el.style.display = 'none'; return; }
    el.style.display = 'block'; el.textContent = 'Carregando detalhes…';
    const res = await apiRequest(`/api/compras/ordens/${id}`);
    if (!res.ok) { el.textContent = 'Falha ao carregar detalhes'; return; }
    const json = await res.json(); const o = json.data || {};
    const items = (o.items||[]).map(i => `#${i.product_id} x ${i.quantity} @ ${i.unit_price}`).join(', ');
    el.innerHTML = `
      <div><strong>Ordem #${o.id}</strong> — Fornecedor: ${o.supplier_id} — Status: ${o.status}</div>
      <div>Itens: ${items || 'Nenhum'}</div>
    `;
  } else if (act === 'approve' && id) {
    const res = await apiRequest(`/api/compras/ordens/${id}/aprovar`, { method: 'POST' });
    if (res.ok) { await loadOrders(); } else { alert('Falha ao aprovar'); }
  } else if (act === 'reject' && id) {
    const res = await apiRequest(`/api/compras/ordens/${id}/rejeitar`, { method: 'POST' });
    if (res.ok) { await loadOrders(); } else { alert('Falha ao rejeitar'); }
  } else if (act === 'cancel' && id) {
    if (!confirm('Confirmar cancelamento da ordem?')) return;
    const res = await apiRequest(`/api/compras/ordens/${id}/cancelar`, { method: 'POST' });
    if (res.ok) { await loadOrders(); } else { alert('Falha ao cancelar'); }
  } else if (act === 'print' && id) {
    window.open(`/api/compras/ordens/${id}/relatorio`, '_blank');
  }
});
document.getElementById('q').addEventListener('input', () => { /* busca via loadOrders */ loadOrders(); });
document.getElementById('btnReload').addEventListener('click', () => loadOrders());
document.getElementById('fEmpresa').addEventListener('change', () => loadOrders());
document.getElementById('fDeposito').addEventListener('change', () => loadOrders());
document.getElementById('fSituacao').addEventListener('change', () => loadOrders());
document.getElementById('fOperacao').addEventListener('change', () => loadOrders());
setTimeout(() => { loadFilters(); loadOrders(); }, 50);
</script>

<dialog id="newDialog">
  <form method="dialog" id="newForm">
    <div class="modal-header" style="display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid #eee; padding-bottom:.5rem; margin-bottom:.75rem;">
      <div>
        <h3 style="margin:0;">Nova Ordem de Compra</h3>
        <small class="muted">Preencha os dados e adicione itens</small>
      </div>
      <div style="display:flex; gap:.75rem; align-items:center;">
        <span class="badge" id="modalItemsCount">0 itens</span>
        <span class="badge" id="modalTotalBadge">Total: R$ 0,00</span>
      </div>
    </div>
    <div class="grid" style="grid-template-columns: repeat(2, minmax(0,1fr)); gap:.5rem;">
      <div>
        <label class="muted">Empresa</label>
        <select id="newEmpresa"></select>
      </div>
      <div>
        <label class="muted">Depósito</label>
        <select id="newDeposito"></select>
      </div>
      <div>
        <label class="muted">Fornecedor</label>
        <input id="newFornecedorInput" type="text" placeholder="ID - Nome do fornecedor" list="supOptions" />
        <datalist id="supOptions"></datalist>
        <input id="newFornecedor" type="hidden" />
      </div>
      <div>
        <label class="muted">Operação</label>
        <select id="newOperacao">
          <option value="compra">Compra</option>
          <option value="reposicao">Reposição</option>
          <option value="producao">Produção</option>
        </select>
      </div>
      <div>
        <label class="muted">Cond. Pagamento</label>
        <div style="display:flex; gap:.5rem; align-items:center;">
          <input id="newCondPag" type="text" placeholder="Ex: 30 dias" style="flex:1;" />
          <select id="newCondPagPreset" style="min-width:140px;">
            <option value="">Preset</option>
            <option value="À vista">À vista</option>
            <option value="14 dias">14 dias</option>
            <option value="30 dias">30 dias</option>
            <option value="30/60">30/60</option>
            <option value="30/60/90">30/60/90</option>
          </select>
        </div>
      </div>
      <div>
        <label class="muted">Cond. Entrega</label>
        <div style="display:flex; gap:.5rem; align-items:center;">
          <input id="newCondEnt" type="text" placeholder="Ex: CIF" style="flex:1;" />
          <select id="newCondEntPreset" style="min-width:120px;">
            <option value="">Preset</option>
            <option value="CIF">CIF</option>
            <option value="FOB">FOB</option>
          </select>
        </div>
      </div>
      <div style="grid-column: 1 / -1;">
        <label class="muted">Observações</label>
        <textarea id="newObs" rows="2" placeholder="Notas adicionais"></textarea>
      </div>
      <div style="grid-column: 1 / -1;">
        <label class="muted">Itens da Ordem</label>
        <div class="card" style="padding:0.75rem;">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:.5rem;">
            <div class="muted">Adicionar itens manualmente ou importar de uma cotação</div>
            <div style="display:flex; gap:.5rem; align-items:center;">
              <button type="button" class="btn btn-secondary" id="btnImportQuote">Importar de Cotação</button>
              <select id="quoteSelect" class="input" disabled style="min-width:220px;">
                <option value="">Cotações do fornecedor</option>
              </select>
              <button type="button" class="btn btn-secondary" id="btnImportSelectedQuote" disabled>Importar selecionada</button>
              <button type="button" class="btn btn-secondary" id="btnClearItems">Limpar itens</button>
            </div>
          </div>
          <div class="grid" style="grid-template-columns: 2fr repeat(4, 1fr) auto; gap:.5rem; align-items:end;">
            <div>
              <label class="muted" for="itemProduto">Produto</label>
              <input id="itemProduto" type="text" placeholder="ID ou nome do produto" list="prodOptions" />
              <datalist id="prodOptions"></datalist>
            </div>
            <div>
              <label class="muted" for="itemQtd">Qtd</label>
              <input id="itemQtd" type="number" step="0.001" min="0" placeholder="0,000" />
            </div>
            <div>
              <label class="muted" for="itemPreco">Preço Unit.</label>
              <input id="itemPreco" type="number" step="0.01" min="0" placeholder="0,00" />
            </div>
            <div>
              <label class="muted" for="itemFrete">Frete</label>
              <input id="itemFrete" type="number" step="0.01" min="0" placeholder="0,00" />
            </div>
            <div>
              <label class="muted" for="itemDesp">Desp. Extras</label>
              <input id="itemDesp" type="number" step="0.01" min="0" placeholder="0,00" />
            </div>
            <div>
              <label class="muted" for="itemEntrega">Entrega</label>
              <input id="itemEntrega" type="date" />
            </div>
            <div style="align-self:center;">
              <button type="button" class="btn btn-secondary" id="btnAddItem">Adicionar</button>
            </div>
          </div>
          <div style="margin-top:.75rem;">
            <table class="table" id="tblItems">
              <thead>
                <tr>
                  <th style="width:48px;">ID</th>
                  <th>Produto</th>
                  <th style="text-align:right;">Qtd</th>
                  <th style="text-align:right;">Preço Unit.</th>
                  <th style="text-align:right;">Frete</th>
                  <th style="text-align:right;">Despesas</th>
                  <th style="text-align:right;">Total</th>
                  <th style="text-align:right;">Entrega</th>
                  <th style="text-align:right;">Ações</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
            <div id="itemsFeedback" class="muted" aria-live="polite"></div>
            <div style="display:flex; justify-content:flex-end; gap:1rem; margin-top:.5rem;">
              <div><strong>Subtotal:</strong> <span id="summarySubtotal">0,00</span></div>
              <div><strong>Frete:</strong> <span id="summaryFreight">0,00</span></div>
              <div><strong>Despesas:</strong> <span id="summaryExtra">0,00</span></div>
              <div><strong>Total:</strong> <span id="summaryTotal">0,00</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="display:flex; gap:.5rem; justify-content:flex-end; margin-top:.75rem;">
      <button type="button" id="btnCreate" disabled title="Preencha fornecedor, empresa/depósito e adicione itens">Criar</button>
      <button type="button" onclick="document.getElementById('newDialog').close()">Fechar</button>
    </div>
  </form>
</dialog>
<script>
async function initNewDialog(){
  try {
    const [empRes, whRes] = await Promise.all([
      apiRequest('/api/cadastros/empresas'),
      apiRequest('/api/wms/warehouses')
    ]);
    const emp = (await empRes.json()).data || [];
    const whs = (await whRes.json()).data || [];
    document.getElementById('newEmpresa').innerHTML = emp.map(e => `<option value="${e.id}">${e.nome||e.name||('ID '+e.id)}</option>`).join('');
    document.getElementById('newDeposito').innerHTML = whs.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  } catch(_){}
}
// Utilitários para itens da ordem
function fmtCurrency(v){ try { return (Number(v||0)).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }); } catch(_) { return String(v); } }
function fmtNumber(v,dec=3){ const n = Number(v||0); return n.toLocaleString('pt-BR', { minimumFractionDigits: dec, maximumFractionDigits: dec }); }
function parseProdInput(val){ const raw = String(val||'').trim(); const id = parseInt(raw.split(' - ')[0], 10); const label = raw.includes(' - ') ? raw.split(' - ').slice(1).join(' - ').trim() : ''; if (!Number.isFinite(id) || id <= 0) return null; return { id, label }; }
async function searchProducts(term){ if (!term || term.length < 2) return []; try { const res = await apiRequest('/api/produtos?q=' + encodeURIComponent(term)); if (!res.ok) return []; const js = await res.json(); const data = js?.data || []; return data.map(p => ({ id: p.id, label: (p.nome||p.descricao||p.codigo||('Produto '+p.id)) })); } catch(_) { return []; } }
function recomputeSummary(){ const rows = document.querySelectorAll('#tblItems tbody tr'); let subtotal=0, freight=0, extra=0; rows.forEach(tr => { const qty = Number(tr.dataset.quantity||0); const price = Number(tr.dataset.unitPrice||0); const fr = Number(tr.dataset.freight||0); const ex = Number(tr.dataset.extraExpenses||0); subtotal += qty*price; freight += fr; extra += ex; }); const sSub = document.getElementById('summarySubtotal'); if (sSub) sSub.textContent = fmtCurrency(subtotal); const sFre = document.getElementById('summaryFreight'); if (sFre) sFre.textContent = fmtCurrency(freight); const sExt = document.getElementById('summaryExtra'); if (sExt) sExt.textContent = fmtCurrency(extra); const sTot = document.getElementById('summaryTotal'); if (sTot) sTot.textContent = fmtCurrency(subtotal+freight+extra); const fb = document.getElementById('itemsFeedback'); if (fb) fb.textContent = rows.length ? `${rows.length} item(ns) adicionados.` : 'Nenhum item adicionado.'; }
function addItemFromInputs(){ const parsed = parseProdInput(document.getElementById('itemProduto').value); if (!parsed){ alert('Selecione um produto válido (use a lista de sugestão).'); return; } const qty = Number(document.getElementById('itemQtd').value||0); const price = Number(document.getElementById('itemPreco').value||0); const fr = Number(document.getElementById('itemFrete').value||0); const ex = Number(document.getElementById('itemDesp').value||0); const dt = String(document.getElementById('itemEntrega').value||'').slice(0,10); if (qty<=0){ alert('Quantidade deve ser positiva.'); return; } if (price<0){ alert('Preço não pode ser negativo.'); return; } if (!dt){ alert('Informe a data de entrega.'); return; } const tbody = document.querySelector('#tblItems tbody'); if (!tbody) return; const total = (qty*price)+fr+ex; const tr = document.createElement('tr'); tr.dataset.productId = String(parsed.id); tr.dataset.productLabel = parsed.label||''; tr.dataset.quantity = String(qty); tr.dataset.unitPrice = String(price); tr.dataset.freight = String(fr); tr.dataset.extraExpenses = String(ex); tr.dataset.deliveryDate = dt; tr.innerHTML = `
  <td>${parsed.id}</td>
  <td>${parsed.label||''}</td>
  <td style="text-align:right;">${fmtNumber(qty,3)}</td>
  <td style="text-align:right;">${fmtCurrency(price)}</td>
  <td style="text-align:right;">${fmtCurrency(fr)}</td>
  <td style="text-align:right;">${fmtCurrency(ex)}</td>
  <td style="text-align:right;">${fmtCurrency(total)}</td>
  <td style="text-align:right;${dt?'':' background-color:#ffeaea;'}">${dt || '<span class=\"muted\">Obrigatória</span>'}</td>
  <td style="text-align:right;"><button type="button" class="btn btn-sm" data-action="editItem">Editar</button> <button type="button" class="btn btn-sm" data-action="removeItem">Remover</button></td>`; tbody.appendChild(tr); document.getElementById('itemProduto').value=''; document.getElementById('itemQtd').value=''; document.getElementById('itemPreco').value=''; document.getElementById('itemFrete').value=''; document.getElementById('itemDesp').value=''; document.getElementById('itemEntrega').value=''; recomputeSummary(); }
document.getElementById('itemProduto').addEventListener('input', async (ev) => { const term = ev.target.value.trim(); const list = document.getElementById('prodOptions'); if (!list) return; list.innerHTML=''; if (term.length<2) return; const items = await searchProducts(term); list.innerHTML = items.slice(0,10).map(p => `<option value="${p.id} - ${p.label}"></option>`).join(''); });
document.getElementById('btnAddItem').addEventListener('click', addItemFromInputs);
// Validação de criação e utilitário para adicionar linha programaticamente
function validateCreate(){ try { const empresa_id = Number(document.getElementById('newEmpresa').value||0); const warehouse_id = Number(document.getElementById('newDeposito').value||0); const supplier_id = Number(document.getElementById('newFornecedor').value||0); const hasItems = document.querySelectorAll('#tblItems tbody tr').length > 0; const btn = document.getElementById('btnCreate'); const ok = (!!empresa_id && !!warehouse_id && !!supplier_id && hasItems); const anyMissingDelivery = Array.from(document.querySelectorAll('#tblItems tbody tr')).some(tr => !(String(tr.dataset.deliveryDate||'').trim())); const finalOk = ok && !anyMissingDelivery; btn.disabled = !finalOk; btn.title = finalOk ? '' : 'Preencha fornecedor, empresa/depósito, adicione itens e defina entrega'; } catch(_){} }
function addItemRow(it){ const tbody = document.querySelector('#tblItems tbody'); if (!tbody) return; const qty = Number(it.quantity||0), price = Number(it.unit_price||0), fr = Number(it.freight||0), ex = Number(it.extra_expenses||0); const dt = String(it.delivery_date||'').slice(0,10); const pid = Number(it.product_id||0); const label = String(it.product_label||'Produto '+pid); if (qty<=0 || pid<=0) return; const total = (qty*price)+fr+ex; const tr = document.createElement('tr'); tr.dataset.productId = String(pid); tr.dataset.productLabel = label||''; tr.dataset.quantity = String(qty); tr.dataset.unitPrice = String(price); tr.dataset.freight = String(fr); tr.dataset.extraExpenses = String(ex); tr.dataset.deliveryDate = dt||''; tr.innerHTML = `
  <td>${pid}</td>
  <td>${label||''}</td>
  <td style="text-align:right;">${fmtNumber(qty,3)}</td>
  <td style="text-align:right;">${fmtCurrency(price)}</td>
  <td style="text-align:right;">${fmtCurrency(fr)}</td>
  <td style="text-align:right;">${fmtCurrency(ex)}</td>
  <td style="text-align:right;">${fmtCurrency(total)}</td>
  <td style="text-align:right;${dt?'':' background-color:#ffeaea;'}">${dt || '<span class=\"muted\">Obrigatória</span>'}</td>
  <td style="text-align:right;"><button type="button" class="btn btn-sm" data-action="editItem">Editar</button> <button type="button" class="btn btn-sm" data-action="removeItem">Remover</button></td>`; tbody.appendChild(tr); }
document.addEventListener('click', (ev) => {
  const btnRem = ev.target.closest('button[data-action="removeItem"]');
  if (btnRem) { const tr = btnRem.closest('tr'); if (tr && tr.parentElement) { tr.parentElement.removeChild(tr); recomputeSummary(); } return; }
  const btnEdit = ev.target.closest('button[data-action="editItem"]');
  if (btnEdit) {
    const tr = btnEdit.closest('tr'); if (!tr) return;
    if (tr.dataset.editing === '1') return;
    tr.dataset.editing = '1';
    const cells = tr.querySelectorAll('td');
    const qty = Number(tr.dataset.quantity||0), price = Number(tr.dataset.unitPrice||0), fr = Number(tr.dataset.freight||0), ex = Number(tr.dataset.extraExpenses||0);
    const ddt = String(tr.dataset.deliveryDate||'');
    cells[2].innerHTML = `<input type="number" step="0.001" min="0" value="${qty}" style="width:100px; text-align:right;" />`;
    cells[3].innerHTML = `<input type="number" step="0.01" min="0" value="${price}" style="width:120px; text-align:right;" />`;
    cells[4].innerHTML = `<input type="number" step="0.01" min="0" value="${fr}" style="width:100px; text-align:right;" />`;
    cells[5].innerHTML = `<input type="number" step="0.01" min="0" value="${ex}" style="width:100px; text-align:right;" />`;
    cells[6].textContent = fmtCurrency((qty*price)+fr+ex);
    cells[7].innerHTML = `<input type="date" value="${ddt}" style="width:140px; text-align:right;" />`;
    cells[8].innerHTML = `<button type="button" class="btn btn-sm" data-action="saveItem">Salvar</button> <button type="button" class="btn btn-sm" data-action="cancelEdit">Cancelar</button>`;
  }
  const btnSave = ev.target.closest('button[data-action="saveItem"]');
  if (btnSave) {
    const tr = btnSave.closest('tr'); if (!tr) return;
    const cells = tr.querySelectorAll('td');
    const newQty = Number(cells[2].querySelector('input')?.value||0);
    const newPrice = Number(cells[3].querySelector('input')?.value||0);
    const newFr = Number(cells[4].querySelector('input')?.value||0);
    const newEx = Number(cells[5].querySelector('input')?.value||0);
    const newDt = String(cells[7].querySelector('input')?.value||'').slice(0,10);
    if (newQty<=0){ alert('Quantidade deve ser positiva.'); return; }
    if (newPrice<0 || newFr<0 || newEx<0){ alert('Valores não podem ser negativos.'); return; }
    if (!newDt){ alert('Informe a data de entrega.'); return; }
    tr.dataset.quantity = String(newQty);
    tr.dataset.unitPrice = String(newPrice);
    tr.dataset.freight = String(newFr);
    tr.dataset.extraExpenses = String(newEx);
    tr.dataset.deliveryDate = newDt;
    // Re-render row to view mode
    const total = (newQty*newPrice)+newFr+newEx;
    cells[2].innerHTML = `${fmtNumber(newQty,3)}`;
    cells[3].innerHTML = `${fmtCurrency(newPrice)}`;
    cells[4].innerHTML = `${fmtCurrency(newFr)}`;
    cells[5].innerHTML = `${fmtCurrency(newEx)}`;
    cells[6].innerHTML = `${fmtCurrency(total)}`;
    cells[7].innerHTML = `${newDt}`;
    cells[7].style.backgroundColor = '';
    cells[8].innerHTML = `<button type="button" class="btn btn-sm" data-action="editItem">Editar</button> <button type="button" class="btn btn-sm" data-action="removeItem">Remover</button>`;
    tr.dataset.editing = '';
    recomputeSummary();
  }
  const btnCancel = ev.target.closest('button[data-action="cancelEdit"]');
  if (btnCancel) {
    const tr = btnCancel.closest('tr'); if (!tr) return;
    const cells = tr.querySelectorAll('td');
    const qty = Number(tr.dataset.quantity||0), price = Number(tr.dataset.unitPrice||0), fr = Number(tr.dataset.freight||0), ex = Number(tr.dataset.extraExpenses||0);
    const ddt = String(tr.dataset.deliveryDate||'');
    const total = (qty*price)+fr+ex;
    cells[2].innerHTML = `${fmtNumber(qty,3)}`;
    cells[3].innerHTML = `${fmtCurrency(price)}`;
    cells[4].innerHTML = `${fmtCurrency(fr)}`;
    cells[5].innerHTML = `${fmtCurrency(ex)}`;
    cells[6].innerHTML = `${fmtCurrency(total)}`;
    cells[7].innerHTML = `${ddt ? ddt : '<span class=\"muted\">Obrigatória</span>'}`;
    cells[7].style.backgroundColor = ddt ? '' : '#ffeaea';
    cells[8].innerHTML = `<button type="button" class="btn btn-sm" data-action="editItem">Editar</button> <button type="button" class="btn btn-sm" data-action="removeItem">Remover</button>`;
    tr.dataset.editing = '';
  }
});
// Importar itens de cotação
document.getElementById('btnImportQuote').addEventListener('click', async () => {
  const idStr = prompt('Informe o ID da cotação para importar:');
  const qid = parseInt(String(idStr||'').trim(), 10);
  if (!Number.isFinite(qid) || qid <= 0) { return; }
  try {
    const res = await apiRequest(`/api/compras/cotacoes/${qid}`);
    if (!res.ok) { alert('Cotação não encontrada ou erro ao carregar'); return; }
    const js = await res.json(); const q = js?.data || {};
    const items = Array.isArray(q.items) ? q.items : [];
    if (items.length === 0) { alert('Cotação sem itens.'); return; }
    const uniqIds = Array.from(new Set(items.map(i => Number(i.product_id||0)).filter(v => v>0)));
    const labels = {};
    await Promise.all(uniqIds.map(async pid => {
      try { const r = await apiRequest(`/api/produtos/${pid}`); if (r.ok) { const jj = await r.json(); const d = jj?.data || {}; labels[pid] = (d.nome||d.descricao||d.codigo||('Produto '+pid)); } } catch(_){ labels[pid] = 'Produto '+pid; }
    }));
    items.forEach(it => {
      addItemRow({ product_id: it.product_id, quantity: it.quantity, unit_price: it.price, freight: 0, extra_expenses: 0, delivery_date: '', product_label: labels[Number(it.product_id)||0] });
    });
    recomputeSummary();
    validateCreate();
    const qb = document.getElementById('modalCotacaoBadge'); if (qb) qb.textContent = 'Cotação: #' + qid;
    alert(`${items.length} item(ns) importados da cotação #${qid}.`);
  } catch(e) { alert('Erro ao importar cotação: ' + e.message); }
});
// Buscar cotações por fornecedor e importar selecionada
async function fetchSupplierQuotes(){ try { const supId = Number(document.getElementById('newFornecedor').value||0); const sel = document.getElementById('quoteSelect'); const btnImpSel = document.getElementById('btnImportSelectedQuote'); sel.innerHTML = '<option value="">Cotações do fornecedor</option>'; sel.disabled = true; btnImpSel.disabled = true; if (!supId) return; const res = await apiRequest('/api/compras/cotacoes?supplier_id=' + supId + '&status=open&per_page=50'); if (!res.ok) return; const js = await res.json(); const data = js?.data || []; sel.innerHTML = '<option value="">Selecione uma cotação</option>' + data.map(c => `<option value="${c.id}">#${c.id} • ${c.status||''} • ${String(c.created_at||'').slice(0,10)}</option>`).join(''); sel.disabled = false; } catch(_){} }
document.getElementById('quoteSelect').addEventListener('change', (ev) => { const v = ev.target.value; document.getElementById('btnImportSelectedQuote').disabled = !v; });
document.getElementById('btnImportSelectedQuote').addEventListener('click', async () => { const qid = parseInt(String(document.getElementById('quoteSelect').value||'').trim(), 10); if (!Number.isFinite(qid) || qid<=0) return; try { const res = await apiRequest(`/api/compras/cotacoes/${qid}`); if (!res.ok) { alert('Cotação não encontrada ou erro ao carregar'); return; } const js = await res.json(); const q = js?.data || {}; const items = Array.isArray(q.items) ? q.items : []; if (items.length === 0) { alert('Cotação sem itens.'); return; } const uniqIds = Array.from(new Set(items.map(i => Number(i.product_id||0)).filter(v => v>0))); const labels = {}; await Promise.all(uniqIds.map(async pid => { try { const r = await apiRequest(`/api/produtos/${pid}`); if (r.ok) { const jj = await r.json(); const d = jj?.data || {}; labels[pid] = (d.nome||d.descricao||d.codigo||('Produto '+pid)); } } catch(_){ labels[pid] = 'Produto '+pid; } })); items.forEach(it => { addItemRow({ product_id: it.product_id, quantity: it.quantity, unit_price: it.price, freight: 0, extra_expenses: 0, delivery_date: '', product_label: labels[Number(it.product_id)||0] }); }); recomputeSummary(); validateCreate(); const qb = document.getElementById('modalCotacaoBadge'); if (qb) qb.textContent = 'Cotação: #' + qid; alert(`${items.length} item(ns) importados da cotação #${qid}.`); } catch(e) { alert('Erro ao importar cotação: ' + e.message); } });
// Limpar todos os itens
document.getElementById('btnClearItems').addEventListener('click', () => { const tbody = document.querySelector('#tblItems tbody'); if (!tbody) return; if (!confirm('Remover todos os itens da ordem?')) return; tbody.innerHTML = ''; recomputeSummary(); validateCreate(); });
document.getElementById('btnNew').addEventListener('click', initNewDialog);
document.getElementById('btnCreate').addEventListener('click', async () => {
  try {
    const empresa_id = Number(document.getElementById('newEmpresa').value || 0);
    const warehouse_id = Number(document.getElementById('newDeposito').value || 0);
    const supplier_id = Number(document.getElementById('newFornecedor').value || 0);
    const operacao = document.getElementById('newOperacao').value || 'compra';
    const condicao_pagamento = document.getElementById('newCondPag').value || '';
    const condicao_entrega = document.getElementById('newCondEnt').value || '';
    const observacoes = document.getElementById('newObs').value || '';
    const rows = Array.from(document.querySelectorAll('#tblItems tbody tr'));
    if (!rows.length) { alert('Adicione pelo menos um item à ordem.'); return; }
    const items = rows.map(tr => ({
      product_id: Number(tr.dataset.productId||0),
      quantity: Number(tr.dataset.quantity||0),
      unit_price: Number(tr.dataset.unitPrice||0),
      freight: Number(tr.dataset.freight||0),
      extra_expenses: Number(tr.dataset.extraExpenses||0),
      delivery_date: String(tr.dataset.deliveryDate||'')
    })).filter(i => i.product_id>0 && i.quantity>0);
    const body = { empresa_id, warehouse_id, supplier_id, operacao, condicao_pagamento, condicao_entrega, observacoes, items };
    const res = await apiRequest('/api/compras/ordens', { method: 'POST', body: JSON.stringify(body) });
    if (!res.ok) { const er = await res.json().catch(()=>({error:'Falha'})); alert(er.error?.message || er.error || 'Falha ao criar ordem'); return; }
    document.getElementById('newDialog').close();
    await loadOrders();
  } catch(_) { alert('Erro ao criar ordem'); }
});
// Autocomplete de fornecedor
async function searchSuppliers(term){ try { const res = await apiRequest('/api/compras/fornecedores?per_page=50'); if (!res.ok) return []; const js = await res.json(); const data = js?.data || []; const t = String(term||'').toLowerCase(); return data.filter(s => String(s.nome||'').toLowerCase().includes(t) || String(s.cnpj||'').includes(t)).map(s => ({ id:s.id, label:`${s.nome||''} ${s.cnpj?('('+s.cnpj+')'):''}`.trim() })); } catch(_) { return []; } }
document.getElementById('newFornecedorInput').addEventListener('input', async (ev) => { const term = ev.target.value.trim(); const list = document.getElementById('supOptions'); list.innerHTML=''; if (term.length<2) { document.getElementById('newFornecedor').value=''; return; } const items = await searchSuppliers(term); list.innerHTML = items.slice(0,10).map(s => `<option value="${s.id} - ${s.label}"></option>`).join(''); });
document.getElementById('newFornecedorInput').addEventListener('change', (ev) => { const val = String(ev.target.value||''); const id = parseInt(val.split(' - ')[0], 10); document.getElementById('newFornecedor').value = Number.isFinite(id) ? String(id) : ''; updateHeaderContext(); validateCreate(); fetchSupplierQuotes(); const qb = document.getElementById('modalCotacaoBadge'); if (qb) qb.textContent = 'Cotação: —'; });
// Presets de pagamento/entrega
document.getElementById('newCondPagPreset').addEventListener('change', (ev) => { const v = ev.target.value; if (v) document.getElementById('newCondPag').value = v; });
document.getElementById('newCondEntPreset').addEventListener('change', (ev) => { const v = ev.target.value; if (v) document.getElementById('newCondEnt').value = v; });
// Atualizar badges do cabeçalho com resumo
const summaryObserver = new MutationObserver(() => { const rows = document.querySelectorAll('#tblItems tbody tr'); const count = rows.length; const totalText = document.getElementById('summaryTotal')?.textContent || 'R$ 0,00'; const ic = document.getElementById('modalItemsCount'); const tb = document.getElementById('modalTotalBadge'); if (ic) ic.textContent = `${count} ${count===1?'item':'itens'}`; if (tb) tb.textContent = `Total: ${totalText}`; validateCreate(); });
summaryObserver.observe(document.getElementById('summaryTotal'), { characterData: true, subtree: true, childList: true });
// Cabeçalho: badges de fornecedor/empresa/depósito
const headerCtxInit = (() => {
  const hdr = document.querySelector('#newDialog .modal-header');
  if (hdr && !hdr.querySelector('#modalContextBadges')) {
    const div = document.createElement('div');
    div.id = 'modalContextBadges';
    div.style.display = 'flex'; div.style.gap = '.5rem'; div.style.alignItems = 'center';
    div.innerHTML = '<span class="badge" id="modalSupplierBadge">Fornecedor: —</span><span class="badge" id="modalEmpresaBadge">Empresa: —</span><span class="badge" id="modalDepositoBadge">Depósito: —</span><span class="badge" id="modalCotacaoBadge">Cotação: —</span>';
    hdr.appendChild(div);
  }
})();
function updateHeaderContext(){ try {
  const supInput = document.getElementById('newFornecedorInput');
  const supBadge = document.getElementById('modalSupplierBadge');
  if (supInput && supBadge) { const txt = supInput.value || ''; const name = txt.includes(' - ') ? txt.split(' - ').slice(1).join(' - ').trim() : txt; supBadge.textContent = 'Fornecedor: ' + (name || '—'); }
  const selEmp = document.getElementById('newEmpresa');
  const empBadge = document.getElementById('modalEmpresaBadge');
  if (selEmp && empBadge) { const name = selEmp.options[selEmp.selectedIndex]?.text || ''; empBadge.textContent = 'Empresa: ' + (name || '—'); }
  const selDep = document.getElementById('newDeposito');
  const depBadge = document.getElementById('modalDepositoBadge');
  if (selDep && depBadge) { const name = selDep.options[selDep.selectedIndex]?.text || ''; depBadge.textContent = 'Depósito: ' + (name || '—'); }
} catch(_){} }
document.getElementById('newEmpresa').addEventListener('change', () => { updateHeaderContext(); validateCreate(); });
document.getElementById('newDeposito').addEventListener('change', () => { updateHeaderContext(); validateCreate(); });
document.getElementById('btnNew').addEventListener('click', () => { setTimeout(() => { updateHeaderContext(); validateCreate(); }, 100); });
</script>
</script>