<?php $title = 'Editar 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 id="pageTitle">Editar Fornecedor</h1>
    <div>
      <a href="/fornecedores" class="btn btn-secondary">Voltar</a>
      <a href="#" id="viewBtn" class="btn btn-secondary">Ver Fornecedor</a>
    </div>
  </div>

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

  <form id="supplierForm" style="display:none;" 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>
        <div class="form-group col-4">
          <label for="im">Inscrição Municipal</label>
          <input type="text" id="im" name="im" placeholder="Informe a IM" autocomplete="off" title="Inscrição Municipal do fornecedor">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Contato</h2>
      <div class="grid">
        <div class="form-group col-4">
          <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-4">
          <label for="telefone_celular">Celular</label>
          <input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000" autocomplete="tel">
        </div>
        <div class="form-group col-4">
          <label for="email">E-mail</label>
          <input type="email" id="email" name="email" placeholder="fornecedor@exemplo.com" autocomplete="email">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Arquivos</h2>
      <div class="grid">
        <div class="form-group col-6">
          <label>Imagem</label>
          <div class="file-input">
            <input type="file" id="imagem" name="imagem" accept="image/*" class="sr-only-file">
            <label for="imagem" class="btn btn-secondary">Selecionar Imagem</label>
            <span class="filename" id="imgFileName">Nenhum arquivo selecionado</span>
          </div>
        </div>
        <div class="form-group col-6">
          <label>Arquivo</label>
          <div class="file-input">
            <input type="file" id="arquivo" name="arquivo" class="sr-only-file">
            <label for="arquivo" class="btn btn-secondary">Selecionar Arquivo</label>
            <span class="filename" id="genFileName">Nenhum arquivo selecionado</span>
          </div>
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Financeiro</h2>
      <div class="grid">
        <div class="form-group col-4">
          <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 class="form-group col-8">
          <label for="referencias">Referências</label>
          <input type="text" id="referencias" name="referencias" placeholder="Indicações comerciais / referências">
        </div>
      </div>
    </div>

    <div class="group">
      <h2>Gestão do Fornecedor</h2>
      <div class="grid">
        <div class="form-group col-6">
          <label for="contato_nome">Nome do contato</label>
          <input type="text" id="contato_nome" name="contato_nome" placeholder="Responsável comercial">
        </div>
        <div class="form-group col-6">
          <label for="site_url">Website</label>
          <input type="url" id="site_url" name="site_url" placeholder="https://exemplo.com" autocomplete="url">
        </div>
        <div class="form-group col-12">
          <label for="observacoes">Observações</label>
          <textarea id="observacoes" name="observacoes" rows="2" placeholder="Notas gerais sobre o fornecedor"></textarea>
        </div>
        <div class="form-group col-3" style="display:flex; align-items:center; gap:8px;">
          <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:center; gap:8px;">
          <input type="checkbox" id="inativo" name="inativo">
          <label for="inativo">Marcar como inativo</label>
        </div>
        <div class="form-group col-6">
          <label for="status_motivo">Motivo (bloqueio/inatividade)</label>
          <input type="text" id="status_motivo" name="status_motivo" placeholder="Justificativa">
        </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="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="cepLookupBtn" class="btn btn-secondary" style="width:100%;">Buscar CEP</button>
        </div>
        <div class="form-group col-9">
          <label for="logradouro">Logradouro *</label>
          <input type="text" id="logradouro" name="logradouro" placeholder="Rua, Av., etc.">
        </div>
        <div class="form-group col-3">
          <label for="numero">Número *</label>
          <input type="text" id="numero" name="numero">
        </div>
        <div class="form-group col-9">
          <label for="complemento">Complemento</label>
          <input type="text" id="complemento" name="complemento">
        </div>
        <div class="form-group col-6">
          <label for="bairro">Bairro *</label>
          <input type="text" id="bairro" name="bairro">
        </div>
        <div class="form-group col-4">
          <label for="cidade">Cidade *</label>
          <input type="text" id="cidade" name="cidade">
        </div>
        <div class="form-group col-2">
          <label for="estado">Estado *</label>
          <input type="text" id="estado" name="estado" placeholder="UF" maxlength="2" style="max-width:80px;">
        </div>
        <input type="hidden" id="latitude" name="latitude">
        <input type="hidden" id="longitude" name="longitude">
      </div>
    </div>

    <div class="group">
      <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_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-9">
            <label for="billing_logradouro">Logradouro *</label>
            <input type="text" id="billing_logradouro" name="billing_logradouro" placeholder="Rua, Av., etc.">
          </div>
          <div class="form-group col-3">
            <label for="billing_numero">Número *</label>
            <input type="text" id="billing_numero" name="billing_numero">
          </div>
          <div class="form-group col-9">
            <label for="billing_complemento">Complemento</label>
            <input type="text" id="billing_complemento" name="billing_complemento">
          </div>
          <div class="form-group col-6">
            <label for="billing_bairro">Bairro *</label>
            <input type="text" id="billing_bairro" name="billing_bairro">
          </div>
          <div class="form-group col-4">
            <label for="billing_cidade">Cidade *</label>
            <input type="text" id="billing_cidade" name="billing_cidade">
          </div>
          <div class="form-group col-2">
            <label for="billing_estado">Estado *</label>
            <input type="text" id="billing_estado" name="billing_estado" placeholder="UF" maxlength="2" style="max-width:80px;">
          </div>
          <input type="hidden" id="billing_latitude" name="billing_latitude">
          <input type="hidden" id="billing_longitude" name="billing_longitude">
        </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_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-9">
            <label for="shipping_logradouro">Logradouro *</label>
            <input type="text" id="shipping_logradouro" name="shipping_logradouro" placeholder="Rua, Av., etc.">
          </div>
          <div class="form-group col-3">
            <label for="shipping_numero">Número *</label>
            <input type="text" id="shipping_numero" name="shipping_numero">
          </div>
          <div class="form-group col-9">
            <label for="shipping_complemento">Complemento</label>
            <input type="text" id="shipping_complemento" name="shipping_complemento">
          </div>
          <div class="form-group col-6">
            <label for="shipping_bairro">Bairro *</label>
            <input type="text" id="shipping_bairro" name="shipping_bairro">
          </div>
          <div class="form-group col-4">
            <label for="shipping_cidade">Cidade *</label>
            <input type="text" id="shipping_cidade" name="shipping_cidade">
          </div>
          <div class="form-group col-2">
            <label for="shipping_estado">Estado *</label>
            <input type="text" id="shipping_estado" name="shipping_estado" placeholder="UF" maxlength="2" style="max-width:80px;">
          </div>
          <input type="hidden" id="shipping_latitude" name="shipping_latitude">
          <input type="hidden" id="shipping_longitude" name="shipping_longitude">
        </div>
      </div>
    </div>

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

  <div id="saveLoading" class="loading" style="display:none;">Salvando alterações...</div>
