<?php /* Movimentações WMS */ ?>
<div class="card">
  <h1><?= htmlspecialchars($title ?? 'Movimentações WMS') ?></h1>
  <div style="display:flex; gap:0.5rem; align-items:center; margin-bottom:1rem;">
    <input id="q" type="text" placeholder="Buscar por produto ou endereço (bin)" style="flex:1; padding:0.5rem;" title="Digite parte do nome do produto ou código do endereço">
    <label for="wmsSep" class="muted">Separador:</label>
    <select id="wmsSep" style="padding:0.4rem;">
      <option value=";">Ponto e vírgula</option>
      <option value=",">Vírgula</option>
      <option value="\t">Tabulação</option>
    </select>
    <input id="start" type="datetime-local" style="padding:0.4rem;" />
    <input id="end" type="datetime-local" style="padding:0.4rem;" />
    <button id="btnExportWms" class="btn">Exportar CSV</button>
    <button id="btnTransfer" class="btn">Transferir Produto</button>
  </div>
  <div id="feedback" class="muted" aria-live="polite"></div>
  <table class="table" id="tbl">
    <thead>
      <tr><th>ID</th><th>Produto</th><th>Origem</th><th>Destino</th><th>Quantidade</th><th>Data</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 = [];
let productNameMap = new Map();

function renderRows(rows) {
  const tbody = document.getElementById('rows');
  tbody.innerHTML = '';
  for (const r of rows) {
    const tr = document.createElement('tr');
    const pnome = productNameMap.get(r.product_id) || r.product_name || r.codigo || r.product_id;
    const qtd = window.fmtQty ? window.fmtQty(r.quantity) : String(Math.trunc(Number(r.quantity||0)));
    const data = window.fmtDateTimeBR ? window.fmtDateTimeBR(r.created_at) : String((r.created_at||'').replace('T',' ').slice(0,19));
    tr.innerHTML = `
      <td>${r.id}</td>
      <td>${pnome}</td>
      <td>${r.from_bin_id}</td>
      <td>${r.to_bin_id}</td>
      <td>${qtd}</td>
      <td>${data}</td>`;
    tbody.appendChild(tr);
  }
}
async function loadMovements() {
  const fb = document.getElementById('feedback'); fb.textContent = 'Carregando…';
  try {
    const res = await apiRequest('/api/wms/movements');
    if (!res.ok) throw new Error('Falha ao carregar');
    const json = await res.json();
    currentRows = json.data || [];
    // Enriquecer nomes de produtos (cache)
    try {
      const unique = Array.from(new Set(currentRows.map(r => r.product_id).filter(Boolean)));
      await Promise.all(unique.map(async pid => {
        if (productNameMap.has(pid)) return;
        try {
          const pr = await apiRequest(`/api/produtos/${pid}`);
          if (pr && pr.ok) {
            const pj = await pr.json(); const d = pj.data || {};
            let nome = d.descricao || d.nome || '';
            if (!nome && d.meta_json) { try { const meta = JSON.parse(d.meta_json); nome = meta.nome || meta.name || ''; } catch(_){} }
            if (!nome) nome = d.codigo || String(pid);
            productNameMap.set(pid, nome);
          } else { productNameMap.set(pid, String(pid)); }
        } catch(_) { productNameMap.set(pid, String(pid)); }
      }));
    } catch(_) {}
    renderRows(currentRows);
    fb.textContent = `${currentRows.length} movimentação(ões) carregadas.`;
  } catch (e) { fb.textContent = 'Erro: ' + e.message; }
}
document.getElementById('btnExportWms').addEventListener('click', function() {
  const sep = document.getElementById('wmsSep').value || ';';
  const q = document.getElementById('q').value || '';
  const start = document.getElementById('start').value || '';
  const end = document.getElementById('end').value || '';
  const params = new URLSearchParams({ sep, q });
  if (start) params.set('start', start);
  if (end) params.set('end', end);
  const url = `/api/wms/movements/export.csv?${params.toString()}`;
  const a = document.createElement('a');
  a.href = url;
  a.download = `wms_movimentacoes_${Date.now()}.csv`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
});
document.getElementById('q').addEventListener('input', () => {
  const q = document.getElementById('q').value.trim().toLowerCase();
  const start = document.getElementById('start').value || '';
  const end = document.getElementById('end').value || '';
  const rows = currentRows.filter(r => {
    const pnome = productNameMap.get(r.product_id) || '';
    const matchQ = (!q) || pnome.toLowerCase().includes(q) || String(r.product_id||'').toLowerCase().includes(q) || String(r.from_bin_id||'').toLowerCase().includes(q) || String(r.to_bin_id||'').toLowerCase().includes(q);
    const dtRow = new Date(r.created_at || '');
    const startDt = start ? new Date(start) : null;
    const endDt = end ? new Date(end) : null;
    const afterStart = !startDt || (!isNaN(dtRow) && dtRow >= startDt);
    const beforeEnd = !endDt || (!isNaN(dtRow) && dtRow <= endDt);
    return matchQ && afterStart && beforeEnd;
  });
  renderRows(rows);
});
document.getElementById('btnTransfer').addEventListener('click', async () => {
  const pid = prompt('Produto ID?'); const fromId = prompt('Bin origem ID?'); const toId = prompt('Bin destino ID?'); const qty = prompt('Quantidade?');
  if (!pid || !fromId || !toId || !qty) return;
  const body = { product_id: Number(pid), from_bin_id: Number(fromId), to_bin_id: Number(toId), quantity: Number(qty) };
  const res = await apiRequest('/api/wms/movements/transfer', { method: 'POST', body: JSON.stringify(body) });
  if (res.ok) { await loadMovements(); } else { alert('Falha na transferência'); }
});
setTimeout(loadMovements, 50);
</script>
<hr/>
<h2>Recebimento/Expedição (PWA)</h2>
<div id="opsSection">
  <div style="margin-bottom:8px;">
    <input id="opsQ" type="text" placeholder="Buscar por código de produto" style="width:260px;" />
    <button id="btnReloadOps" class="btn">Recarregar</button>
    <span id="opsFeedback" style="margin-left:8px;color:#555;"></span>
  </div>
  <div style="display:flex; gap:16px; align-items:flex-start;">
    <div style="flex:1;">
      <h3>Recebimento (raw)</h3>
      <table class="table" id="tblRecv">
        <thead>
          <tr>
            <th>ID</th><th>Código</th><th>Qtd</th><th>Origem</th><th>Status</th><th>Data</th>
          </tr>
        </thead>
        <tbody id="tbRecv"></tbody>
      </table>
      <div><small><span id="recvCount">0</span> recebimento(s) exibidos.</small></div>
    </div>
    <div style="flex:1;">
      <h3>Expedição (raw)</h3>
      <table class="table" id="tblShip">
        <thead>
          <tr>
            <th>ID</th><th>Código</th><th>Qtd</th><th>Destino</th><th>Status</th><th>Data</th>
          </tr>
        </thead>
        <tbody id="tbShip"></tbody>
      </table>
      <div><small><span id="shipCount">0</span> expedição(ões) exibidas.</small></div>
    </div>
  </div>
