<?php /* Resposta de Cotação pelo Fornecedor (pública via token) */ ?>
<div class="card" style="max-width: 860px; margin: 0 auto;">
  <h1><?= htmlspecialchars($title ?? 'Responder Cotação') ?></h1>
  <p class="muted">Use o link enviado por email. Esta página não requer login.</p>
  <div id="feedback" class="alert" style="display:none;"></div>
  <div id="content" style="display:none;">
    <div class="form-group">
      <label>Fornecedor</label>
      <input id="supplier" type="text" disabled>
    </div>
    <div class="form-group">
      <label>Cotação</label>
      <input id="quoteInfo" type="text" disabled>
    </div>
    <table class="table">
      <thead>
        <tr><th>Item</th><th>Produto</th><th>Quantidade</th><th>Seu Preço</th></tr>
      </thead>
      <tbody id="items"></tbody>
    </table>
    <div style="display:flex; gap:0.5rem; justify-content:flex-end; margin-top:1rem;">
      <button id="btnSubmit" class="btn">Enviar Resposta</button>
    </div>
  </div>
</div>

<script>
function qs(name){ const p=new URLSearchParams(location.search); return p.get(name)||''; }
function getCookie(name){ const m = document.cookie.match(new RegExp('(?:^|; )'+name+'=([^;]+)')); return m ? decodeURIComponent(m[1]) : ''; }
async function api(url, opts={}){
  const params = new URLSearchParams(location.search);
  const tenantFromLink = params.get('tenant');
  const tenant = tenantFromLink || getCookie('x-tenant-id') || 'default';
  const baseHeaders = { 'Content-Type': 'application/json', 'x-tenant-id': tenant };
  const res = await fetch(url, { ...opts, headers: { ...baseHeaders, ...(opts.headers||{}) }, credentials: 'same-origin', cache: 'no-store' });
  return res;
}
function showMsg(type, msg){ const fb=document.getElementById('feedback'); fb.className = 'alert ' + (type==='error'?'alert-error':'alert-success'); fb.textContent=msg; fb.style.display='block'; }

const token = qs('token');
let inviteData = null;

// Garantir tenant correto via parâmetro do link
const params = new URLSearchParams(location.search);
const tenantFromLink = params.get('tenant');
if (tenantFromLink) {
  try {
    document.cookie = 'x-tenant-id=' + tenantFromLink + '; path=/; max-age=' + (60*60*24*30);
  } catch(e) {}
}

async function load(){
  if (!token) { showMsg('error','Token ausente do link.'); return; }
  const res = await api('/api/compras/cotacoes/responder?token=' + encodeURIComponent(token));
  if (!res.ok) { showMsg('error','Convite inválido ou expirado.'); return; }
  const json = await res.json(); inviteData = json.data;
  document.getElementById('supplier').value = inviteData.invite.email + ' (ID ' + inviteData.invite.supplier_id + ')';
  document.getElementById('quoteInfo').value = '#' + inviteData.quote.id + ' · status ' + inviteData.quote.status;
  const tbody = document.getElementById('items'); tbody.innerHTML='';
  for (const it of inviteData.items){
    const tr = document.createElement('tr');
    tr.innerHTML = `<td>${it.id}</td><td>${it.product_id}</td><td>${it.quantity}</td>
      <td><input type="number" step="0.01" min="0" data-item-id="${it.id}" placeholder="Informe o preço" style="width:140px"></td>`;
    tbody.appendChild(tr);
  }
  document.getElementById('content').style.display='block';
}

document.addEventListener('click', async (ev)=>{
  const btn = ev.target.closest('#btnSubmit'); if (!btn) return;
  const inputs = Array.from(document.querySelectorAll('input[data-item-id]'));
  const offers = inputs.map(i => ({ item_id: parseInt(i.getAttribute('data-item-id'),10), price: parseFloat(i.value||'0') }));
  if (offers.some(o => !(o.price>0))) { showMsg('error','Preencha todos os preços com valores maiores que zero.'); return; }
  const res = await api('/api/compras/cotacoes/responder', { method: 'POST', body: JSON.stringify({ token, offers }) });
  if (res.ok) { showMsg('success','Resposta enviada com sucesso. Obrigado!'); btn.disabled=true; }
  else { showMsg('error','Falha ao enviar resposta.'); }
});

setTimeout(load,50);
</script>