<?php
// views/pages/apioficial.php
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/components/tutorial.php';
require_once __DIR__ . '/../../app/license_guard.php';
license_guard_or_die();

$pdo = db();

$userPlan = 'basic';
if (!empty($_SESSION['user']['id'])) {
  try {
    $st = $pdo->prepare('SELECT plan FROM auth_users WHERE id = :id LIMIT 1');
    $st->execute([':id' => $_SESSION['user']['id']]);
    $plan = $st->fetchColumn();
    if (in_array($plan, ['basic','profissional','premium'], true)) $userPlan = $plan;
  } catch (Throwable $e) {}
}
?>

<div class="mb-4 sm:mb-6">
<?= tutorial_component([
  'id'     => 'api_oficial',
  'title'  => 'Como conectar a API Oficial do WhatsApp',
  'button' => 'Ver tutorial da API Oficial',
  'video'  => 'https://www.youtube-nocookie.com/embed/WIsouGJUMb8',
  'spotlight' => true,
  'cta' => [
      'label' => '🚀 Adquirir Método de Implementação',
      'url'   => 'https://pay.kiwify.com.br/9rKQYlJ'
  ]
]); ?>

</div>

<div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6">
  <div class="flex items-center justify-between mb-4">
    <div>
      <h2 class="text-xl font-semibold">API Oficial do WhatsApp</h2>
      <p class="text-xs text-gray-500 mt-1">Cadastre os dados da sua conexão com o Evolua Chat.</p>
    </div>
  </div>

  <!-- BLOCO: SEM CONEXÃO -->
  <div id="createBlock">
    <button id="btnOpenCreate" class="rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2">
      Criar conexão
    </button>
    <p class="text-xs text-gray-500 mt-2">
      Você irá informar: <b>Nome da conexão</b>, <b>WABA ID</b>, <b>Phone Number ID</b>, <b>Token de envio</b>, <b>Token do Evolua Chat</b>, <b>Usuário/Senha do Evolua Chat</b> e <b>Número</b>.
    </p>
  </div>

  <!-- BLOCO: COM CONEXÃO -->
  <div id="cardBlock" class="hidden mt-4">
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 p-4 bg-gray-50 dark:bg-gray-950">
      <div class="flex items-start justify-between gap-3">
        <div>
          <div class="text-sm text-gray-500">Conexão</div>
          <div class="text-lg font-semibold" id="cardName">—</div>

          <div class="mt-2 grid grid-cols-1 md:grid-cols-2 gap-2 text-sm text-gray-700 dark:text-gray-300">

            <div class="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 p-3">
              <div class="text-xs text-gray-500">Token Evolua Chat</div>
              <div class="font-medium" id="cardEvoluaToken">—</div>
            </div>

            <div class="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 p-3">
              <div class="text-xs text-gray-500">Usuário Evolua Chat</div>
              <div class="font-medium" id="cardEvoluaUser">—</div>
            </div>

            <div class="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 p-3 md:col-span-2">
              <div class="text-xs text-gray-500">Senha Evolua Chat</div>
              <div class="font-medium" id="cardEvoluaPass">—</div>
            </div>

          </div>

          <!-- ====== WABA switches ====== -->
          <div class="mt-4 space-y-4">
            <!-- Agente ligado? -->
            <div>
              <div class="flex items-center justify-between">
                <div>
                  <div class="text-sm font-medium text-gray-900 dark:text-gray-100">Agente de atendimento ligado?</div>
                  <div id="lblAgenteWaba" class="mt-1 inline-flex items-center rounded bg-emerald-50 px-2 py-1 text-xs text-emerald-700 border border-emerald-200">
                    Agente ligado
                  </div>
                  <div class="text-xs text-gray-500 mt-1">
                    Desative esta opção caso queira realizar apenas disparos, sem a interação do agente de IA
                  </div>
                </div>

                <label class="inline-flex items-center cursor-pointer select-none">
                  <input id="swAgenteWaba" type="checkbox" class="sr-only">
                  <span class="relative inline-block w-12 h-6 bg-gray-200 rounded-full transition">
                    <span id="knobAgenteWaba" class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition"></span>
                  </span>
                </label>
              </div>
            </div>

            <!-- Responder todos? -->
            <div>
              <div class="flex items-center justify-between">
                <div>
                  <div class="text-sm font-medium text-gray-900 dark:text-gray-100">Responder Todos?</div>
                  <div id="lblRespWaba" class="mt-1 inline-flex items-center rounded bg-amber-50 px-2 py-1 text-xs text-amber-700 border border-amber-200">
                    Responder Todos: desligado
                  </div>
                  <div class="text-xs text-gray-500 mt-1">
                    Se ligado responderá leads de todas origens; se desligado, apenas prospecção.
                  </div>
                </div>

                <label class="inline-flex items-center cursor-pointer select-none">
                  <input id="swRespWaba" type="checkbox" class="sr-only">
                  <span class="relative inline-block w-12 h-6 bg-gray-200 rounded-full transition">
                    <span id="knobRespWaba" class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition"></span>
                  </span>
                </label>
              </div>
            </div>

            <!-- Webhook -->
            <div class="mt-6 w-full rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
              <div class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                Webhook de Integração no Evolua Chat
              </div>

              <p class="text-xs text-gray-500 mt-1">
                Cole esta URL na criação da integração no Evolua Chat.
              </p>

              <div class="mt-3 flex w-full gap-2 items-center">
                <input
                  id="wabaWebhookUrl"
                  type="text"
                  readonly
                  dir="rtl"
                  class="min-w-0 flex-1 w-full rounded-lg border border-gray-300 dark:border-gray-700
                         px-3 py-2 font-mono text-xs
                         bg-gray-50 dark:bg-gray-950
                         text-gray-900 dark:text-gray-100"
                  style="text-align:left"
                  value=""
                  onclick="this.focus(); this.select();"
                />

                <button
                  id="btnCopyWebhook"
                  type="button"
                  class="shrink-0 rounded-lg bg-indigo-600 hover:bg-indigo-700
                         text-white text-xs font-semibold px-4 py-2"
                  style="min-width:92px"
                >
                  Copiar
                </button>
              </div>

              <div id="webhookCopyMsg" class="mt-2 text-xs text-emerald-700 hidden">
                ✓ Webhook copiado com sucesso
              </div>
            </div>

            <div id="wabaSaveMsg" class="text-xs text-gray-500"></div>
          </div>

          <div class="mt-3 text-xs text-gray-500">
            <span id="cardUpdated">—</span>
          </div>
        </div>

        <div class="flex flex-col gap-2 shrink-0">
          <button id="btnEdit" class="rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 text-sm">
            Editar
          </button>
          <button id="btnDelete" class="rounded-lg bg-rose-600 hover:bg-rose-700 text-white px-4 py-2 text-sm">
            Excluir
          </button>
          <span id="statusMsg" class="text-xs text-gray-600 dark:text-gray-400"></span>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- MODAL (Criar / Editar) -->
