<?php
// configuracoes.php — Configurações do sistema (COMPLETO - TODAS OPÇÕES)
$pageActive = 'configuracoes';
$pageTitle  = 'Configurações';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requirePerfil(['ADMIN']);

$msg  = '';
$erro = '';

// ── Garante tabela ──────────────────────────────────────
pdo()->exec("CREATE TABLE IF NOT EXISTS `configuracoes` (
  `chave`     VARCHAR(100) NOT NULL,
  `valor`     TEXT         DEFAULT NULL,
  `descricao` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`chave`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// ── Valores padrão ─────────────────────────────────────
$defaults = [
    'empresa_nome'         => [APP_NAME,  'Nome da empresa exibido no sistema'],
    'empresa_cidade'       => ['Jales',   'Cidade sede'],
    'supervisor_nome'      => ['',        'Nome do supervisor para relatórios WA'],
    'supervisor_whatsapp'  => ['',        'WhatsApp do supervisor (DDD+número)'],
    'cidades_atendidas'    => ['Jales,Paranapuã,Santa Albertina,Mesópolis,Populina,Dirce Reis', 'Cidades separadas por vírgula'],
    'os_vencimento_dias'   => ['7',       'Dias até OS ser marcada como vencida'],
    'alerta_estoque_email' => ['',        'E-mail para alertas de estoque'],
    'logo_url'             => ['',        'Caminho relativo do logotipo'],
    // Cores principais
    'cor_primaria'         => ['#00d4ff', 'Cor principal (botões, links, destaques)'],
    'cor_acento'           => ['#ec4899', 'Cor de acento (badges, conclusão)'],
    'cor_fundo'            => ['#0d0714', 'Cor de fundo do sistema'],
    'cor_sidebar'          => ['#150a1e', 'Cor de fundo da barra lateral'],
    // Cores de superfície
    'cor_card'             => ['#1a1030', 'Cor de fundo dos cards e painéis'],
    'cor_card2'            => ['#1e1438', 'Cor de fundo secundária (inputs, selects)'],
    'cor_surface'          => ['#150a1e', 'Cor de superfície (header, sidebar)'],
    // Cores de texto
    'cor_texto'            => ['#e2e8f0', 'Cor do texto principal'],
    'cor_texto_muted'      => ['#94a3b8', 'Cor do texto secundário (muted)'],
    'cor_texto_placeholder'=> ['#64748b', 'Cor do placeholder dos inputs'],
    // Cores de borda
    'cor_borda'            => ['#2d1f4e', 'Cor das bordas gerais'],
    'cor_borda2'           => ['#3d2a66', 'Cor das bordas em hover/foco'],
    'cor_borda_tabela'     => ['#2d1f4e', 'Cor das bordas das tabelas'],
    // Cores de estado
    'cor_sucesso'          => ['#10b981', 'Cor de sucesso/confirmação (verde)'],
    'cor_erro'             => ['#ef4444', 'Cor de erro/perigo (vermelho)'],
    'cor_aviso'            => ['#f59e0b', 'Cor de aviso/atenção (laranja)'],
    'cor_info'             => ['#3b82f6', 'Cor de informação (azul)'],
    'cor_purple'           => ['#a855f7', 'Cor roxa (agendamentos, destaque)'],
    // Badges
    'cor_badge_red'        => ['#ef4444', 'Cor do badge vermelho'],
    'cor_badge_green'      => ['#10b981', 'Cor do badge verde'],
    'cor_badge_amber'      => ['#f59e0b', 'Cor do badge laranja'],
    'cor_badge_cyan'       => ['#00d4ff', 'Cor do badge ciano'],
    'cor_badge_purple'     => ['#a855f7', 'Cor do badge roxo'],
    'cor_badge_muted'      => ['#64748b', 'Cor do badge cinza'],
    // Bordas e efeitos
    'bordas_arredondadas'  => ['10', 'Raio de arredondamento global (px)'],
    'efeito_sombra'        => ['media', 'Intensidade das sombras/glow (nenhuma/leve/media/intensa)'],
    'borda_tabela_estilo'  => ['solid', 'Estilo da borda das tabelas (solid/dashed/dotted/none)'],
    'borda_tabela_largura' => ['1', 'Espessura da borda das tabelas (px)'],
    // Tipografia
    'fonte_principal'      => ['Exo 2',        'Fonte principal do sistema'],
    'fonte_mono'           => ['Share Tech Mono','Fonte monoespaçada (códigos, badges)'],
    'tamanho_fonte_base'   => ['14',      'Tamanho base da fonte em px'],
    'peso_fonte'           => ['400', 'Peso da fonte (400/500/600/700)'],
    'altura_linha'         => ['1.5', 'Altura da linha (line-height)'],
    'espacamento_letras'   => ['0', 'Espaçamento entre letras (px)'],
    'tamanho_titulo'       => ['20', 'Tamanho dos títulos (px)'],
    // WhatsApp
    'wa_api_url'           => ['',        'URL base da Evolution API'],
    'wa_api_token'         => ['',        'Global apikey do Evolution API'],
    'wa_instancia'         => ['',        'Nome exato da instância'],
    'wa_url_publica'       => ['',        'URL pública do sistema para fotos'],
];

$stmtIns = pdo()->prepare("INSERT IGNORE INTO configuracoes (chave, valor, descricao) VALUES (?,?,?)");
foreach ($defaults as $k => [$v, $d]) $stmtIns->execute([$k, $v, $d]);

// ── POST: salvar ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrf($_POST['csrf_token'] ?? '')) die('CSRF inválido');
    $stmtUpd = pdo()->prepare("UPDATE configuracoes SET valor=? WHERE chave=?");
    foreach ($_POST['cfg'] ?? [] as $chave => $valor) {
        $chave = preg_replace('/[^a-z0-9_]/', '', $chave);
        $stmtUpd->execute([trim($valor), $chave]);
    }
    // Upload do logotipo
    if (!empty($_FILES['logo_file']['name'])) {
        $f   = $_FILES['logo_file'];
        $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg','jpeg','png','svg','webp'])) {
            $erro = 'Formato do logo inválido. Use JPG, PNG, SVG ou WEBP.';
        } elseif ($f['size'] > 2*1024*1024) {
            $erro = 'Logo muito grande (máx. 2 MB).';
        } elseif ($f['error'] !== UPLOAD_ERR_OK) {
            $erro = 'Erro no upload do logo.';
        } else {
            $dir = __DIR__ . '/uploads/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $logoAtual = getConfig('logo_url', '');
            if ($logoAtual && file_exists(__DIR__ . '/' . ltrim($logoAtual,'/'))) {
                @unlink(__DIR__ . '/' . ltrim($logoAtual,'/'));
            }
            $nome = 'logo_' . time() . '.' . $ext;
            if (move_uploaded_file($f['tmp_name'], $dir . $nome)) {
                $stmtUpd->execute(['uploads/' . $nome, 'logo_url']);
            } else {
                $erro = 'Falha ao salvar o logo.';
            }
        }
    }
    if (isset($_POST['excluir_logo'])) {
        $logoAtual = getConfig('logo_url', '');
        if ($logoAtual && file_exists(__DIR__ . '/' . ltrim($logoAtual,'/'))) {
            @unlink(__DIR__ . '/' . ltrim($logoAtual,'/'));
        }
        $stmtUpd->execute(['', 'logo_url']);
    }
    if (!$erro) $msg = '✓ Configurações salvas com sucesso!';
}

