<?php /* Vendas > Impressão de Orçamento (layout profissional) */ ?>
<style>
  :root {
    --fg: #1f2937; /* gray-800 */
    --muted: #6b7280; /* gray-500 */
    --accent: #0ea5e9; /* sky-500 */
    --border: #e5e7eb; /* gray-200 */
    --bg: #ffffff;
  }
  .print-wrap { max-width: 900px; margin: 0 auto; color: var(--fg); }
  .doc { background: var(--bg); border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
  .doc-header { display: grid; grid-template-columns: 140px 1fr; gap: 16px; padding: 24px; border-bottom: 2px solid var(--border); }
  .brand { display:flex; align-items:center; gap:12px; }
  .brand img { max-height: 90px; object-fit: contain; }
  .brand .title { font-size: 20px; font-weight: 700; }
  .company-info { font-size: 13px; line-height: 1.5; }
  .doc-meta { display:grid; grid-template-columns: repeat(3, minmax(0,1fr)); gap: 12px; padding: 16px 24px; background: #f9fafb; border-bottom: 1px solid var(--border); }
  .doc-meta .card { background:#fff; border:1px solid var(--border); border-radius:8px; padding:12px; }
  .doc-meta .label { color: var(--muted); font-size: 12px; }
  .doc-meta .value { font-weight: 600; font-size: 14px; }
  .section { padding: 20px 24px; }
  .section h3 { margin:0 0 8px 0; font-size: 16px; }
  .grid-2 { display:grid; grid-template-columns: 1.4fr 1fr; gap: 16px; }
  .box { border:1px solid var(--border); border-radius:8px; padding:12px; background:#fff; }
  .muted { color: var(--muted); }
  .table-responsive { overflow-x:auto; }
  table.doc-table { width:100%; border-collapse: collapse; min-width: 700px; }
  table.doc-table thead th { text-align:left; font-size:12px; color:var(--muted); border-bottom:2px solid var(--border); padding:8px; }
  table.doc-table tbody td { padding:8px; border-bottom:1px solid var(--border); font-size:13px; }
  table.doc-table tbody tr:nth-child(odd) { background:#fcfdff; }
  .totals { display:grid; grid-template-columns: 1fr 260px; gap:16px; align-items:start; margin-top:8px; }
  .totals .summary { border:2px solid var(--accent); border-radius:10px; padding:12px; background:#f0f9ff; }
  .totals .summary .row { display:flex; justify-content:space-between; padding:6px 0; }
  .totals .summary .row.total { font-weight:700; font-size:16px; }
  .actions { display:flex; justify-content:space-between; gap:8px; padding:16px 0; }
  .btn { appearance:none; border:1px solid var(--border); background:#fff; border-radius:8px; padding:8px 12px; cursor:pointer; }
  .btn-primary { background: var(--accent); color:#fff; border-color: var(--accent); }
  .highlight { background:#fef3c7; border:1px solid #f59e0b; border-radius:8px; padding:10px; }
  @media print {
    @page { size: A4; margin: 12mm; }
    .actions, nav.breadcrumb { display:none !important; }
    body { margin:0; background:#fff; }
    .doc { box-shadow:none; border:0; }
    .print-wrap { max-width: unset; }
  }
</style>

<nav class="breadcrumb" style="display:flex;align-items:center;gap:.5rem; margin-bottom:.75rem;">
  <a href="/vendas/orcamentos" class="btn">Voltar</a>
  <span class="muted">Impressão de Orçamento</span>
  <div style="margin-left:auto; display:flex; gap:.5rem;">
    <button class="btn btn-primary" onclick="window.print()">Imprimir / PDF</button>
  </div>
  <input type="hidden" id="__docId" value="<?= htmlspecialchars((string)($id ?? 0)) ?>" />
</nav>

<div class="print-wrap">
  <div class="doc" id="docQuote">
    <div class="doc-header">
      <div class="brand">
        <img id="companyLogo" alt="Logo" />
        <div>
          <div class="title" id="companyName">Empresa</div>
          <div class="muted" id="companyTag">Orçamento comercial</div>
        </div>
      </div>
      <div class="company-info" id="companyInfo">Carregando dados da empresa...</div>
    </div>

    <div class="doc-meta">
      <div class="card">
        <div class="label">Número</div>
        <div class="value" id="docNumero">-</div>
      </div>
      <div class="card">
        <div class="label">Data de Emissão</div>
        <div class="value" id="docEmissao">-</div>
      </div>
      <div class="card">
        <div class="label">Validade</div>
        <div class="value"><span id="docValidade">30 dias</span></div>
      </div>
    </div>

    <div class="section grid-2">
      <div class="box">
        <h3>Dados do Cliente</h3>
        <div id="clientInfo" class="muted">Carregando cliente...</div>
      </div>
      <div class="box">
        <h3>Condições de Pagamento</h3>
        <div class="muted">Edite antes de imprimir</div>
        <textarea id="condPagamento" rows="4" style="width:100%;"></textarea>
      </div>
    </div>

    <div class="section">
      <h3>Produtos/Serviços</h3>
      <div class="table-responsive">
        <table class="doc-table" id="itemsTable">
          <thead>
            <tr>
              <th style="width:12%">Código</th>
              <th>Descrição</th>
              <th style="width:10%; text-align:right;">Un.</th>
              <th style="width:10%; text-align:right;">Qtd</th>
              <th style="width:14%; text-align:right;">Preço</th>
              <th style="width:14%; text-align:right;">Total</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>

      <div class="totals">
        <div></div>
        <div class="summary" id="totalsBox">
          <div class="row"><span>Subtotal</span><strong id="subTotal">R$ 0,00</strong></div>
          <div class="row"><span>Descontos</span><strong id="descontos">R$ 0,00</strong></div>
          <div class="row total"><span>Total</span><strong id="valorTotal">R$ 0,00</strong></div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="highlight">
        <strong>Observações importantes:</strong>
        <div id="docObservacoes" class="muted">Preços sujeitos à atualização. Imagens meramente ilustrativas.</div>
      </div>
    </div>
  </div>
  <div class="actions">
    <span class="muted">Revise os campos editáveis antes de imprimir.</span>
    <div style="display:flex; gap:.5rem;">
      <button class="btn" onclick="history.back()">Voltar</button>
      <button class="btn btn-primary" onclick="window.print()">Imprimir / PDF</button>
    </div>
  </div>
</div>

<script>
async function apiRequest(url, opts){
  const r = await fetch(url, { credentials: 'include', ...opts });
  return r;
}
function fmtCurrency(v){ return (Number(v||0)).toLocaleString('pt-BR', { style:'currency', currency:'BRL' }); }
function fmtDate(s){ try { return new Date(String(s)).toLocaleDateString('pt-BR'); } catch(_){ return String(s||''); } }

(async function init(){
  const id = Number(document.getElementById('__docId').value||0);
  if (!id) { alert('ID do orçamento inválido'); return; }

  // Empresa
  try {
    const cr = await apiRequest('/api/admin/tenants/summary');
    if (cr && cr.ok) { const cj = await cr.json(); const c = cj.data||cj||{};
      document.getElementById('companyName').textContent = c.razao_social || c.name || 'Empresa';
      const infoParts = [];
      if (c.cnpj) infoParts.push('CNPJ: ' + c.cnpj);
      if (c.inscricao_estadual) infoParts.push('IE: ' + c.inscricao_estadual);
      if (c.endereco) infoParts.push(String(c.endereco));
      document.getElementById('companyInfo').textContent = infoParts.join(' • ');
      const logoEl = document.getElementById('companyLogo');
      const logo = c.logo_url || c.logo || '';
      if (logo) { logoEl.src = logo; } else { logoEl.style.display = 'none'; }
    }
  } catch(_){ }

  // Orçamento
  const resp = await apiRequest(`/api/vendas/orcamentos/${id}`);
  if (!resp.ok) { alert('Falha ao carregar orçamento'); return; }
  const data = await resp.json();
  const quote = data.data?.quote || data.data || {};
  const items = data.data?.items || quote.items || [];

  document.getElementById('docNumero').textContent = String(quote.numero || quote.id);
  document.getElementById('docEmissao').textContent = fmtDate(quote.created_at);
  document.getElementById('docValidade').textContent = quote.validade ? String(quote.validade) : '30 dias';
  document.getElementById('docObservacoes').textContent = String(quote.obs || quote.observacoes || '');

  // Cliente
  let clientText = 'Cliente não informado';
  if (quote.cliente_id) {
    try { const cr = await apiRequest(`/api/clientes/${quote.cliente_id}`);
      if (cr && cr.ok) { const cj = await cr.json(); const c = cj.data||{};
        clientText = `${c.nome||'-'}\n${c.cnpj||c.cpf ? ('CNPJ/CPF: ' + (c.cnpj||c.cpf)) : ''}`;
        const addr = (c.enderecos&&c.enderecos.principal)||{};
        const addrTxt = [addr.logradouro, addr.numero, addr.bairro, addr.cidade, addr.estado].filter(Boolean).join(', ');
        if (addrTxt) clientText += `\n${addrTxt}`;
        if (c.email) clientText += `\n${c.email}`;
        if (c.telefone) clientText += `\n${c.telefone}`;
      }
    } catch(_){ }
  }
  document.getElementById('clientInfo').textContent = clientText;

  // Itens: enriquecer com produto
  const tbody = document.querySelector('#itemsTable tbody');
  let subtotal = 0;
  for (const it of (items||[])) {
    let codigo = `PROD${it.product_id}`; let nome = `Produto ${it.product_id}`; let un = 'UN';
    try {
      const pr = await apiRequest(`/api/produtos/${it.product_id}`);
      if (pr && pr.ok) { const pj = await pr.json(); const p = pj.data||{}; codigo = p.codigo||codigo; nome = p.nome||nome; un = p.unidade||un; }
    } catch(_){ }
    const qtd = Number(it.quantidade||0); const preco = Number(it.preco||0); const total = Number(it.total||qtd*preco);
    subtotal += total;
    const tr = document.createElement('tr');
    tr.innerHTML = `<td>${codigo}</td><td>${nome}</td><td style="text-align:right;">${un}</td><td style="text-align:right;">${qtd}</td><td style="text-align:right;">${fmtCurrency(preco)}</td><td style="text-align:right;">${fmtCurrency(total)}</td>`;
    tbody.appendChild(tr);
  }
  document.getElementById('subTotal').textContent = fmtCurrency(subtotal);
  document.getElementById('valorTotal').textContent = fmtCurrency(Number(quote.valor_total||subtotal));
  document.getElementById('descontos').textContent = fmtCurrency(0);

  // Condições de pagamento: prefill
  document.getElementById('condPagamento').value = quote.condicoes_pagamento || 'A combinar';
})();
</script>