</div>
<script>
async function loadOps() {
  const fb = document.getElementById('opsFeedback');
  const q = document.getElementById('opsQ').value.trim();
  fb.textContent = 'Carregando recebimento/expedição...';
  try {
    const qs = q ? `&q=${encodeURIComponent(q)}` : '';
    const recvResp = await fetch(`/api/wms/mobile/receiving?per_page=50${qs}`);
    const shipResp = await fetch(`/api/wms/mobile/shipping?per_page=50${qs}`);
    if (!recvResp.ok || !shipResp.ok) throw new Error('Falha ao consultar endpoints');
    const recv = await recvResp.json();
    const ship = await shipResp.json();
    const tbRecv = document.getElementById('tbRecv');
    const tbShip = document.getElementById('tbShip');
    tbRecv.innerHTML = '';
    tbShip.innerHTML = '';
    (recv.rows || []).forEach(r => {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${r.id}</td><td>${r.product_code||r.product_id||''}</td><td>${r.quantity}</td><td>${r.origin||''}</td><td>${r.status}</td><td>${r.created_at}</td>`;
      tbRecv.appendChild(tr);
    });
    (ship.rows || []).forEach(r => {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${r.id}</td><td>${r.product_code||r.product_id||''}</td><td>${r.quantity}</td><td>${r.dest||''}</td><td>${r.status}</td><td>${r.created_at}</td>`;
      tbShip.appendChild(tr);
    });
    document.getElementById('recvCount').textContent = (recv.rows||[]).length;
    document.getElementById('shipCount').textContent = (ship.rows||[]).length;
    fb.textContent = 'Dados atualizados.';
  } catch (e) {
    fb.textContent = 'Erro: ' + e.message;
  }
}
document.getElementById('btnReloadOps').addEventListener('click', loadOps);
document.getElementById('opsQ').addEventListener('input', () => { loadOps(); });
window.addEventListener('load', loadOps);
</script>