<?php $title = 'Novo Fornecedor'; ?>

<style>
  .grid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 12px; }
  .col-2 { grid-column: span 2; }
  .col-3 { grid-column: span 3; }
  .col-4 { grid-column: span 4; }
  .col-6 { grid-column: span 6; }
  .col-8 { grid-column: span 8; }
  .col-12 { grid-column: span 12; }
  @media (max-width: 900px) { .col-2, .col-3, .col-4, .col-6, .col-8 { grid-column: span 12; } }
  .field-sm { max-width: 180px; }
  .field-xs { max-width: 140px; }
  .group { margin-bottom: 1rem; }
  .group h2 { font-size: 1rem; color: #444; margin: 0 0 0.5rem; }
  .error { border-color: #d93025 !important; }
  .hint { font-size: 0.85rem; color: #777; }
  .file-input { display: flex; align-items: center; gap: 8px; }
  .file-input .filename { font-size: 0.9rem; color: #555; }
  .sr-only-file { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
</style>

<div class="card">
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
    <h1>Novo Fornecedor</h1>
    <a href="/fornecedores" class="btn btn-secondary">Voltar</a>
  </div>

  <div id="alert" class="alert" style="display:none;"></div>

  <form id="supplierForm" enctype="multipart/form-data">
    <div class="group">
      <h2>Identificação fiscal</h2>
      <div class="grid">
        <div class="form-group col-6">
          <label for="nome_fantasia">Nome Fantasia *</label>
          <input type="text" id="nome_fantasia" name="nome_fantasia" required placeholder="Digite o nome fantasia" autocomplete="organization">
        </div>
        <div class="form-group col-6">
          <label for="razao_social">Razão Social *</label>
          <input type="text" id="razao_social" name="razao_social" required placeholder="Digite a razão social" autocomplete="organization">
        </div>
        <div class="form-group col-4">
          <label for="cnpj">CNPJ *</label>
          <div style="display:flex; align-items:center; gap:6px;">
            <input type="text" id="cnpj" name="cnpj" class="field-sm" maxlength="18" required placeholder="00.000.000/0000-00" inputmode="numeric" autocomplete="off">
            <button type="button" id="cnpjLookupBtn" class="btn btn-secondary">Consultar CNPJ</button>
          </div>
        </div>
        <div class="form-group col-4">
          <label for="ie">Inscrição Estadual *</label>
          <input type="text" id="ie" name="ie" required placeholder="Informe a IE" autocomplete="off" title="Inscrição Estadual conforme UF">
          <div class="hint">Aceita "ISENTO" ou máscara dinâmica por UF.</div>
        </div>
        <div class="form-group col-4">
          <label for="im">Inscrição Municipal</label>
          <input type="text" id="im" name="im" placeholder="Opcional" autocomplete="off">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Contato</h2>
      <div class="grid">
        <div class="form-group col-6">
          <label for="telefone_fixo">Telefone Fixo</label>
          <input type="text" id="telefone_fixo" name="telefone_fixo" placeholder="(00) 0000-0000" autocomplete="tel">
        </div>
        <div class="form-group col-6">
          <label for="telefone_celular">Telefone Celular</label>
          <input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000" autocomplete="tel">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Arquivos</h2>
      <div class="grid">
        <div class="form-group col-6">
          <label for="imagem">Imagem (JPG/PNG até 2MB)</label>
          <div class="file-input">
            <input type="file" id="imagem" name="imagem" accept="image/jpeg,image/png" class="sr-only-file">
            <label for="imagem" class="btn btn-secondary">Selecionar arquivo</label>
            <span id="imagemFilename" class="filename">Nenhum arquivo selecionado</span>
          </div>
        </div>
        <div class="form-group col-6">
          <label for="arquivo">Arquivo (PDF/DOC/XLS até 5MB)</label>
          <div class="file-input">
            <input type="file" id="arquivo" name="arquivo" accept="application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" class="sr-only-file">
            <label for="arquivo" class="btn btn-secondary">Selecionar arquivo</label>
            <span id="arquivoFilename" class="filename">Nenhum arquivo selecionado</span>
          </div>
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Referências</h2>
      <div class="grid">
        <div class="form-group col-12">
          <label for="referencias">Referências Comerciais</label>
          <textarea id="referencias" name="referencias" rows="4" placeholder="Informe referências comerciais relevantes"></textarea>
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Financeiro</h2>
      <div class="grid">
        <div class="form-group col-6">
          <label for="limite_credito">Limite de Crédito</label>
          <input type="text" id="limite_credito" name="limite_credito" placeholder="0,00" inputmode="decimal">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Gestão do fornecedor</h2>
      <div class="grid">
        <div class="form-group col-4">
          <label for="email">E-mail</label>
          <input type="email" id="email" name="email" placeholder="email@fornecedor.com" autocomplete="email">
        </div>
        <div class="form-group col-4">
          <label for="contato_nome">Contato</label>
          <input type="text" id="contato_nome" name="contato_nome" placeholder="Nome do contato">
        </div>
        <div class="form-group col-4">
          <label for="site_url">Site</label>
          <input type="url" id="site_url" name="site_url" placeholder="https://www.site.com">
        </div>
        <div class="form-group col-12">
          <label for="observacoes">Observações</label>
          <textarea id="observacoes" name="observacoes" rows="3" placeholder="Notas gerais sobre o fornecedor"></textarea>
        </div>
        <div class="form-group col-3" style="display:flex; align-items:end; gap:6px;">
          <input type="checkbox" id="bloqueado" name="bloqueado">
          <label for="bloqueado">Bloquear fornecedor</label>
        </div>
        <div class="form-group col-3" style="display:flex; align-items:end; gap:6px;">
          <input type="checkbox" id="inativo" name="inativo">
          <label for="inativo">Inativar fornecedor</label>
        </div>
        <div class="form-group col-6">
          <label for="status_motivo">Motivo (obrigatório ao bloquear/inativar)</label>
          <input type="text" id="status_motivo" name="status_motivo" placeholder="Informe o motivo">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Endereço principal</h2>
      <div class="grid">
        <div class="form-group col-2">
          <label for="cep">CEP *</label>
          <input type="text" id="cep" name="address[cep]" class="field-xs" maxlength="9" required placeholder="00000-000" inputmode="numeric" autocomplete="postal-code">
        </div>
        <div class="form-group col-1" style="display:flex; align-items:flex-end;">
          <button type="button" id="cepLookupBtn" class="btn btn-secondary" style="width:100%;">Buscar CEP</button>
        </div>
        <div class="form-group col-3">
          <label for="logradouro_tipo">Tipo de Logradouro</label>
          <select id="logradouro_tipo" name="logradouro_tipo">
            <option value="">Selecione</option>
            <option>Rua</option>
            <option>Avenida</option>
            <option>Travessa</option>
            <option>Alameda</option>
            <option>Praça</option>
            <option>Rodovia</option>
            <option>Estrada</option>
            <option>Viela</option>
            <option>Quadra</option>
            <option>Marginal</option>
          </select>
        </div>
        <div class="form-group col-6">
          <label for="logradouro">Logradouro *</label>
          <input type="text" id="logradouro" name="address[logradouro]" required placeholder="Nome da via">
        </div>
        <div class="form-group col-3">
          <label for="numero">Número *</label>
          <input type="text" id="numero" name="address[numero]" required>
        </div>
        <div class="form-group col-9">
          <label for="complemento">Complemento</label>
          <input type="text" id="complemento" name="address[complemento]">
        </div>
        <div class="form-group col-6">
          <label for="bairro">Bairro *</label>
          <input type="text" id="bairro" name="address[bairro]" required>
        </div>
        <div class="form-group col-4">
          <label for="cidade">Cidade *</label>
          <input type="text" id="cidade" name="address[cidade]" required>
        </div>
        <div class="form-group col-2">
          <label for="estado">Estado *</label>
          <input type="text" id="estado" name="address[estado]" required placeholder="UF" maxlength="2" style="max-width:80px;">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Endereços alternativos</h2>
      <div class="grid">
        <div class="form-group col-6" style="display:flex; align-items:center; gap:8px;">
          <input type="checkbox" id="billing_enabled" name="billing_enabled">
          <label for="billing_enabled">Endereço de cobrança diferente</label>
        </div>
        <div class="form-group col-6" style="display:flex; align-items:center; gap:8px;">
          <input type="checkbox" id="shipping_enabled" name="shipping_enabled">
          <label for="shipping_enabled">Endereço de entrega diferente</label>
        </div>
      </div>
      <div id="billing_section" style="display:none; margin-top:0.75rem;">
        <h3 style="font-size:0.95rem; color:#555; margin-bottom:0.5rem;">Endereço de Cobrança</h3>
        <div class="grid">
          <div class="form-group col-2">
            <label for="billing_cep">CEP *</label>
            <input type="text" id="billing_cep" name="billing_address[cep]" class="field-xs" maxlength="9" placeholder="00000-000" inputmode="numeric" autocomplete="postal-code">
          </div>
          <div class="form-group col-1" style="display:flex; align-items:flex-end;">
            <button type="button" id="billingCepLookupBtn" class="btn btn-secondary" style="width:100%;">Buscar CEP</button>
          </div>
          <div class="form-group col-3">
            <label for="billing_logradouro_tipo">Tipo de Logradouro</label>
            <select id="billing_logradouro_tipo" name="billing_logradouro_tipo">
              <option value="">Selecione</option>
              <option>Rua</option>
              <option>Avenida</option>
              <option>Travessa</option>
              <option>Alameda</option>
              <option>Praça</option>
              <option>Rodovia</option>
              <option>Estrada</option>
              <option>Viela</option>
              <option>Quadra</option>
              <option>Marginal</option>
            </select>
          </div>
          <div class="form-group col-6">
            <label for="billing_logradouro">Logradouro *</label>
            <input type="text" id="billing_logradouro" name="billing_address[logradouro]" placeholder="Nome da via">
          </div>
          <div class="form-group col-3">
            <label for="billing_numero">Número *</label>
            <input type="text" id="billing_numero" name="billing_address[numero]">
          </div>
          <div class="form-group col-9">
            <label for="billing_complemento">Complemento</label>
            <input type="text" id="billing_complemento" name="billing_address[complemento]">
          </div>
          <div class="form-group col-6">
            <label for="billing_bairro">Bairro *</label>
            <input type="text" id="billing_bairro" name="billing_address[bairro]">
          </div>
          <div class="form-group col-4">
            <label for="billing_cidade">Cidade *</label>
            <input type="text" id="billing_cidade" name="billing_address[cidade]">
          </div>
          <div class="form-group col-2">
            <label for="billing_estado">Estado *</label>
            <input type="text" id="billing_estado" name="billing_address[estado]" placeholder="UF" maxlength="2" style="max-width:80px;">
          </div>
        </div>
      </div>
      <div id="shipping_section" style="display:none; margin-top:0.75rem;">
        <h3 style="font-size:0.95rem; color:#555; margin-bottom:0.5rem;">Endereço de Entrega</h3>
        <div class="grid">
          <div class="form-group col-2">
            <label for="shipping_cep">CEP *</label>
            <input type="text" id="shipping_cep" name="shipping_address[cep]" class="field-xs" maxlength="9" placeholder="00000-000" inputmode="numeric" autocomplete="postal-code">
          </div>
          <div class="form-group col-1" style="display:flex; align-items:flex-end;">
            <button type="button" id="shippingCepLookupBtn" class="btn btn-secondary" style="width:100%;">Buscar CEP</button>
          </div>
          <div class="form-group col-3">
            <label for="shipping_logradouro_tipo">Tipo de Logradouro</label>
            <select id="shipping_logradouro_tipo" name="shipping_logradouro_tipo">
              <option value="">Selecione</option>
              <option>Rua</option>
              <option>Avenida</option>
              <option>Travessa</option>
              <option>Alameda</option>
              <option>Praça</option>
              <option>Rodovia</option>
              <option>Estrada</option>
              <option>Viela</option>
              <option>Quadra</option>
              <option>Marginal</option>
            </select>
          </div>
          <div class="form-group col-6">
            <label for="shipping_logradouro">Logradouro *</label>
            <input type="text" id="shipping_logradouro" name="shipping_address[logradouro]" placeholder="Nome da via">
          </div>
          <div class="form-group col-3">
            <label for="shipping_numero">Número *</label>
            <input type="text" id="shipping_numero" name="shipping_address[numero]">
          </div>
          <div class="form-group col-9">
            <label for="shipping_complemento">Complemento</label>
            <input type="text" id="shipping_complemento" name="shipping_address[complemento]">
          </div>
          <div class="form-group col-6">
            <label for="shipping_bairro">Bairro *</label>
            <input type="text" id="shipping_bairro" name="shipping_address[bairro]">
          </div>
          <div class="form-group col-4">
            <label for="shipping_cidade">Cidade *</label>
            <input type="text" id="shipping_cidade" name="shipping_address[cidade]">
          </div>
          <div class="form-group col-2">
            <label for="shipping_estado">Estado *</label>
            <input type="text" id="shipping_estado" name="shipping_address[estado]" placeholder="UF" maxlength="2" style="max-width:80px;">
          </div>
        </div>
      </div>
    </div>

    <div style="display: flex; gap: 1rem; margin-top: 2rem;">
      <button type="submit" class="btn" id="submitBtn">Criar Fornecedor</button>
      <a href="/fornecedores" class="btn btn-secondary">Cancelar</a>
    </div>
  </form>

  <div id="loading" class="loading" style="display:none;">Salvando fornecedor...</div>
</div>

<script>
  const supplierForm = document.getElementById('supplierForm');
  const submitBtn = document.getElementById('submitBtn');
  const cnpjLookupBtn = document.getElementById('cnpjLookupBtn');
  const cnpjInput = document.getElementById('cnpj');
  const cepLookupBtn = document.getElementById('cepLookupBtn');
  const cepInput = document.getElementById('cep');
  const nfInput = document.getElementById('nome_fantasia');
  const rsInput = document.getElementById('razao_social');
  const telFixoInput = document.getElementById('telefone_fixo');
  const telCelInput = document.getElementById('telefone_celular');
  const limInput = document.getElementById('limite_credito');
  const ieInput = document.getElementById('ie');
  const imInput = document.getElementById('im');
  const emailInput = document.getElementById('email');
  const contatoInput = document.getElementById('contato_nome');
  const siteInput = document.getElementById('site_url');
  const obsInput = document.getElementById('observacoes');
  const bloqueadoChk = document.getElementById('bloqueado');
  const inativoChk = document.getElementById('inativo');
  const statusMotivoInput = document.getElementById('status_motivo');
  const billingEnabled = document.getElementById('billing_enabled');
  const shippingEnabled = document.getElementById('shipping_enabled');
  const billingSection = document.getElementById('billing_section');
  const shippingSection = document.getElementById('shipping_section');
  const billingCepInput = document.getElementById('billing_cep');
  const shippingCepInput = document.getElementById('shipping_cep');
  const billingCepBtn = document.getElementById('billingCepLookupBtn');
  const shippingCepBtn = document.getElementById('shippingCepLookupBtn');

  function showLoading(){ document.getElementById('loading').style.display = 'block'; }
  function hideLoading(){ document.getElementById('loading').style.display = 'none'; }
  function showAlert(msg, type='success'){ const el=document.getElementById('alert'); el.className = `alert alert-${type}`; el.textContent = msg; el.style.display='block'; setTimeout(()=>{ el.style.display='none'; }, 5000); }

  // Máscaras e validações
  function maskCEP(value){ const d = (value||'').replace(/\D/g,'').slice(0,8); return d.length > 5 ? `${d.slice(0,5)}-${d.slice(5)}` : d; }
  function maskCNPJ(value){ const d = (value||'').replace(/\D/g,'').slice(0,14);
    if (d.length <= 2) return d;
    if (d.length <= 5) return `${d.slice(0,2)}.${d.slice(2)}`;
    if (d.length <= 8) return `${d.slice(0,2)}.${d.slice(2,5)}.${d.slice(5)}`;
    if (d.length <= 12) return `${d.slice(0,2)}.${d.slice(2,5)}.${d.slice(5,8)}/${d.slice(8)}`;
    return `${d.slice(0,2)}.${d.slice(2,5)}.${d.slice(5,8)}/${d.slice(8,12)}-${d.slice(12,14)}`;
  }
  function validateIE(ie, uf){ const ieTrim = (ie||'').trim().toUpperCase(); if (ieTrim === 'ISENTO') return true; const d = ieTrim.replace(/[^0-9A-Z]/g,''); const sizes = { SP:12, RJ:8, MG:13, PR:10, RS:10, SC:9, BA:8, ES:9, PE:14, CE:9, GO:9, MT:11, MS:9, PA:8, AL:9, AM:9, DF:13, RN:9, RO:14, TO:9, MA:9, PB:9, PI:9, SE:9 }; const size = sizes[uf] || 9; return d.length === size; }
  function validateIM(im){ const v = (im||'').trim(); if (v === '') return true; return /^[0-9A-Za-z\.\-\/]{5,20}$/.test(v); }
  function onlyDigits(str){ return (str||'').replace(/\D/g,''); }
  function formatMoneyBR(value){ const digits = onlyDigits(value); if (!digits) return 'R$ 0,00'; const intPart = digits.slice(0, -2) || '0'; const fracPart = digits.slice(-2).padStart(2, '0'); const intFormatted = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, '.'); return `R$ ${intFormatted},${fracPart}`; }
  function parseMoneyBR(value){ const digits = onlyDigits(value); if (!digits) return 0; const v = parseInt(digits, 10); return (v / 100); }
  function setError(el, has){ el.classList.toggle('error', !!has); }

  cnpjInput.addEventListener('input', function(e){ const v = maskCNPJ(e.target.value); e.target.value = v; setError(e.target, v.length !== 18); if (v.length === 18) ieInput.focus(); });
  // CEP: mascarar apenas no blur para evitar inversão durante digitação
  cepInput.addEventListener('input', function(e){ const d = (e.target.value||'').replace(/\D/g,''); setError(e.target, d.length !== 8); });
  cepInput.addEventListener('blur', function(e){ const d = (e.target.value||'').replace(/\D/g,''); e.target.value = maskCEP(e.target.value); if (d.length === 8) document.getElementById('logradouro').focus(); });
  ieInput.addEventListener('blur', function(){ const uf = (document.getElementById('estado').value||'').toUpperCase(); const ok = validateIE(ieInput.value, uf); setError(ieInput, !ok); });
  imInput.addEventListener('blur', function(){ const ok = validateIM(imInput.value); setError(imInput, !ok); });
  limInput.addEventListener('input', function(e){ const v = e.target.value; e.target.value = formatMoneyBR(v); const n = parseMoneyBR(e.target.value); setError(e.target, !(Number.isFinite(n) && n >= 0)); });
  limInput.addEventListener('blur', function(e){ e.target.value = formatMoneyBR(e.target.value); });
  limInput.addEventListener('focus', function(e){ setTimeout(()=>e.target.select(),0); });

  function toggleSection(checkbox, section, prefix){ const enabled = checkbox.checked; section.style.display = enabled ? 'block' : 'none'; const reqIds = ['logradouro','numero','bairro','cidade','estado','cep']; reqIds.forEach(id => { const input = document.getElementById(`${prefix}_${id}`); if (!input) return; input.required = enabled; if (!enabled) input.classList.remove('error'); }); }
  billingEnabled.addEventListener('change', () => toggleSection(billingEnabled, billingSection, 'billing'));
  shippingEnabled.addEventListener('change', () => toggleSection(shippingEnabled, shippingSection, 'shipping'));
  statusMotivoInput.addEventListener('input', () => { statusMotivoInput.classList.toggle('error', false); });
  bloqueadoChk.addEventListener('change', () => { statusMotivoInput.required = (bloqueadoChk.checked || inativoChk.checked); });
  inativoChk.addEventListener('change', () => { statusMotivoInput.required = (bloqueadoChk.checked || inativoChk.checked); });

  billingCepInput.addEventListener('input', function(e){ const d = (e.target.value||'').replace(/\D/g,''); setError(e.target, billingEnabled.checked && d.length !== 8); });
  billingCepInput.addEventListener('blur', function(e){ e.target.value = maskCEP(e.target.value); });
  shippingCepInput.addEventListener('input', function(e){ const d = (e.target.value||'').replace(/\D/g,''); setError(e.target, shippingEnabled.checked && d.length !== 8); });
  shippingCepInput.addEventListener('blur', function(e){ e.target.value = maskCEP(e.target.value); });

  async function cepLookupGeneric(cepDigits, prefix){ const btn = prefix==='billing' ? billingCepBtn : shippingCepBtn; try{ btn.disabled = true; btn.textContent = 'Buscando...'; const resp = await apiRequest(`/api/fornecedores/cep/${cepDigits}`); if (!resp) return; if (resp.ok){ const payload = await resp.json(); const d = payload.data || {}; ['logradouro','complemento','bairro','cidade','estado'].forEach(k => { const el = document.getElementById(`${prefix}_${k}`); if (el && d[k]) el.value = (k==='estado' ? String(d[k]||'').toUpperCase() : d[k]); }); const cepEl = document.getElementById(`${prefix}_cep`); if (cepEl) cepEl.value = maskCEP(cepDigits); showAlert(`Endereço de ${prefix==='billing'?'cobrança':'entrega'} carregado pelo CEP!`, 'success'); } else { showAlert('CEP não encontrado', 'error'); } } catch(err){ showAlert('Erro ao buscar CEP', 'error'); } finally { btn.disabled = false; btn.textContent = 'Buscar CEP'; } }
  billingCepBtn.addEventListener('click', () => { const cepDigits = (billingCepInput.value||'').replace(/\D/g,''); if (cepDigits.length !== 8){ showAlert('CEP de cobrança deve ter 8 dígitos', 'error'); return; } cepLookupGeneric(cepDigits, 'billing'); });
  shippingCepBtn.addEventListener('click', () => { const cepDigits = (shippingCepInput.value||'').replace(/\D/g,''); if (cepDigits.length !== 8){ showAlert('CEP de entrega deve ter 8 dígitos', 'error'); return; } cepLookupGeneric(cepDigits, 'shipping'); });

  // Consulta CNPJ com auto-disparo quando atingir 14 dígitos
  let __cnpjAutoTimer = null;
  async function tryAutoCnpjLookup(){ const digits = (cnpjInput.value||'').replace(/\D/g,''); if (digits.length !== 14) return; if ((nfInput.value || rsInput.value)) return; cnpjLookupBtn.click(); }
  cnpjInput.addEventListener('blur', tryAutoCnpjLookup);
  cnpjInput.addEventListener('input', () => { clearTimeout(__cnpjAutoTimer); __cnpjAutoTimer = setTimeout(tryAutoCnpjLookup, 400); });

  cnpjLookupBtn.addEventListener('click', async function(){ const cnpj = (cnpjInput.value||'').replace(/\D/g,''); if (cnpj.length !== 14){ showAlert('CNPJ deve ter 14 dígitos', 'error'); return; }
    try {
      cnpjLookupBtn.disabled = true; cnpjLookupBtn.textContent = 'Consultando...';
      const response = await apiRequest(`/api/fornecedores/cnpj/${cnpj}`);
      if (!response) return;
      if (response.ok){ const payload = await response.json(); const d = payload.data || {};
        const nomeEmpresa = d.nome_fantasia || d.razao_social;
        if (nomeEmpresa) { nfInput.value = nomeEmpresa; rsInput.value = d.razao_social || rsInput.value; }
        if (d.telefone){ const digits = (d.telefone||'').replace(/\D/g,''); if (digits.length === 11) telCelInput.value = d.telefone; else if (digits.length === 10) telFixoInput.value = d.telefone; }
        const e = d.endereco || {}; if (e.logradouro) document.getElementById('logradouro').value = e.logradouro; if (e.numero) document.getElementById('numero').value = e.numero; if (e.complemento) document.getElementById('complemento').value = e.complemento; if (e.bairro) document.getElementById('bairro').value = e.bairro; if (e.cidade) document.getElementById('cidade').value = e.cidade; if (e.estado) document.getElementById('estado').value = String(e.estado).toUpperCase(); if (e.cep) document.getElementById('cep').value = maskCEP(e.cep);
        showAlert('Dados do CNPJ carregados com sucesso!', 'success');
      } else {
        let msg = 'Erro ao consultar CNPJ';
        try { const err = await response.json(); msg = err?.error?.message || msg; } catch(_){ }
        showAlert(msg, 'error');
      }
    } catch(err){ showAlert('Erro ao consultar CNPJ', 'error'); }
    finally { cnpjLookupBtn.disabled = false; cnpjLookupBtn.textContent = 'Consultar CNPJ'; }
  });

  // Busca CEP principal
  cepLookupBtn.addEventListener('click', async function(){ const cep = (cepInput.value||'').replace(/\D/g,''); if (cep.length !== 8){ showAlert('CEP deve ter 8 dígitos', 'error'); return; }
    try { cepLookupBtn.disabled = true; cepLookupBtn.textContent = 'Buscando...'; const response = await apiRequest(`/api/fornecedores/cep/${cep}`); if (!response) return; if (response.ok){ const payload = await response.json(); const d = payload.data || {}; if (d.logradouro) document.getElementById('logradouro').value = d.logradouro; if (d.complemento) document.getElementById('complemento').value = d.complemento; if (d.bairro) document.getElementById('bairro').value = d.bairro; if (d.cidade) document.getElementById('cidade').value = d.cidade; if (d.estado) document.getElementById('estado').value = String(d.estado).toUpperCase(); document.getElementById('cep').value = maskCEP(cep); showAlert('Endereço carregado pelo CEP!', 'success'); } else { showAlert('CEP não encontrado', 'error'); } }
    catch(err){ showAlert('Erro ao buscar CEP', 'error'); }
    finally { cepLookupBtn.disabled = false; cepLookupBtn.textContent = 'Buscar CEP'; }
  });

  // Submissão do formulário
  supplierForm.addEventListener('submit', async function(e){ e.preventDefault();
    // Antes de gerar FormData, combinar tipo de logradouro com logradouro
    function combineTipo(prefix=''){
      const tipoEl = document.getElementById((prefix?prefix+'_':'')+'logradouro_tipo');
      const logEl = document.getElementById((prefix?prefix+'_':'')+'logradouro');
      const tipo = (tipoEl?.value || '').trim();
      const log = (logEl?.value || '').trim();
      if (logEl) logEl.value = (tipo ? `${tipo} ${log}` : log);
    }
    combineTipo(''); if (billingEnabled.checked) combineTipo('billing'); if (shippingEnabled.checked) combineTipo('shipping');

    const formData = new FormData(supplierForm);
    function buildAddress(prefix=''){ const get = (id) => (document.getElementById((prefix?prefix+'_':'')+id)?.value || '').trim(); const parts = []; const logradouro=get('logradouro'); const numero=get('numero'); const bairro=get('bairro'); const cidade=get('cidade'); const estado=(get('estado')||'').toUpperCase(); const cep=(get('cep')||'').replace(/\D/g,''); if (logradouro) parts.push(logradouro); if (numero) parts.push(String(numero)); if (bairro) parts.push(bairro); if (cidade) parts.push(cidade); if (estado) parts.push(estado); if (cep) parts.push(cep); return parts.join(', '); }
    async function geocode(address){ if (!address) return null; try { const resp = await apiRequest(`/api/fornecedores/geocode?q=${encodeURIComponent(address)}`); if (!resp || !resp.ok) return null; const data = await resp.json(); if (!data || !data.ok) return null; return { lat: parseFloat(data.lat), lon: parseFloat(data.lon) }; } catch(_){ return null; } }

    const cnpjDigits = (formData.get('cnpj')||'').replace(/\D/g,''); formData.set('cnpj', cnpjDigits);
    // CEPs e UFs normalizados
    formData.set('address[cep]', (document.getElementById('cep').value||'').replace(/\D/g,''));
    formData.set('address[estado]', String(document.getElementById('estado').value||'').toUpperCase());
    if (billingEnabled.checked){ formData.set('billing_address[cep]', (document.getElementById('billing_cep').value||'').replace(/\D/g,'')); formData.set('billing_address[estado]', String(document.getElementById('billing_estado').value||'').toUpperCase()); }
    if (shippingEnabled.checked){ formData.set('shipping_address[cep]', (document.getElementById('shipping_cep').value||'').replace(/\D/g,'')); formData.set('shipping_address[estado]', String(document.getElementById('shipping_estado').value||'').toUpperCase()); }

    formData.set('bloqueado', bloqueadoChk.checked ? 'true' : 'false'); formData.set('inativo', inativoChk.checked ? 'true' : 'false'); if ((bloqueadoChk.checked || inativoChk.checked) && !(statusMotivoInput.value||'').trim()){ setError(statusMotivoInput, true); showAlert('Informe o motivo para bloquear/inativar', 'error'); return; }
    formData.set('tipo', 'PJ'); formData.set('ie', (formData.get('ie')||'').toString().trim()); formData.set('im', (formData.get('im')||'').toString().trim());
    const uf = String(document.getElementById('estado').value||'').toUpperCase(); if (!validateIE(formData.get('ie'), uf)){ showAlert('Inscrição Estadual inválida para a UF', 'error'); return; } if (!validateIM(formData.get('im'))){ showAlert('Inscrição Municipal inválida', 'error'); return; }
    const limNum = parseMoneyBR(formData.get('limite_credito')); if (!Number.isFinite(limNum) || limNum < 0){ showAlert('Limite de crédito inválido', 'error'); return; } formData.set('limite_credito', String(limNum)); if (!cnpjDigits || cnpjDigits.length !== 14){ showAlert('CNPJ é obrigatório e deve ter 14 dígitos', 'error'); return; }
    try {
      const principalAddr = buildAddress(''); const pGeo = await geocode(principalAddr); if (pGeo){ formData.set('address[latitude]', String(pGeo.lat)); formData.set('address[longitude]', String(pGeo.lon)); }
      if (billingEnabled.checked){ const bAddr = buildAddress('billing'); const bGeo = await geocode(bAddr); if (bGeo){ formData.set('billing_address[latitude]', String(bGeo.lat)); formData.set('billing_address[longitude]', String(bGeo.lon)); } }
      if (shippingEnabled.checked){ const sAddr = buildAddress('shipping'); const sGeo = await geocode(sAddr); if (sGeo){ formData.set('shipping_address[latitude]', String(sGeo.lat)); formData.set('shipping_address[longitude]', String(sGeo.lon)); } }
    } catch(_){ }

    try {
      showLoading(); submitBtn.disabled = true;
      const resp = await apiRequest('/api/fornecedores', { method:'POST', body: formData });
      if (!resp) return; if (resp.ok){ const result = await resp.json(); showAlert('Fornecedor criado com sucesso!', 'success'); setTimeout(()=>{ window.location.href = `/fornecedores/${result.id}`; }, 1200); }
      else { let errorMsg = 'Erro ao criar fornecedor'; try { const err = await resp.json(); errorMsg = err?.error?.message || errorMsg; } catch(_){} showAlert(errorMsg, 'error'); }
    } catch(err){ showAlert('Erro ao criar fornecedor', 'error'); }
    finally { hideLoading(); submitBtn.disabled = false; }
  });

  // Atualizar rótulos de arquivo selecionado
  const imagemInput = document.getElementById('imagem');
  const arquivoInput = document.getElementById('arquivo');
  const imagemFilename = document.getElementById('imagemFilename');
  const arquivoFilename = document.getElementById('arquivoFilename');
  if (imagemInput) imagemInput.addEventListener('change', function(){ const f = this.files && this.files[0] ? this.files[0].name : 'Nenhum arquivo selecionado'; if (imagemFilename) imagemFilename.textContent = f; });
  if (arquivoInput) arquivoInput.addEventListener('change', function(){ const f = this.files && this.files[0] ? this.files[0].name : 'Nenhum arquivo selecionado'; if (arquivoFilename) arquivoFilename.textContent = f; });
</script>