// ── Lê valores atuais ──────────────────────────────────
$cfgs = pdo()->query("SELECT chave, valor FROM configuracoes")->fetchAll(PDO::FETCH_KEY_PAIR);
$cv   = fn(string $k, string $d='') => $cfgs[$k] ?? $d;
$logoAtual = $cv('logo_url');
$logoExiste= $logoAtual && file_exists(__DIR__ . '/' . ltrim($logoAtual,'/'));

require_once __DIR__ . '/includes/header.php';
?>
<style>
.tab-nav{display:flex;gap:4px;margin-bottom:20px;background:var(--card2);border-radius:10px;padding:5px;border:1px solid var(--border);flex-wrap:wrap}
.tab-btn{flex:1;min-width:100px;padding:9px 14px;border:none;border-radius:7px;background:none;color:var(--muted);cursor:pointer;font-size:11px;font-family:var(--mono);font-weight:700;letter-spacing:.8px;transition:.15s;white-space:nowrap;text-align:center}
.tab-btn:hover{color:var(--text);background:rgba(255,255,255,.05)}
.tab-btn.active{background:var(--cyan);color:#050e1a;box-shadow:0 0 12px var(--cyan)44}
.tab-pane{display:none}.tab-pane.active{display:block}
.cfg-section{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:20px;margin-bottom:16px}
.cfg-section-title{font-size:10px;font-family:var(--mono);color:var(--cyan);letter-spacing:2px;margin-bottom:14px;padding-bottom:8px;border-bottom:1px solid rgba(0,212,255,.12)}
.color-preview{width:36px;height:36px;border-radius:7px;border:2px solid var(--border);flex-shrink:0;cursor:pointer;transition:.2s;position:relative}
.color-preview input[type=color]{position:absolute;inset:0;opacity:0;cursor:pointer}
.color-wrap{display:flex;align-items:center;gap:8px}
.preview-swatch{width:100%;height:36px;border-radius:8px;border:1px solid var(--border);margin-top:10px;display:flex;overflow:hidden}
.swatch-seg{flex:1;display:flex;align-items:center;justify-content:center;font-size:9px;font-family:var(--mono);font-weight:700;color:rgba(255,255,255,.8)}
.logo-preview{max-height:60px;max-width:200px;object-fit:contain;border-radius:6px;border:1px solid var(--border);padding:6px;background:var(--card)}
.upload-zone-sm{border:2px dashed var(--border2);border-radius:8px;padding:16px;text-align:center;cursor:pointer;position:relative;transition:.2s}
.upload-zone-sm:hover{border-color:var(--cyan);background:rgba(0,212,255,.04)}
.upload-zone-sm input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.font-preview{padding:10px 14px;background:var(--card2);border-radius:8px;border:1px solid var(--border);margin-top:10px;color:var(--text);min-height:42px;transition:all .2s}
.size-btn{padding:6px 14px;border:1px solid var(--border);border-radius:6px;background:var(--card2);color:var(--text);cursor:pointer;font-size:12px;transition:.15s}
.size-btn:hover{border-color:var(--cyan);color:var(--cyan)}
.size-btn.active{border-color:var(--cyan);background:rgba(0,212,255,.12);color:var(--cyan);font-weight:700}
.range-row{display:flex;align-items:center;gap:12px;margin-top:8px}
.range-row input[type=range]{flex:1;accent-color:var(--cyan)}
.range-val{font-family:var(--mono);font-size:12px;color:var(--cyan);min-width:48px;text-align:right;font-weight:700}
.opt-btn-group{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
.opt-btn{padding:6px 14px;border:1px solid var(--border);border-radius:6px;background:var(--card2);color:var(--text);cursor:pointer;font-size:11px;transition:.15s;font-family:var(--mono)}
.opt-btn:hover{border-color:var(--cyan);color:var(--cyan)}
.opt-btn.active{border-color:var(--cyan);background:rgba(0,212,255,.12);color:var(--cyan);font-weight:700}
.tabela-preview{width:100%;border-collapse:collapse;margin-top:10px;font-size:12px}
.tabela-preview th,.tabela-preview td{padding:8px 10px;text-align:left}
.tabela-preview thead th{background:var(--card2);color:var(--cyan);font-family:var(--mono);font-size:10px;letter-spacing:1px}
.radius-box{width:64px;height:64px;background:var(--card2);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;font-size:10px;color:var(--muted);font-family:var(--mono)}
.shadow-box{width:80px;height:64px;border-radius:10px;background:var(--card2);display:flex;align-items:center;justify-content:center;font-size:9px;color:var(--muted);font-family:var(--mono);transition:all .2s}
.badge-preview{display:inline-flex;padding:4px 10px;border-radius:20px;font-size:10px;font-weight:700;font-family:var(--mono);margin:3px}
</style>

<div class="topbar"><button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
  <div>
    <div class="page-title">⚙ Configurações do Sistema</div>
    <div class="page-sub">Empresa · Cores · Bordas · Tipografia · WhatsApp</div>
  </div>
</div>

<div class="content" style="max-width:900px">

<?php if ($msg):  ?><div class="alert alert-success"><?= e($msg) ?></div><?php endif; ?>
<?php if ($erro): ?><div class="alert alert-danger"><?= e($erro) ?></div><?php endif; ?>

<div class="tab-nav">
  <button class="tab-btn active" onclick="abrirAba('empresa',this)">◎ Empresa</button>
  <button class="tab-btn"        onclick="abrirAba('cores',this)">🎨 Cores</button>
  <button class="tab-btn"        onclick="abrirAba('bordas',this)">✨ Bordas</button>
  <button class="tab-btn"        onclick="abrirAba('badges',this)">🏷 Badges</button>
  <button class="tab-btn"        onclick="abrirAba('tipografia',this)">🔤 Tipografia</button>
  <button class="tab-btn"        onclick="abrirAba('whatsapp',this)">📱 WhatsApp</button>
  <button class="tab-btn"        onclick="abrirAba('outros',this)">⚙ Outros</button>
</div>

<form method="post" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>"/>

<!-- ═══════════════ ABA: EMPRESA ═══════════════ -->
<div class="tab-pane active" id="tab-empresa">
<div class="cfg-section">
  <div class="cfg-section-title">◎ EMPRESA E IDENTIDADE</div>
  <div class="form-grid">
    <div class="form-group">
      <label class="form-label">NOME DA EMPRESA</label>
      <input class="form-input" type="text" name="cfg[empresa_nome]" value="<?= e($cv('empresa_nome',APP_NAME)) ?>" placeholder="MKT Telecom"/>
    </div>
    <div class="form-group">
      <label class="form-label">CIDADE SEDE</label>
      <input class="form-input" type="text" name="cfg[empresa_cidade]" value="<?= e($cv('empresa_cidade')) ?>" placeholder="Jales"/>
    </div>
    <div class="form-group full">
      <label class="form-label">LOGOTIPO</label>
      <div style="display:flex;align-items:center;gap:14px;flex-wrap:wrap">
        <?php if ($logoExiste): ?>
          <img src="<?= e($logoAtual) ?>" class="logo-preview" id="logo-preview-img" alt="Logo"/>
          <div>
            <div style="font-size:11px;color:var(--green);margin-bottom:8px">✓ Logo carregado</div>
            <button type="submit" name="excluir_logo" value="1" class="btn btn-danger btn-xs" onclick="return confirm('Remover o logo atual?')">✕ Remover</button>
          </div>
        <?php else: ?>
          <div id="logo-preview-wrap" style="width:80px;height:60px;background:var(--card2);border:1px dashed var(--border);border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:24px">🏢</div>
        <?php endif; ?>
        <div style="flex:1;min-width:200px">
          <div class="upload-zone-sm">
            <input type="file" name="logo_file" accept="image/jpeg,image/png,image/svg+xml,image/webp" onchange="previewLogo(this)"/>
            <div style="font-size:12px;color:var(--muted)"><b style="color:var(--text)">Clique ou arraste</b> para enviar novo logo</div>
            <div style="font-size:10px;color:var(--muted);margin-top:3px;font-family:var(--mono)">PNG · SVG · JPG · WEBP · Máx. 2 MB</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</div>

<!-- ═══════════════ ABA: CORES ═══════════════ -->
<div class="tab-pane" id="tab-cores">
<div class="cfg-section">
  <div class="cfg-section-title">🎨 TEMA DE CORES</div>
  <div class="form-grid cols4">
    <?php
    $coresTema = [
      'cor_primaria'=>['Principal','Botões, links', '#00d4ff'],
      'cor_acento'  =>['Acento','Badges, sucesso', '#ec4899'],
      'cor_fundo'   =>['Fundo','Background', '#0d0714'],
      'cor_sidebar' =>['Sidebar','Barra lateral', '#150a1e'],
    ];
    foreach ($coresTema as $k=>[$l,$d,$def]): $val=$cv($k,$def); ?>
    <div class="form-group">
      <label class="form-label"><?= $l ?></label>
      <div class="color-wrap">
        <div class="color-preview" id="prev_<?= $k ?>" style="background:<?= e($val) ?>" onclick="document.getElementById('col_<?= $k ?>').click()">
          <input type="color" id="col_<?= $k ?>" value="<?= e($val) ?>" oninput="sinc('<?= $k ?>')"/>
        </div>
        <input class="form-input" type="text" id="txt_<?= $k ?>" name="cfg[<?= $k ?>]" value="<?= e($val) ?>" oninput="sincTxt('<?= $k ?>')" style="font-family:var(--mono);font-size:12px"/>
      </div>
      <div class="form-hint"><?= $d ?></div>
    </div>
    <?php endforeach; ?>
  </div>
  <div style="margin-top:14px">
    <div class="form-label">PALETAS RÁPIDAS</div>
    <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:6px">
      <?php
      $paletas = [
        'Ciano'=>'#00d4ff,#ec4899,#0d0714,#150a1e',
        'Azul'=>'#3b82f6,#6366f1,#05080f,#0a0f1e',
        'Verde'=>'#22c55e,#84cc16,#061008,#091510',
        'Laranja'=>'#f97316,#ef4444,#120801,#1a0c03',
        'Roxo'=>'#a855f7,#ec4899,#0d0714,#150a1e',
        'Ouro'=>'#f59e0b,#fbbf24,#110e01,#1a1502',
      ];
      foreach($paletas as $n=>$p): ?>
      <button type="button" class="btn btn-ghost btn-xs" onclick="aplicarPaleta('<?= $p ?>')"><?= $n ?></button>
      <?php endforeach; ?>
      <button type="button" class="btn btn-ghost btn-xs" onclick="aplicarPaleta('#00d4ff,#ec4899,#0d0714,#150a1e')">↺ Reset</button>
    </div>
  </div>
</div>

<div class="cfg-section">
  <div class="cfg-section-title">🖋 SUPERFÍCIES E TEXTO</div>
  <div class="form-grid cols4">
    <?php
    $coresSup = [
      'cor_card'=>['Cards','Fundo cards', '#1a1030'],
      'cor_card2'=>['Inputs','Fundo inputs', '#1e1438'],
      'cor_surface'=>['Superfície','Header/sidebar', '#150a1e'],
      'cor_texto'=>['Texto','Texto principal', '#e2e8f0'],
      'cor_texto_muted'=>['Muted','Texto secundário', '#94a3b8'],
      'cor_texto_placeholder'=>['Placeholder','Placeholders', '#64748b'],
      'cor_borda'=>['Borda','Bordas gerais', '#2d1f4e'],
      'cor_borda2'=>['Borda Hover','Bordas hover/foco', '#3d2a66'],
    ];
    foreach ($coresSup as $k=>[$l,$d,$def]): $val=$cv($k,$def); ?>
    <div class="form-group">
      <label class="form-label"><?= $l ?></label>
      <div class="color-wrap">
        <div class="color-preview" id="prev_<?= $k ?>" style="background:<?= e($val) ?>" onclick="document.getElementById('col_<?= $k ?>').click()">
          <input type="color" id="col_<?= $k ?>" value="<?= e($val) ?>" oninput="sinc('<?= $k ?>')"/>
        </div>
        <input class="form-input" type="text" id="txt_<?= $k ?>" name="cfg[<?= $k ?>]" value="<?= e($val) ?>" oninput="sincTxt('<?= $k ?>')" style="font-family:var(--mono);font-size:12px"/>
      </div>
      <div class="form-hint"><?= $d ?></div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<div class="cfg-section">
  <div class="cfg-section-title">🚦 CORES DE ESTADO</div>
  <div class="form-grid cols4">
    <?php
    $coresEst = [
      'cor_sucesso'=>['Sucesso','#10b981'],
      'cor_erro'=>['Erro','#ef4444'],
      'cor_aviso'=>['Aviso','#f59e0b'],
      'cor_info'=>['Info','#3b82f6'],
      'cor_purple'=>['Roxo','#a855f7'],
    ];
    foreach ($coresEst as $k=>[$l,$def]): $val=$cv($k,$def); ?>
    <div class="form-group">
      <label class="form-label"><?= $l ?></label>
      <div class="color-wrap">
        <div class="color-preview" id="prev_<?= $k ?>" style="background:<?= e($val) ?>" onclick="document.getElementById('col_<?= $k ?>').click()">
          <input type="color" id="col_<?= $k ?>" value="<?= e($val) ?>" oninput="sinc('<?= $k ?>')"/>
        </div>
        <input class="form-input" type="text" id="txt_<?= $k ?>" name="cfg[<?= $k ?>]" value="<?= e($val) ?>" oninput="sincTxt('<?= $k ?>')" style="font-family:var(--mono);font-size:12px"/>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <div class="preview-swatch">
    <div class="swatch-seg" id="sw-suc" style="background:<?= e($cv('cor_sucesso','#10b981')) ?>;color:#050e1a">SUCESSO</div>
    <div class="swatch-seg" id="sw-err" style="background:<?= e($cv('cor_erro','#ef4444')) ?>;color:#fff">ERRO</div>
    <div class="swatch-seg" id="sw-avi" style="background:<?= e($cv('cor_aviso','#f59e0b')) ?>;color:#050e1a">AVISO</div>
    <div class="swatch-seg" id="sw-inf" style="background:<?= e($cv('cor_info','#3b82f6')) ?>;color:#fff">INFO</div>
    <div class="swatch-seg" id="sw-pur" style="background:<?= e($cv('cor_purple','#a855f7')) ?>;color:#fff">ROXO</div>
  </div>
</div>
</div><!-- /tab-cores -->

<!-- ═══════════════ ABA: BORDAS ═══════════════ -->
<div class="tab-pane" id="tab-bordas">
<div class="cfg-section">
  <div class="cfg-section-title">✨ BORDAS, RAIO E EFEITOS</div>

  <div class="form-group" style="margin-bottom:18px">
    <label class="form-label">RAIO DE ARREDONDAMENTO GLOBAL</label>
    <input type="hidden" name="cfg[bordas_arredondadas]" id="inp-raio" value="<?= e($cv('bordas_arredondadas','10')) ?>"/>
    <div class="range-row">
      <input type="range" min="0" max="24" step="1" value="<?= e($cv('bordas_arredondadas','10')) ?>" oninput="atualizarRaio(this.value)"/>
      <span class="range-val" id="raio-val"><?= e($cv('bordas_arredondadas','10')) ?>px</span>
    </div>
    <div class="range-row" style="margin-top:10px">
      <div class="radius-box" id="raio-prev-card" style="border-radius:<?= e($cv('bordas_arredondadas','10')) ?>px">Card</div>
      <div class="radius-box" id="raio-prev-btn" style="border-radius:<?= (int)$cv('bordas_arredondadas','10')/2 ?>px;width:90px">Botão</div>
      <div class="radius-box" id="raio-prev-input" style="border-radius:<?= (int)$cv('bordas_arredondadas','10')/1.5 ?>px;width:90px">Input</div>
    </div>
  </div>

  <div class="form-group" style="margin-bottom:18px">
    <label class="form-label">INTENSIDADE DE SOMBRAS / GLOW</label>
    <input type="hidden" name="cfg[efeito_sombra]" id="inp-sombra" value="<?= e($cv('efeito_sombra','media')) ?>"/>
    <div class="opt-btn-group" id="grp-sombra">
      <?php $sombras=['nenhuma'=>'Nenhuma','leve'=>'Leve','media'=>'Média','intensa'=>'Intensa']; $sAt=$cv('efeito_sombra','media'); foreach($sombras as $v=>$l): ?>
      <button type="button" class="opt-btn <?= $sAt==$v?'active':'' ?>" data-val="<?= $v ?>" onclick="selecionarOpt('sombra','<?= $v ?>')"><?= $l ?></button>
      <?php endforeach; ?>
    </div>
    <div class="range-row" style="margin-top:10px">
      <?php $sombraMap=['nenhuma'=>'none','leve'=>'0 2px 8px rgba(0,0,0,.3)','media'=>'0 4px 20px rgba(0,0,0,.4), 0 0 12px rgba(0,212,255,.15)','intensa'=>'0 8px 32px rgba(0,0,0,.5), 0 0 24px rgba(0,212,255,.35)']; ?>
      <div class="shadow-box" id="sombra-prev" style="box-shadow:<?= $sombraMap[$sAt] ?>;border-radius:<?= e($cv('bordas_arredondadas','10')) ?>px">Preview</div>
    </div>
  </div>

  <div class="form-group">
    <label class="form-label">BORDA DAS TABELAS</label>
    <div class="form-grid cols4" style="margin-top:8px">
      <div class="form-group">
        <label class="form-label" style="font-size:9px">COR</label>
        <div class="color-wrap">
          <div class="color-preview" id="prev_cor_borda_tabela" style="background:<?= e($cv('cor_borda_tabela','#2d1f4e')) ?>" onclick="document.getElementById('col_cor_borda_tabela').click()">
            <input type="color" id="col_cor_borda_tabela" value="<?= e($cv('cor_borda_tabela','#2d1f4e')) ?>" oninput="sinc('cor_borda_tabela')"/>
          </div>
          <input class="form-input" type="text" id="txt_cor_borda_tabela" name="cfg[cor_borda_tabela]" value="<?= e($cv('cor_borda_tabela','#2d1f4e')) ?>" oninput="sincTxt('cor_borda_tabela')" style="font-family:var(--mono);font-size:12px"/>
        </div>
      </div>
      <div class="form-group">
        <label class="form-label" style="font-size:9px">ESTILO</label>
        <input type="hidden" name="cfg[borda_tabela_estilo]" id="inp-borda-estilo" value="<?= e($cv('borda_tabela_estilo','solid')) ?>"/>
        <div class="opt-btn-group" id="grp-borda-estilo">
          <?php $estilos=['solid'=>'Sólida','dashed'=>'Tracejada','dotted'=>'Pontilhada','none'=>'Nenhuma']; $eAt=$cv('borda_tabela_estilo','solid'); foreach($estilos as $v=>$l): ?>
          <button type="button" class="opt-btn <?= $eAt==$v?'active':'' ?>" data-val="<?= $v ?>" onclick="selecionarOpt('borda-estilo','<?= $v ?>')"><?= $l ?></button>
          <?php endforeach; ?>
        </div>
      </div>
      <div class="form-group">
        <label class="form-label" style="font-size:9px">ESPESSURA</label>
        <input type="hidden" name="cfg[borda_tabela_largura]" id="inp-borda-largura" value="<?= e($cv('borda_tabela_largura','1')) ?>"/>
        <div class="range-row">
          <input type="range" min="0" max="4" step="1" value="<?= e($cv('borda_tabela_largura','1')) ?>" oninput="atualizarBordaTabela(this.value)"/>
          <span class="range-val" id="borda-largura-val"><?= e($cv('borda_tabela_largura','1')) ?>px</span>
        </div>
      </div>
    </div>
    <table class="tabela-preview" id="tab-prev">
      <thead><tr><th>CLIENTE</th><th>PLANO</th><th>STATUS</th></tr></thead>
      <tbody>
        <tr><td>João Silva</td><td>300 MB</td><td>Ativo</td></tr>
        <tr><td>Maria Souza</td><td>500 MB</td><td>Bloqueado</td></tr>
      </tbody>
    </table>
  </div>
</div>
</div><!-- /tab-bordas -->

<!-- ═══════════════ ABA: BADGES ═══════════════ -->
<div class="tab-pane" id="tab-badges">
<div class="cfg-section">
  <div class="cfg-section-title">🏷 CORES DOS BADGES</div>
  <div class="form-grid cols4">
    <?php
    $badges = [
      'cor_badge_red'=>['Vermelho','#ef4444'],
      'cor_badge_green'=>['Verde','#10b981'],
      'cor_badge_amber'=>['Laranja','#f59e0b'],
      'cor_badge_cyan'=>['Ciano','#00d4ff'],
      'cor_badge_purple'=>['Roxo','#a855f7'],
      'cor_badge_muted'=>['Cinza','#64748b'],
    ];
    foreach ($badges as $k=>[$l,$def]): $val=$cv($k,$def); ?>
    <div class="form-group">
      <label class="form-label"><?= $l ?></label>
      <div class="color-wrap">
        <div class="color-preview" id="prev_<?= $k ?>" style="background:<?= e($val) ?>" onclick="document.getElementById('col_<?= $k ?>').click()">
          <input type="color" id="col_<?= $k ?>" value="<?= e($val) ?>" oninput="sinc('<?= $k ?>')"/>
        </div>
        <input class="form-input" type="text" id="txt_<?= $k ?>" name="cfg[<?= $k ?>]" value="<?= e($val) ?>" oninput="sincTxt('<?= $k ?>')" style="font-family:var(--mono);font-size:12px"/>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <div style="margin-top:14px">
    <div class="form-label">PREVIEW DOS BADGES</div>
    <div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px">
      <span class="badge-preview" id="badge-red-prev" style="background:<?= e($cv('cor_badge_red','#ef4444')) ?>1a;color:<?= e($cv('cor_badge_red','#ef4444')) ?>;border:1px solid <?= e($cv('cor_badge_red','#ef4444')) ?>33">BLOQUEADO</span>
      <span class="badge-preview" id="badge-green-prev" style="background:<?= e($cv('cor_badge_green','#10b981')) ?>1a;color:<?= e($cv('cor_badge_green','#10b981')) ?>;border:1px solid <?= e($cv('cor_badge_green','#10b981')) ?>33">ATIVO</span>
      <span class="badge-preview" id="badge-amber-prev" style="background:<?= e($cv('cor_badge_amber','#f59e0b')) ?>1a;color:<?= e($cv('cor_badge_amber','#f59e0b')) ?>;border:1px solid <?= e($cv('cor_badge_amber','#f59e0b')) ?>33">PENDENTE</span>
      <span class="badge-preview" id="badge-cyan-prev" style="background:<?= e($cv('cor_badge_cyan','#00d4ff')) ?>1a;color:<?= e($cv('cor_badge_cyan','#00d4ff')) ?>;border:1px solid <?= e($cv('cor_badge_cyan','#00d4ff')) ?>33">ANDAMENTO</span>
      <span class="badge-preview" id="badge-purple-prev" style="background:<?= e($cv('cor_badge_purple','#a855f7')) ?>1a;color:<?= e($cv('cor_badge_purple','#a855f7')) ?>;border:1px solid <?= e($cv('cor_badge_purple','#a855f7')) ?>33">AGENDADA</span>
      <span class="badge-preview" id="badge-muted-prev" style="background:<?= e($cv('cor_badge_muted','#64748b')) ?>1a;color:<?= e($cv('cor_badge_muted','#64748b')) ?>;border:1px solid <?= e($cv('cor_badge_muted','#64748b')) ?>33">CANCELADA</span>
    </div>
  </div>
</div>
</div><!-- /tab-badges -->

<!-- ═══════════════ ABA: TIPOGRAFIA ═══════════════ -->
<div class="tab-pane" id="tab-tipografia">
<div class="cfg-section">
  <div class="cfg-section-title">🔤 TIPOGRAFIA</div>

  <!-- Fonte Principal -->
  <div class="form-group" style="margin-bottom:20px">
    <label class="form-label">FONTE PRINCIPAL</label>
    <select class="form-select" name="cfg[fonte_principal]" id="sel-fonte-principal" onchange="atualizarPrevFonte()" style="margin-top:6px">
      <?php
      $fontes = ['Exo 2','Inter','Roboto','Open Sans','Nunito','Poppins','Lato','Montserrat','Raleway','Ubuntu','Source Sans 3','Fira Sans','DM Sans','Quicksand','Work Sans','Manrope','Titillium Web','Jost','Karla','Rubik','Heebo','Assistant','Mukta','Noto Sans','PT Sans','Oswald','Fjalla One','Barlow','Saira','Archivo'];
      $fAt = $cv('fonte_principal','Exo 2');
      foreach($fontes as $f): ?>
      <option value="<?= e($f) ?>" <?= $fAt==$f?'selected':'' ?>><?= e($f) ?></option>
      <?php endforeach; ?>
    </select>
    <div class="font-preview" id="prev-fonte-principal" style="font-family:'<?= e($fAt) ?>',sans-serif">O roteador foi instalado com sucesso. Velocidade: 300 Mbps — Serviço ativo ✓</div>
  </div>

  <!-- Fonte Monoespaçada -->
  <div class="form-group" style="margin-bottom:20px">
    <label class="form-label">FONTE MONOESPAÇADA</label>
    <select class="form-select" name="cfg[fonte_mono]" id="sel-fonte-mono" onchange="atualizarPrevFonteMono()" style="margin-top:6px">
      <?php
      $mono = ['Share Tech Mono','JetBrains Mono','Fira Code','Source Code Pro','Roboto Mono','Ubuntu Mono','Space Mono','Inconsolata','Courier Prime','IBM Plex Mono','Nova Mono','Anonymous Pro','Cousine','Cutive Mono','Major Mono Display','Syne Mono','Fantasque Sans Mono','Mononoki','Victor Mono','Iosevka'];
      $mAt = $cv('fonte_mono','Share Tech Mono');
      foreach($mono as $f): ?>
      <option value="<?= e($f) ?>" <?= $mAt==$f?'selected':'' ?>><?= e($f) ?></option>
      <?php endforeach; ?>
    </select>
    <div class="font-preview" id="prev-fonte-mono" style="font-family:'<?= e($mAt) ?>',monospace;font-size:12px">PPPoE: cliente@mkt | Senha: mbc80480# | IP: 192.168.1.146 | VLAN: 1001</div>
  </div>

  <!-- Tamanho base -->
  <div class="form-group" style="margin-bottom:20px">
    <label class="form-label">TAMANHO BASE</label>
    <select class="form-select" name="cfg[tamanho_fonte_base]" id="sel-tamanho" onchange="atualizarPrevTamanho()" style="margin-top:6px">
      <?php for($px=11;$px<=18;$px++): $s=($px==14)?' (padrão)':''; ?>
      <option value="<?= $px ?>" <?= $cv('tamanho_fonte_base','14')==$px?'selected':'' ?>><?= $px ?>px<?= $s ?></option>
      <?php endfor; ?>
    </select>
    <div class="font-preview" id="prev-tamanho" style="font-size:<?= e($cv('tamanho_fonte_base','14')) ?>px">OS #2026-0019 · João da Silva · Status: CONCLUÍDA</div>
  </div>

  <!-- Peso da fonte -->
  <div class="form-group" style="margin-bottom:20px">
    <label class="form-label">PESO DA FONTE</label>
    <input type="hidden" name="cfg[peso_fonte]" id="inp-peso" value="<?= e($cv('peso_fonte','400')) ?>"/>
    <div class="opt-btn-group" id="grp-peso">
      <?php $pesos=['400'=>'Normal','500'=>'Médio','600'=>'Semi-negrito','700'=>'Negrito']; $pAt=$cv('peso_fonte','400'); foreach($pesos as $v=>$l): ?>
      <button type="button" class="opt-btn <?= $pAt==$v?'active':'' ?>" data-val="<?= $v ?>" onclick="selecionarOpt('peso','<?= $v ?>');document.getElementById('prev-peso').style.fontWeight='<?= $v ?>'"><?= $l ?></button>
      <?php endforeach; ?>
    </div>
    <div class="font-preview" id="prev-peso" style="font-weight:<?= e($pAt) ?>">Técnico em campo: Carlos Eduardo · OS #0042 · Bairro Centro</div>
  </div>

  <!-- Altura da linha -->
  <div class="form-group" style="margin-bottom:20px">
    <label class="form-label">ALTURA DA LINHA</label>
    <input type="hidden" name="cfg[altura_linha]" id="inp-linha" value="<?= e($cv('altura_linha','1.5')) ?>"/>
    <div class="range-row">
      <input type="range" min="1.1" max="2.0" step="0.1" value="<?= e($cv('altura_linha','1.5')) ?>" oninput="rangeUpdate('linha',this.value,'prev-linha','lineHeight','')"/>
      <span class="range-val" id="linha-val"><?= e($cv('altura_linha','1.5')) ?></span>
    </div>
    <div class="font-preview" id="prev-linha" style="line-height:<?= e($cv('altura_linha','1.5')) ?>">Cliente sem conexão desde 08:40. Técnico despachado para verificar a ONU e o cabo drop até a caixa CTO mais próxima.</div>
  </div>

  <!-- Espaçamento entre letras -->
  <div class="form-group" style="margin-bottom:20px">
    <label class="form-label">ESPAÇAMENTO ENTRE LETRAS</label>
    <input type="hidden" name="cfg[espacamento_letras]" id="inp-esp" value="<?= e($cv('espacamento_letras','0')) ?>"/>
    <div class="range-row">
      <input type="range" min="-0.5" max="2" step="0.1" value="<?= e($cv('espacamento_letras','0')) ?>" oninput="rangeUpdate('esp',this.value,'prev-esp','letterSpacing','px')"/>
      <span class="range-val" id="esp-val"><?= e($cv('espacamento_letras','0')) ?>px</span>
    </div>
    <div class="font-preview" id="prev-esp" style="letter-spacing:<?= e($cv('espacamento_letras','0')) ?>px">PAINEL DE CONTROLE · MKT TELECOM</div>
  </div>

  <!-- Tamanho dos títulos -->
  <div class="form-group">
    <label class="form-label">TAMANHO DOS TÍTULOS</label>
    <select class="form-select" name="cfg[tamanho_titulo]" id="sel-titulo" onchange="atualizarPrevTitulo()" style="margin-top:6px">
      <?php for($px=18;$px<=28;$px+=2): ?>
      <option value="<?= $px ?>" <?= $cv('tamanho_titulo','20')==$px?'selected':'' ?>><?= $px ?>px</option>
      <?php endfor; ?>
    </select>
    <div class="font-preview" id="prev-titulo" style="font-size:<?= e($cv('tamanho_titulo','20')) ?>px;font-weight:700">⚙ Configurações do Sistema</div>
  </div>
</div>
</div><!-- /tab-tipografia -->

<!-- ═══════════════ ABA: WHATSAPP ═══════════════ -->
<div class="tab-pane" id="tab-whatsapp">
<div class="cfg-section">
  <div class="cfg-section-title">📱 WHATSAPP — EVOLUTION API</div>
  <div id="wa-status-box" style="background:var(--card2);border:1px solid var(--border);border-radius:8px;padding:12px 14px;display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px;flex-wrap:wrap">
    <div style="display:flex;align-items:center;gap:10px">
      <div id="wa-status-dot" style="width:12px;height:12px;border-radius:50%;background:var(--muted);flex-shrink:0;transition:.3s"></div>
      <div>
        <div id="wa-status-text" style="font-size:12px;font-weight:700">Status: não verificado</div>
        <div id="wa-status-sub" style="font-size:10px;color:var(--muted);font-family:var(--mono)">Salve e clique em Testar Conexão</div>
      </div>
    </div>
    <div style="display:flex;gap:8px">
      <button type="button" class="btn btn-ghost btn-sm" onclick="testarWA()">🔌 Testar Conexão</button>
      <a id="wa-qr-link" href="#" target="_blank" class="btn btn-ghost btn-sm" style="display:none">📷 QR Code</a>
    </div>
  </div>
  <div class="form-grid">
    <div class="form-group full"><label class="form-label">URL DA API</label><input class="form-input" type="text" name="cfg[wa_api_url]" value="<?= e($cv('wa_api_url')) ?>" placeholder="http://192.168.1.10:8080" style="font-family:var(--mono)"/></div>
    <div class="form-group"><label class="form-label">GLOBAL APIKEY</label><input class="form-input" type="text" name="cfg[wa_api_token]" value="<?= e($cv('wa_api_token')) ?>" placeholder="2BB9F404F2F2C9974E3AB5C7" style="font-family:var(--mono)"/></div>
    <div class="form-group"><label class="form-label">NOME DA INSTÂNCIA</label><input class="form-input" type="text" name="cfg[wa_instancia]" value="<?= e($cv('wa_instancia')) ?>" placeholder="mkt-telecom" style="font-family:var(--mono)"/></div>
    <div class="form-group full"><label class="form-label">URL PÚBLICA</label><input class="form-input" type="text" name="cfg[wa_url_publica]" value="<?= e($cv('wa_url_publica')) ?>" placeholder="http://191.241.137.22:8010/mkt_telecom" style="font-family:var(--mono)"/></div>
  </div>
</div>
</div><!-- /tab-whatsapp -->

<!-- ═══════════════ ABA: OUTROS ═══════════════ -->
<div class="tab-pane" id="tab-outros">
<div class="cfg-section">
  <div class="cfg-section-title">👤 SUPERVISOR</div>
  <div class="form-grid">
    <div class="form-group"><label class="form-label">NOME</label><input class="form-input" type="text" name="cfg[supervisor_nome]" value="<?= e($cv('supervisor_nome')) ?>" placeholder="João da Silva"/></div>
    <div class="form-group"><label class="form-label">WHATSAPP</label><input class="form-input" type="tel" name="cfg[supervisor_whatsapp]" value="<?= e($cv('supervisor_whatsapp')) ?>" placeholder="17999999999"/></div>
  </div>
</div>
<div class="cfg-section">
  <div class="cfg-section-title">⚙ OPERACIONAL</div>
  <div class="form-grid">
    <div class="form-group full"><label class="form-label">CIDADES ATENDIDAS</label><input class="form-input" type="text" name="cfg[cidades_atendidas]" value="<?= e($cv('cidades_atendidas')) ?>" placeholder="Jales,Paranapuã,..."/></div>
    <div class="form-group"><label class="form-label">DIAS ATÉ OS VENCIDA</label><input class="form-input" type="number" name="cfg[os_vencimento_dias]" value="<?= e($cv('os_vencimento_dias','7')) ?>" min="1" max="60"/></div>
    <div class="form-group"><label class="form-label">E-MAIL ALERTAS ESTOQUE</label><input class="form-input" type="email" name="cfg[alerta_estoque_email]" value="<?= e($cv('alerta_estoque_email')) ?>" placeholder="alerta@mkt.com.br"/></div>
  </div>
</div>
</div><!-- /tab-outros -->

<div style="display:flex;justify-content:flex-end;gap:10px;padding-bottom:32px;margin-top:8px">
  <button type="reset" class="btn btn-ghost" onclick="location.reload()">↺ Descartar</button>
  <button type="submit" class="btn btn-primary">✓ Salvar Configurações</button>
</div>
</form>
</div><!-- /content -->

<script>
// ═══════════════ ABAS ═══════════════
function abrirAba(id,btn){document.querySelectorAll('.tab-pane').forEach(p=>p.classList.remove('active'));document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));document.getElementById('tab-'+id).classList.add('active');btn.classList.add('active')}
(function(){const a=new URLSearchParams(location.search).get('aba');if(a){const b=document.querySelector(`.tab-btn[onclick*="'${a}'"]`);if(b)abrirAba(a,b)}})();