</div>

<script>
  let supplierId = null;
  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');

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

  // Masks simples
  function maskCnpj(v){ v = (v||'').replace(/\D/g,''); if(v.length>14) v = v.slice(0,14); return v.replace(/(\d{2})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1/$2').replace(/(\d{4})(\d{1,2})$/,'$1-$2'); }
  function maskCep(v){ v = (v||'').replace(/\D/g,''); if(v.length>8) v = v.slice(0,8); return v.replace(/(\d{5})(\d{1,3})$/,'$1-$2'); }
  cnpjInput.addEventListener('input', ()=>{ cnpjInput.value = maskCnpj(cnpjInput.value); });
  cepInput.addEventListener('input', ()=>{ cepInput.value = maskCep(cepInput.value); });

  // Toggle billing/shipping
  document.getElementById('billing_enabled').addEventListener('change', (e)=>{ document.getElementById('billing_section').style.display = e.target.checked ? 'block':'none'; });
  document.getElementById('shipping_enabled').addEventListener('change', (e)=>{ document.getElementById('shipping_section').style.display = e.target.checked ? 'block':'none'; });

  async function loadSupplier(){
    try{
      showLoading();
      const url = new URL(window.location.href);
      const parts = url.pathname.split('/').filter(Boolean);
      supplierId = parseInt(parts[1] || '0', 10);
      const resp = await apiRequest(`/api/fornecedores/${supplierId}`);
      if(!resp || !resp.ok){ throw new Error('Erro ao carregar fornecedor'); }
      const payload = await resp.json();
      const sup = payload.data || payload;
      populateForm(sup);
    }catch(e){ showAlert('Erro ao carregar fornecedor: ' + e.message, 'error'); }
  }

  function populateForm(sup){
    const nomeDisplay = sup.nome_fantasia || sup.razao_social || sup.nome || sup.id;
    document.getElementById('pageTitle').textContent = `Editar Fornecedor: ${nomeDisplay}`;
    document.getElementById('viewBtn').href = `/fornecedores/${sup.id}`;

    document.getElementById('nome_fantasia').value = sup.nome_fantasia || sup.nome || '';
    document.getElementById('razao_social').value = sup.razao_social || '';
    document.getElementById('cnpj').value = sup.cnpj || '';
    document.getElementById('ie').value = sup.ie || '';
    document.getElementById('im').value = sup.im || '';
    document.getElementById('telefone_fixo').value = sup.telefone_fixo || '';
    document.getElementById('telefone_celular').value = sup.telefone_celular || '';
    document.getElementById('email').value = sup.email || '';
    document.getElementById('contato_nome').value = sup.contato_nome || '';
    document.getElementById('site_url').value = sup.site_url || '';
    document.getElementById('observacoes').value = sup.observacoes || '';
    document.getElementById('referencias').value = sup.referencias || '';
    document.getElementById('limite_credito').value = sup.limite_credito != null ? String(sup.limite_credito).replace('.', ',') : '';
    document.getElementById('bloqueado').checked = !!sup.bloqueado;
    document.getElementById('inativo').checked = !!sup.inativo;
    document.getElementById('status_motivo').value = sup.status_motivo || '';

    // Endereços vindo da API: address/billing_address/shipping_address
    const principal = sup.address || (sup.enderecos ? (sup.enderecos.find(e=>e.tipo==='principal')||{}) : {});
    const cobranca = sup.billing_address || (sup.enderecos ? (sup.enderecos.find(e=>e.tipo==='cobranca')||null) : null);
    const entrega = sup.shipping_address || (sup.enderecos ? (sup.enderecos.find(e=>e.tipo==='entrega')||null) : null);
    // principal
    document.getElementById('cep').value = principal && principal.cep || '';
    document.getElementById('logradouro').value = principal && principal.logradouro || '';
    document.getElementById('numero').value = principal && principal.numero || '';
    document.getElementById('complemento').value = principal && principal.complemento || '';
    document.getElementById('bairro').value = principal && principal.bairro || '';
    document.getElementById('cidade').value = principal && principal.cidade || '';
    document.getElementById('estado').value = principal && principal.estado || '';
    document.getElementById('latitude').value = principal && principal.latitude != null ? String(principal.latitude) : '';
    document.getElementById('longitude').value = principal && principal.longitude != null ? String(principal.longitude) : '';
    // cobranca
    if (cobranca) {
      document.getElementById('billing_enabled').checked = true;
      document.getElementById('billing_section').style.display = 'block';
      document.getElementById('billing_cep').value = cobranca.cep || '';
      document.getElementById('billing_logradouro').value = cobranca.logradouro || '';
      document.getElementById('billing_numero').value = cobranca.numero || '';
      document.getElementById('billing_complemento').value = cobranca.complemento || '';
      document.getElementById('billing_bairro').value = cobranca.bairro || '';
      document.getElementById('billing_cidade').value = cobranca.cidade || '';
      document.getElementById('billing_estado').value = cobranca.estado || '';
      document.getElementById('billing_latitude').value = cobranca.latitude != null ? String(cobranca.latitude) : '';
      document.getElementById('billing_longitude').value = cobranca.longitude != null ? String(cobranca.longitude) : '';
    }
    // entrega
    if (entrega) {
      document.getElementById('shipping_enabled').checked = true;
      document.getElementById('shipping_section').style.display = 'block';
      document.getElementById('shipping_cep').value = entrega.cep || '';
      document.getElementById('shipping_logradouro').value = entrega.logradouro || '';
      document.getElementById('shipping_numero').value = entrega.numero || '';
      document.getElementById('shipping_complemento').value = entrega.complemento || '';
      document.getElementById('shipping_bairro').value = entrega.bairro || '';
      document.getElementById('shipping_cidade').value = entrega.cidade || '';
      document.getElementById('shipping_estado').value = entrega.estado || '';
      document.getElementById('shipping_latitude').value = entrega.latitude != null ? String(entrega.latitude) : '';
      document.getElementById('shipping_longitude').value = entrega.longitude != null ? String(entrega.longitude) : '';
    }

    hideLoading(); supplierForm.style.display = 'block';
  }

  // CEP lookups
  async function lookupCep(target){
    const input = document.getElementById(target);
    const cep = (input.value||'').replace(/\D/g,'');
    if(cep.length !== 8){ showAlert('CEP deve ter 8 dígitos', 'error'); return; }
    try{
      const btn = target==='cep' ? cepLookupBtn : (target==='billing_cep' ? document.getElementById('billingCepLookupBtn') : document.getElementById('shippingCepLookupBtn'));
      btn.disabled = true; btn.textContent = 'Buscando...';
      const resp = await apiRequest(`/api/fornecedores/cep/${cep}`);
      if(resp && resp.ok){
        const payload = await resp.json();
        const d = payload.data || {};
        const prefix = target==='cep' ? '' : (target==='billing_cep' ? 'billing_' : 'shipping_');
        if (d.logradouro) document.getElementById(prefix+'logradouro').value = d.logradouro;
        if (d.complemento) document.getElementById(prefix+'complemento').value = d.complemento;
        if (d.bairro) document.getElementById(prefix+'bairro').value = d.bairro;
        if (d.cidade) document.getElementById(prefix+'cidade').value = d.cidade;
        if (d.estado) document.getElementById(prefix+'estado').value = d.estado;
        document.getElementById(prefix+'cep').value = d.cep || cep;
        showAlert('Endereço carregado pelo CEP!', 'success');
      } else { showAlert('CEP não encontrado', 'error'); }
    }catch(err){ showAlert('Erro ao buscar CEP', 'error'); }
    finally{
      const btn = target==='cep' ? cepLookupBtn : (target==='billing_cep' ? document.getElementById('billingCepLookupBtn') : document.getElementById('shippingCepLookupBtn'));
      btn.disabled = false; btn.textContent = 'Buscar CEP';
    }
  }
  document.getElementById('billingCepLookupBtn').addEventListener('click', ()=> lookupCep('billing_cep'));
  document.getElementById('shippingCepLookupBtn').addEventListener('click', ()=> lookupCep('shipping_cep'));
  cepLookupBtn.addEventListener('click', ()=> lookupCep('cep'));

  // CNPJ lookup
  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 resp = await apiRequest(`/api/fornecedores/cnpj/${cnpj}`);
      if(resp && resp.ok){ const payload = await resp.json(); const d = payload.data || {};
        if (d.nome_fantasia && !document.getElementById('nome_fantasia').value) document.getElementById('nome_fantasia').value = d.nome_fantasia;
        if (d.razao_social && !document.getElementById('razao_social').value) document.getElementById('razao_social').value = d.razao_social;
        if (d.email && !document.getElementById('email').value) document.getElementById('email').value = d.email;
        if (d.telefone && !document.getElementById('telefone_fixo').value) document.getElementById('telefone_fixo').value = d.telefone;
        showAlert('Dados carregados pelo CNPJ!', 'success');
      } else { showAlert('CNPJ não encontrado', 'error'); }
    }catch(err){ showAlert('Erro ao consultar CNPJ', 'error'); }
    finally{ cnpjLookupBtn.disabled = false; cnpjLookupBtn.textContent = 'Consultar CNPJ'; }
  });

  // Atualizar labels de arquivos
  document.getElementById('imagem').addEventListener('change', function(){ const f = this.files && this.files[0]; document.getElementById('imgFileName').textContent = f ? f.name : 'Nenhum arquivo selecionado'; });
  document.getElementById('arquivo').addEventListener('change', function(){ const f = this.files && this.files[0]; document.getElementById('genFileName').textContent = f ? f.name : 'Nenhum arquivo selecionado'; });

  // Submit
  supplierForm.addEventListener('submit', async function(e){
    e.preventDefault();
    try{
      document.getElementById('saveLoading').style.display='block';
      submitBtn.disabled = true; submitBtn.textContent = 'Salvando...';

      // Normalizações
      const cnpj = (cnpjInput.value||'').replace(/\D/g,'');
      const cep = (cepInput.value||'').replace(/\D/g,'');
      if (cnpj.length !== 14) { throw new Error('CNPJ inválido'); }
      if (cep.length !== 8) { throw new Error('CEP inválido'); }
      const fd = new FormData();
      fd.append('nome_fantasia', document.getElementById('nome_fantasia').value);
      fd.append('razao_social', document.getElementById('razao_social').value);
      fd.append('cnpj', cnpj);
      fd.append('ie', document.getElementById('ie').value);
      fd.append('im', document.getElementById('im').value);
      fd.append('telefone_fixo', document.getElementById('telefone_fixo').value);
      fd.append('telefone_celular', document.getElementById('telefone_celular').value);
      fd.append('email', document.getElementById('email').value);
      fd.append('contato_nome', document.getElementById('contato_nome').value);
      fd.append('site_url', document.getElementById('site_url').value);
      fd.append('observacoes', document.getElementById('observacoes').value);
      fd.append('referencias', document.getElementById('referencias').value);
      const limiteVal = document.getElementById('limite_credito').value ? String(document.getElementById('limite_credito').value).replace('.', '').replace(',', '.') : '';
      if (limiteVal !== '') fd.append('limite_credito', limiteVal);
      fd.append('bloqueado', document.getElementById('bloqueado').checked ? '1' : '0');
      fd.append('inativo', document.getElementById('inativo').checked ? '1' : '0');
      fd.append('status_motivo', document.getElementById('status_motivo').value);

      // Endereço principal
      fd.append('address[cep]', cep);
      fd.append('address[logradouro]', document.getElementById('logradouro').value);
      fd.append('address[numero]', document.getElementById('numero').value);
      fd.append('address[complemento]', document.getElementById('complemento').value);
      fd.append('address[bairro]', document.getElementById('bairro').value);
      fd.append('address[cidade]', document.getElementById('cidade').value);
      fd.append('address[estado]', (document.getElementById('estado').value||'').toUpperCase());
      if (document.getElementById('latitude').value) fd.append('address[latitude]', document.getElementById('latitude').value);
      if (document.getElementById('longitude').value) fd.append('address[longitude]', document.getElementById('longitude').value);

      // Endereços adicionais
      if (document.getElementById('billing_enabled').checked) {
        fd.append('billing_address[cep]', (document.getElementById('billing_cep').value||'').replace(/\D/g,''));
        fd.append('billing_address[logradouro]', document.getElementById('billing_logradouro').value);
        fd.append('billing_address[numero]', document.getElementById('billing_numero').value);
        fd.append('billing_address[complemento]', document.getElementById('billing_complemento').value);
        fd.append('billing_address[bairro]', document.getElementById('billing_bairro').value);
        fd.append('billing_address[cidade]', document.getElementById('billing_cidade').value);
        fd.append('billing_address[estado]', (document.getElementById('billing_estado').value||'').toUpperCase());
        if (document.getElementById('billing_latitude').value) fd.append('billing_address[latitude]', document.getElementById('billing_latitude').value);
        if (document.getElementById('billing_longitude').value) fd.append('billing_address[longitude]', document.getElementById('billing_longitude').value);
      }
      if (document.getElementById('shipping_enabled').checked) {
        fd.append('shipping_address[cep]', (document.getElementById('shipping_cep').value||'').replace(/\D/g,''));
        fd.append('shipping_address[logradouro]', document.getElementById('shipping_logradouro').value);
        fd.append('shipping_address[numero]', document.getElementById('shipping_numero').value);
        fd.append('shipping_address[complemento]', document.getElementById('shipping_complemento').value);
        fd.append('shipping_address[bairro]', document.getElementById('shipping_bairro').value);
        fd.append('shipping_address[cidade]', document.getElementById('shipping_cidade').value);
        fd.append('shipping_address[estado]', (document.getElementById('shipping_estado').value||'').toUpperCase());
        if (document.getElementById('shipping_latitude').value) fd.append('shipping_address[latitude]', document.getElementById('shipping_latitude').value);
        if (document.getElementById('shipping_longitude').value) fd.append('shipping_address[longitude]', document.getElementById('shipping_longitude').value);
      }

      // Arquivos
      if (supplierForm.imagem && supplierForm.imagem.files && supplierForm.imagem.files[0]) {
        fd.append('imagem', supplierForm.imagem.files[0]);
      }
      if (supplierForm.arquivo && supplierForm.arquivo.files && supplierForm.arquivo.files[0]) {
        fd.append('arquivo', supplierForm.arquivo.files[0]);
      }

      const resp = await apiRequest(`/api/fornecedores/${supplierId}`, { method: 'PUT', body: fd });
      if (!resp || !resp.ok) {
        let msg = 'Falha ao salvar';
        try{
          const err = await resp.json();
          msg = err.error?.message || err.error || msg;
          if (err.error?.code === 'duplicate_cnpj') { msg = 'CNPJ já cadastrado para outro fornecedor.'; }
        }catch(_){ }
        throw new Error(msg);
      }
      showAlert('Fornecedor atualizado com sucesso!', 'success');
      window.location.href = `/fornecedores/${supplierId}`;
    }catch(e){ showAlert(e.message, 'error'); }
    finally{ document.getElementById('saveLoading').style.display='none'; submitBtn.disabled=false; submitBtn.textContent='Salvar Alterações'; }
  });

  // Auto consulta CNPJ ao digitar
  let __cnpjAutoTimer = null;
  async function tryAutoCnpjLookup(){
    const digits = (cnpjInput.value||'').replace(/\D/g,'');
    if (digits.length !== 14) return;
    const nf = document.getElementById('nome_fantasia').value; const rs = document.getElementById('razao_social').value;
    if (nf || rs) return;
    cnpjLookupBtn.click();
  }
  cnpjInput.addEventListener('blur', tryAutoCnpjLookup);
  cnpjInput.addEventListener('input', ()=>{ clearTimeout(__cnpjAutoTimer); __cnpjAutoTimer = setTimeout(tryAutoCnpjLookup, 400); });

  document.addEventListener('DOMContentLoaded', loadSupplier);
</script>