<div id="connModal" class="fixed inset-0 z-50 hidden">
  <div class="absolute inset-0 bg-black/50 backdrop-blur-sm"></div>
  <div class="absolute inset-0 flex items-center justify-center p-4">
    <div class="w-full max-w-xl rounded-2xl bg-white shadow-xl ring-1 ring-black/5">
      <div class="px-5 py-4 border-b flex items-center justify-between">
        <h3 class="text-lg font-semibold" id="modalTitle">Criar conexão</h3>
        <button id="modalClose" class="text-gray-600 hover:text-black" aria-label="Fechar">&times;</button>
      </div>

      <div class="p-5 grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="md:col-span-2">
          <label class="block text-sm mb-1">Nome da conexão</label>
          <input id="fName" type="text" class="w-full rounded border px-3 py-2" placeholder="Ex: Meu WhatsApp Oficial">
        </div>

        <div class="md:col-span-2">
          <label class="block text-sm mb-1">Token do Evolua Chat</label>
          <textarea id="fEvoluaToken" rows="3" class="w-full rounded border px-3 py-2 font-mono text-xs"
            placeholder="Cole aqui o token do Evolua Chat..."></textarea>
          <p class="text-xs text-gray-500 mt-1">Usado para integrar e validar operações com o Evolua Chat.</p>
        </div>

        <div>
          <label class="block text-sm mb-1">Usuário Evolua Chat</label>
          <div class="flex gap-2">
            <input id="fEvoluaUser" type="text" class="w-full rounded border px-3 py-2" placeholder="Ex: meuemail@dominio.com">
          </div>
        </div>

        <div>
          <label class="block text-sm mb-1">Senha Evolua Chat</label>
          <div class="flex gap-2">
            <input id="fEvoluaPass" type="password" class="w-full rounded border px-3 py-2" placeholder="Digite sua senha">
          </div>
        </div>

        <div class="md:col-span-2">
          <div class="flex items-center gap-2">
            <button
              id="btnValidateEvolua"
              type="button"
              class="rounded px-4 py-2 text-sm font-semibold"
              style="background:#111827;color:#fff;"
              onmouseover="this.style.background='#0b1220'"
              onmouseout="this.style.background='#111827'"
            >
              Validar conexão
            </button>

            <span id="evoluaCheck" class="hidden inline-flex items-center gap-2 text-sm font-medium text-emerald-700">
              <span class="inline-flex size-5 items-center justify-center rounded-full bg-emerald-100">✓</span>
              Conexão validada
            </span>

            <span id="evoluaCheckErr" class="hidden text-sm font-medium text-rose-700">
              usuário ou senha incorretos
            </span>
          </div>

          <p class="text-xs text-gray-500 mt-2">
            Você só consegue <b>Salvar</b> depois de validar o usuário/senha do Evolua Chat.
          </p>
        </div>

        <div class="md:col-span-2">
          <div id="modalMsg" class="text-sm"></div>
        </div>
      </div>

      <div class="px-5 py-4 border-t flex items-center justify-end gap-2">
        <button id="modalCancel" class="px-3 py-2 rounded border">Cancelar</button>
        <button id="modalSave" class="px-4 py-2 rounded bg-indigo-600 text-white">Salvar</button>
      </div>
    </div>
  </div>