// ═══════════════ CORES ═══════════════
function sinc(k){const c=document.getElementById('col_'+k).value;document.getElementById('txt_'+k).value=c;document.getElementById('prev_'+k).style.background=c;atualizarPreviews(k)}
function sincTxt(k){const t=document.getElementById('txt_'+k).value;if(/^#[0-9a-fA-F]{3,6}$/.test(t)){document.getElementById('col_'+k).value=t;document.getElementById('prev_'+k).style.background=t;atualizarPreviews(k)}}
function atualizarPreviews(k){
  const v=document.getElementById('txt_'+k).value;
  if(k.startsWith('cor_badge_')){
    const badgeMap={cor_badge_red:'badge-red-prev',cor_badge_green:'badge-green-prev',cor_badge_amber:'badge-amber-prev',cor_badge_cyan:'badge-cyan-prev',cor_badge_purple:'badge-purple-prev',cor_badge_muted:'badge-muted-prev'};
    const el=document.getElementById(badgeMap[k]);
    if(el){el.style.background=v+'1a';el.style.color=v;el.style.borderColor=v+'33'}
  }
  if(['cor_sucesso','cor_erro','cor_aviso','cor_info','cor_purple'].includes(k)){
    const swMap={cor_sucesso:'sw-suc',cor_erro:'sw-err',cor_aviso:'sw-avi',cor_info:'sw-inf',cor_purple:'sw-pur'};
    const sw=document.getElementById(swMap[k]);if(sw)sw.style.background=v;
  }
  if(k==='cor_borda_tabela')atualizarTabela();
}
function aplicarPaleta(str){const[pri,acc,bg,side]=str.split(',');const s={cor_primaria:pri,cor_acento:acc,cor_fundo:bg,cor_sidebar:side};for(const[k,v]of Object.entries(s)){document.getElementById('col_'+k).value=v;document.getElementById('txt_'+k).value=v;document.getElementById('prev_'+k).style.background=v}}
function previewLogo(i){if(!i.files||!i.files[0])return;const r=new FileReader();r.onload=e=>{const el=document.getElementById('logo-preview-wrap')||document.getElementById('logo-preview-img');if(!el)return;if(el.tagName==='IMG')el.src=e.target.result;else el.innerHTML='<img src="'+e.target.result+'" style="max-height:54px;max-width:180px;object-fit:contain"/>'};r.readAsDataURL(i.files[0])}

// ═══════════════ BORDAS ═══════════════
function atualizarRaio(px){document.getElementById('inp-raio').value=px;document.getElementById('raio-val').textContent=px+'px';document.getElementById('raio-prev-card').style.borderRadius=px+'px';document.getElementById('raio-prev-btn').style.borderRadius=(px/2)+'px';document.getElementById('raio-prev-input').style.borderRadius=(px/1.5)+'px';document.getElementById('sombra-prev').style.borderRadius=px+'px'}
function selecionarOpt(grupo,valor){
  const map={sombra:'inp-sombra','borda-estilo':'inp-borda-estilo',peso:'inp-peso'};
  document.getElementById(map[grupo]).value=valor;
  document.querySelectorAll(`#grp-${grupo} .opt-btn`).forEach(b=>b.classList.toggle('active',b.dataset.val===valor));
  if(grupo==='sombra'){
    const sm={'nenhuma':'none','leve':'0 2px 8px rgba(0,0,0,.3)','media':'0 4px 20px rgba(0,0,0,.4), 0 0 12px rgba(0,212,255,.15)','intensa':'0 8px 32px rgba(0,0,0,.5), 0 0 24px rgba(0,212,255,.35)'};
    document.getElementById('sombra-prev').style.boxShadow=sm[valor]||sm.media;
  }
  if(grupo==='borda-estilo')atualizarTabela();
}
function atualizarBordaTabela(px){document.getElementById('inp-borda-largura').value=px;document.getElementById('borda-largura-val').textContent=px+'px';atualizarTabela()}
function atualizarTabela(){
  const l=document.getElementById('inp-borda-largura').value,e=document.getElementById('inp-borda-estilo').value,c=document.getElementById('txt_cor_borda_tabela').value;
  const b=`${l}px ${e} ${c}`;const t=document.getElementById('tab-prev');
  t.style.border=b;t.querySelectorAll('th,td').forEach(el=>el.style.border=b);
}

// ═══════════════ TIPOGRAFIA ═══════════════
function atualizarPrevFonte(){const f=document.getElementById('sel-fonte-principal').value;document.getElementById('prev-fonte-principal').style.fontFamily=`'${f}',sans-serif`}
function atualizarPrevFonteMono(){const f=document.getElementById('sel-fonte-mono').value;document.getElementById('prev-fonte-mono').style.fontFamily=`'${f}',monospace`}
function atualizarPrevTamanho(){const px=document.getElementById('sel-tamanho').value;document.getElementById('prev-tamanho').style.fontSize=px+'px'}
function atualizarPrevTitulo(){const px=document.getElementById('sel-titulo').value;document.getElementById('prev-titulo').style.fontSize=px+'px'}
function rangeUpdate(chave,valor,prevId,prop,sufixo){
  const map={linha:'inp-linha',esp:'inp-esp'};
  document.getElementById(map[chave]).value=valor;
  document.getElementById(chave+'-val').textContent=valor+sufixo;
  document.getElementById(prevId).style[prop]=valor+sufixo;
}

// ═══════════════ WHATSAPP ═══════════════
function testarWA(){
  const d=document.getElementById('wa-status-dot'),t=document.getElementById('wa-status-text'),s=document.getElementById('wa-status-sub'),q=document.getElementById('wa-qr-link');
  t.textContent='Verificando...';d.style.background='#f59e0b';
  fetch('ajax/wa_status.php?force=1').then(r=>r.json()).then(r=>{
    if(r.status==='conectado'){d.style.background='#10b981';t.textContent='✓ WhatsApp conectado!';s.textContent='Instância: '+r.instancia;q.style.display='none'}
    else if(r.status==='nao_configurado'){d.style.background='var(--muted)';t.textContent='Não configurado';s.textContent=r.msg;q.style.display='none'}
    else{d.style.background='#ef4444';t.textContent='⚠ Desconectado';s.textContent=r.msg||'';if(r.qrcode){q.href=r.qrcode;q.style.display=''}}
  }).catch(e=>{d.style.background='#ef4444';t.textContent='✕ Erro na API';s.textContent=String(e)});
}

// Inicializa preview da tabela
document.addEventListener('DOMContentLoaded',()=>{atualizarTabela()});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