</div>

<script>
  const API = 'api/apioficial.php';

  const createBlock = document.getElementById('createBlock');
  const cardBlock   = document.getElementById('cardBlock');

  const cardName   = document.getElementById('cardName');
  const cardEvoluaToken = document.getElementById('cardEvoluaToken');
  const cardEvoluaUser  = document.getElementById('cardEvoluaUser');
  const cardEvoluaPass  = document.getElementById('cardEvoluaPass');
  const statusMsg  = document.getElementById('statusMsg');

  // modal
  const connModal  = document.getElementById('connModal');
  const modalTitle = document.getElementById('modalTitle');
  const modalClose = document.getElementById('modalClose');
  const modalCancel= document.getElementById('modalCancel');
  const modalSave  = document.getElementById('modalSave');
  const modalMsg   = document.getElementById('modalMsg');

  const fName = document.getElementById('fName');
  const fEvoluaToken = document.getElementById('fEvoluaToken');
  const fEvoluaUser  = document.getElementById('fEvoluaUser');
  const fEvoluaPass  = document.getElementById('fEvoluaPass');

  const btnValidateEvolua = document.getElementById('btnValidateEvolua');
  const evoluaCheck = document.getElementById('evoluaCheck');
  const evoluaCheckErr = document.getElementById('evoluaCheckErr');

  const btnOpenCreate = document.getElementById('btnOpenCreate');
  const btnEdit   = document.getElementById('btnEdit');
  const btnDelete = document.getElementById('btnDelete');

  const swAgenteWaba = document.getElementById('swAgenteWaba');
  const swRespWaba   = document.getElementById('swRespWaba');
  const knobAgenteWaba = document.getElementById('knobAgenteWaba');
  const knobRespWaba   = document.getElementById('knobRespWaba');
  const lblAgenteWaba  = document.getElementById('lblAgenteWaba');
  const lblRespWaba    = document.getElementById('lblRespWaba');
  const wabaSaveMsg    = document.getElementById('wabaSaveMsg');

  const webhookInput = document.getElementById('wabaWebhookUrl');
  const btnCopyWebhook = document.getElementById('btnCopyWebhook');
  const webhookMsg = document.getElementById('webhookCopyMsg');

  let evoluaValidated = false;
  let _wabaSaving = false;

  function resetEvoluaValidationUI(){
    evoluaValidated = false;
    evoluaCheck.classList.add('hidden');
    evoluaCheckErr.classList.add('hidden');
  }

  function setMsg(el, type, text) {
    el.textContent = text || '';
    el.className = 'text-sm';
    if (!text) return;
    if (type === 'ok')   el.classList.add('text-emerald-700');
    if (type === 'warn') el.classList.add('text-amber-700');
    if (type === 'err')  el.classList.add('text-rose-700');
    if (type === 'info') el.classList.add('text-gray-600');
  }

  async function fetchJSON(url, opts = {}) {
    const r = await fetch(url, { credentials:'same-origin', cache:'no-store', ...opts });
    const t = await r.text();
    let d = null;
    try { d = JSON.parse(t) } catch {}
    if (!r.ok || !d) return { ok:false, status:r.status||0, error:d?.error||t||'Falha' };
    return d;
  }

  function openModal(mode = 'create') {
    modalTitle.textContent = (mode === 'edit') ? 'Editar conexão' : 'Criar conexão';
    setMsg(modalMsg, 'info', '');
    connModal.classList.remove('hidden');
    setTimeout(()=>fName?.focus(), 50);
  }
  function closeModal() {
    connModal.classList.add('hidden');
    setMsg(modalMsg, 'info', '');
  }

  modalClose?.addEventListener('click', closeModal);
  modalCancel?.addEventListener('click', closeModal);
  connModal?.addEventListener('click', (e) => {
    if (e.target === connModal) closeModal();
  });
  document.addEventListener('keydown', (e) => {
    if (!connModal.classList.contains('hidden') && e.key === 'Escape') closeModal();
  });

  fEvoluaUser.addEventListener('input', resetEvoluaValidationUI);
  fEvoluaPass.addEventListener('input', resetEvoluaValidationUI);

  function fillForm(data) {
    fName.value = data?.name || '';
    fEvoluaToken.value = '';
    fEvoluaUser.value = '';
    fEvoluaPass.value = '';
    resetEvoluaValidationUI();
  }

  function renderCard(data) {
    cardName.textContent = data?.name || '—';
    cardEvoluaToken.textContent = data?.evolua_token_masked || '—';
    cardEvoluaUser.textContent  = data?.evolua_user_masked || '—';
cardEvoluaPass.textContent = data?.evolua_pass_masked ? '••••••••••••' : '—';
    const ag = !!data?.agente_ligado_waba;
    const rt = !!data?.responder_todos_waba;

    swAgenteWaba.checked = ag;
    swRespWaba.checked   = rt;

    paintSwitch(swAgenteWaba, knobAgenteWaba);
    paintSwitch(swRespWaba, knobRespWaba);
    renderWabaLabels();

    if (data?.webhook_waba_evo_chat) webhookInput.value = data.webhook_waba_evo_chat;
  }

  function paintSwitch(inputEl, knobEl){
    const track = knobEl.parentElement;
    if (inputEl.checked){
      track.classList.remove('bg-gray-200');
      track.classList.add('bg-emerald-500');
      knobEl.style.transform = 'translateX(24px)';
    } else {
      track.classList.add('bg-gray-200');
      track.classList.remove('bg-emerald-500');
      knobEl.style.transform = 'translateX(0px)';
    }
  }

  function setWabaMsg(type, text){
    wabaSaveMsg.textContent = text || '';
    wabaSaveMsg.className = 'text-xs';
    if (!text) { wabaSaveMsg.classList.add('text-gray-500'); return; }
    if (type === 'ok') wabaSaveMsg.classList.add('text-emerald-700');
    if (type === 'err') wabaSaveMsg.classList.add('text-rose-700');
    if (type === 'info') wabaSaveMsg.classList.add('text-gray-500');
  }

  function renderWabaLabels(){
    if (swAgenteWaba.checked){
      lblAgenteWaba.textContent = 'Agente ligado';
      lblAgenteWaba.className = 'mt-1 inline-flex items-center rounded bg-emerald-50 px-2 py-1 text-xs text-emerald-700 border border-emerald-200';
    } else {
      lblAgenteWaba.textContent = 'Agente desligado';
      lblAgenteWaba.className = 'mt-1 inline-flex items-center rounded bg-rose-50 px-2 py-1 text-xs text-rose-700 border border-rose-200';
    }

    if (swRespWaba.checked){
      lblRespWaba.textContent = 'Responder Todos: ligado';
      lblRespWaba.className = 'mt-1 inline-flex items-center rounded bg-emerald-50 px-2 py-1 text-xs text-emerald-700 border border-emerald-200';
    } else {
      lblRespWaba.textContent = 'Responder Todos: desligado';
      lblRespWaba.className = 'mt-1 inline-flex items-center rounded bg-amber-50 px-2 py-1 text-xs text-amber-700 border border-amber-200';
    }
  }

  async function saveWabaSettings(){
    if (_wabaSaving) return;
    _wabaSaving = true;

    swAgenteWaba.disabled = true;
    swRespWaba.disabled = true;
    setWabaMsg('info', 'Salvando...');

    const payload = {
      agente_ligado_waba: swAgenteWaba.checked,
      responder_todos_waba: swRespWaba.checked
    };

    const r = await fetchJSON(`${API}?action=waba_settings.save`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    swAgenteWaba.disabled = false;
    swRespWaba.disabled = false;
    _wabaSaving = false;

    if (!r.ok){
      setWabaMsg('err', r.error || 'Falha ao salvar');
      return;
    }

    setWabaMsg('ok', '✓ Configuração salva!');
    setTimeout(() => setWabaMsg('info',''), 1500);
  }

  swAgenteWaba.addEventListener('change', async () => {
    paintSwitch(swAgenteWaba, knobAgenteWaba);
    renderWabaLabels();
    await saveWabaSettings();
  });

  swRespWaba.addEventListener('change', async () => {
    paintSwitch(swRespWaba, knobRespWaba);
    renderWabaLabels();
    await saveWabaSettings();
  });

  btnValidateEvolua?.addEventListener('click', async () => {
    resetEvoluaValidationUI();

    const email = (fEvoluaUser.value || '').trim();
    const password = (fEvoluaPass.value || '').trim();

    if (!email) { evoluaCheckErr.classList.remove('hidden'); evoluaCheckErr.textContent = 'Informe o usuário (email)'; return; }
    if (!password) { evoluaCheckErr.classList.remove('hidden'); evoluaCheckErr.textContent = 'Informe a senha'; return; }

    btnValidateEvolua.disabled = true;
    btnValidateEvolua.textContent = 'Validando...';
    evoluaCheckErr.classList.add('hidden');

    const r = await fetchJSON(`${API}?action=validate_evolua`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    });

    btnValidateEvolua.disabled = false;
    btnValidateEvolua.textContent = 'Validar conexão';

    if (r.ok) {
      evoluaValidated = true;
      evoluaCheck.classList.remove('hidden');
      evoluaCheckErr.classList.add('hidden');
      return;
    }

    evoluaValidated = false;
    evoluaCheck.classList.add('hidden');
    evoluaCheckErr.classList.remove('hidden');
    evoluaCheckErr.textContent = 'usuário ou senha incorretos';
  });

  async function boot() {
    const me = await fetchJSON(`${API}?action=me`);
    if (!me.ok) {
      createBlock.classList.remove('hidden');
      cardBlock.classList.add('hidden');
      setMsg(statusMsg, 'err', me.error || 'Falha ao carregar');
      return;
    }

    const connected = !!me.connected;
    if (!connected) {
      createBlock.classList.remove('hidden');
      cardBlock.classList.add('hidden');
      fillForm(null);
      return;
    }

    createBlock.classList.add('hidden');
    cardBlock.classList.remove('hidden');
    renderCard(me.data);
    fillForm(me.data);
  }

  btnOpenCreate?.addEventListener('click', () => {
    fillForm(null);
    openModal('create');
  });

  btnEdit?.addEventListener('click', async () => {
    const me = await fetchJSON(`${API}?action=me`);
    if (!me.ok) { setMsg(statusMsg,'err', me.error||'Falha'); return; }
    fillForm(me.data);
    openModal('edit');
    setMsg(modalMsg,'info','⚠️ No editar, cole os tokens novamente se quiser trocar.');
  });

  modalSave?.addEventListener('click', async () => {
    const payload = {
      name: (fName.value || '').trim(),
      evolua_chat_token: (fEvoluaToken.value || '').trim(),
      user_evolua_chat: (fEvoluaUser.value || '').trim(),
      pass_evolua_chat: (fEvoluaPass.value || '').trim(),
    };

    if (!payload.name) return setMsg(modalMsg,'err','Informe o nome da conexão.');
    if (!payload.evolua_chat_token) return setMsg(modalMsg,'err','Cole o Token do Evolua Chat.');
    if (!payload.user_evolua_chat) return setMsg(modalMsg,'err','Informe o Usuário do Evolua Chat.');
    if (!payload.pass_evolua_chat) return setMsg(modalMsg,'err','Informe a Senha do Evolua Chat.');

    if (!evoluaValidated) return setMsg(modalMsg,'err','Valide a conexão do Evolua Chat antes de salvar.');

    modalSave.disabled = true;
    modalSave.textContent = 'Salvando...';
    setMsg(modalMsg,'info','');

    const r = await fetchJSON(`${API}?action=save`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    modalSave.disabled = false;
    modalSave.textContent = 'Salvar';

    if (!r.ok) return setMsg(modalMsg,'err', r.error || 'Falha ao salvar');

    setMsg(modalMsg,'ok','✓ Conexão salva com sucesso!');
    await boot();
    setTimeout(closeModal, 450);
  });

  btnDelete?.addEventListener('click', async () => {
    if (!confirm('Excluir a conexão oficial? (isso remove token e IDs do seu usuário)')) return;
    setMsg(statusMsg,'info','Excluindo...');
    const r = await fetchJSON(`${API}?action=delete`, { method: 'POST' });
    if (!r.ok) { setMsg(statusMsg,'err', r.error||'Falha ao excluir'); return; }
    setMsg(statusMsg,'ok','Conexão removida.');
    await boot();
  });

  btnCopyWebhook?.addEventListener('click', async () => {
    const txt = (webhookInput.value || '').trim();
    if (!txt) return;

    try {
      await navigator.clipboard.writeText(txt);
    } catch {
      webhookInput.focus();
      webhookInput.select();
      document.execCommand('copy');
    }

    webhookMsg.classList.remove('hidden');
    setTimeout(() => webhookMsg.classList.add('hidden'), 1500);
  });

  boot();
</script>
