<?php
// views/pages/gmaps.php
// v2: adicionado botão "Copiar link do extrator" baseado em admin_extrators

// Boot & middlewares
require_once __DIR__ . '/../../app/config.php';
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/auth_middleware.php';
require_once __DIR__ . '/components/tutorial.php';

require_auth_or_redirect();

// Dados do usuário logado
$userId    = isset($_SESSION['user']['id'])    ? $_SESSION['user']['id'] : null;
$userEmail = isset($_SESSION['user']['email']) ? trim((string)$_SESSION['user']['email']) : null;

// Busca licença Google Maps na tabela public.auth_users
$licencaGoogleMaps = '';
try {
  $pdo = db();

  // 1) Tenta por ID (funciona para int ou uuid)
  if (!empty($userId)) {
    $q = $pdo->prepare("SELECT licenca_google_maps FROM public.auth_users WHERE id::text = :id::text LIMIT 1");
    $q->execute([':id' => (string)$userId]);
    $row = $q->fetch(PDO::FETCH_ASSOC);
  }

  // 2) Fallback por e-mail (se nada encontrado)
  if (empty($row) && !empty($userEmail)) {
    $q = $pdo->prepare("SELECT licenca_google_maps FROM public.auth_users WHERE email = :email LIMIT 1");
    $q->execute([':email' => $userEmail]);
    $row = $q->fetch(PDO::FETCH_ASSOC);
  }

  if (!empty($row['licenca_google_maps'])) {
    $licencaGoogleMaps = (string)$row['licenca_google_maps'];
  }
} catch (Throwable $e) {
  // Opcional: log
}

// Busca link do extrator (cadastrado pelo admin)
$linkExtrator = '';
try {
  $r = db()->query("SELECT link_google_maps FROM admin_extrators WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
  if (!empty($r['link_google_maps'])) {
    $linkExtrator = (string)$r['link_google_maps'];
  }
} catch (Throwable $e) {
  // tabela ainda não criada ou erro — botão não aparece
}

$safeLicense = htmlspecialchars($licencaGoogleMaps, ENT_QUOTES, 'UTF-8');
$safeLink    = htmlspecialchars($linkExtrator,     ENT_QUOTES, 'UTF-8');

// (Opcional) vídeo do tutorial desta página
$tutorialVideo = 'https://youtu.be/EdojaenB0uk';
?>

<!-- Componente Tutorial no topo -->
<div class="mb-4 sm:mb-6">
<?= tutorial_component([
  'id'        => 'extensoes',
  'title'     => 'Extensões',
  'button'    => 'Ver tutorial',
  'video'     => $tutorialVideo,
  'spotlight' => true
]); ?>
</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">
    <div>
      <h2 class="text-xl font-semibold">Extrator Google Maps</h2>
      <p class="text-sm text-gray-500 dark:text-gray-400">Clique no botão abaixo pra copiar o link e instalar a extensão.</p>
    </div>
  </div>

  <!-- Botão Copiar Link do Extrator -->
  <div class="mt-6">
    <?php if ($linkExtrator !== ''): ?>
      <div class="flex justify-center">
        <button id="btnCopyExtractor"
                type="button"
                data-link="<?= $safeLink ?>"
                class="inline-flex items-center gap-2 justify-center rounded-xl px-5 py-3 text-sm font-medium
                       bg-emerald-600 hover:bg-emerald-700 text-white transition-all">
          <span id="btnCopyExtractorIcon">📋</span>
          <span id="btnCopyExtractorText">Copiar link do extrator Google Maps</span>
        </button>
      </div>
      <p id="copyExtractorMsg" class="text-xs text-gray-500 mt-2 text-center"></p>
    <?php else: ?>
      <div class="flex justify-center">
        <div class="rounded-lg border border-amber-300 bg-amber-50 text-amber-900 px-4 py-2 text-sm">
          ⚠️ O link de instalação ainda não foi configurado. Avise o administrador.
        </div>
      </div>
    <?php endif; ?>
  </div>


  <!-- Bloco da licença -->
  <div class="mt-6 rounded-xl border border-gray-200 dark:border-gray-800 p-4 bg-gray-50 dark:bg-gray-950">
    <h3 class="font-medium mb-2">Sua chave de licença</h3>

    <div class="grid gap-2">
      <label class="text-xs text-gray-500 dark:text-gray-400">Google Maps</label>

      <?php if ($safeLicense !== ''): ?>
        <div class="flex flex-col sm:flex-row gap-2 items-stretch sm:items-center">
          <div class="relative flex-1">
            <input id="licenseInput"
                   type="text"
                   value="<?= $safeLicense; ?>"
                   readonly
                   class="w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-950 px-3 py-2 pr-24 text-sm select-all">
            <button id="btnToggleMask"
                    type="button"
                    class="absolute right-2 top-1/2 -translate-y-1/2 text-xs rounded-md border border-gray-300 dark:border-gray-700 px-2 py-1 bg-white dark:bg-gray-900">
              Ocultar
            </button>
          </div>

          <button id="btnCopy"
                  type="button"
                  class="rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 text-sm">
            Copiar chave
          </button>
        </div>
        <p id="copyMsg" class="text-xs text-gray-500 mt-1"></p>
      <?php else: ?>
        <div class="rounded-lg border border-amber-300 bg-amber-50 text-amber-900 px-3 py-2 text-sm">
          Nenhuma chave cadastrada para Google Maps.
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
// ─── Copiar Link do Extrator ───
const btnExt = document.getElementById('btnCopyExtractor');
const msgExt = document.getElementById('copyExtractorMsg');
const txtExt = document.getElementById('btnCopyExtractorText');
const iconExt = document.getElementById('btnCopyExtractorIcon');

if (btnExt) {
  btnExt.addEventListener('click', async () => {
    const link = btnExt.dataset.link;
    if (!link) return;
    try {
      await navigator.clipboard.writeText(link);
      if (txtExt)  txtExt.textContent  = 'Link copiado!';
      if (iconExt) iconExt.textContent = '✅';
      btnExt.classList.remove('bg-emerald-600', 'hover:bg-emerald-700');
      btnExt.classList.add('bg-emerald-800');
      if (msgExt) msgExt.textContent = link;
      setTimeout(() => {
        if (txtExt)  txtExt.textContent  = 'Copiar link do extrator Google Maps';
        if (iconExt) iconExt.textContent = '📋';
        btnExt.classList.remove('bg-emerald-800');
        btnExt.classList.add('bg-emerald-600', 'hover:bg-emerald-700');
        if (msgExt) msgExt.textContent = '';
      }, 2500);
    } catch (e) {
      if (msgExt) msgExt.textContent = 'Não conseguiu copiar automaticamente. Link: ' + link;
    }
  });
}

// ─── Copiar/Ocultar Chave de Licença (existente) ───
const btnCopy = document.getElementById('btnCopy');
const copyMsg = document.getElementById('copyMsg');
const input   = document.getElementById('licenseInput');
const btnMask = document.getElementById('btnToggleMask');

if (btnCopy && input) {
  btnCopy.addEventListener('click', async () => {
    try {
      input.select();
      input.setSelectionRange(0, input.value.length);
      await navigator.clipboard.writeText(input.value);
      copyMsg && (copyMsg.textContent = 'Chave copiada!');
      setTimeout(() => copyMsg && (copyMsg.textContent = ''), 1500);
    } catch(e) {
      copyMsg && (copyMsg.textContent = 'Não foi possível copiar automaticamente. Selecione e copie manualmente.');
      setTimeout(() => copyMsg && (copyMsg.textContent = ''), 2500);
    }
  });
}

// Ocultar/mostrar
if (btnMask && input) {
  let masked = false;
  const original = input.value;

  function mask(str) {
    if (!str) return '';
    if (str.length <= 8) return '*'.repeat(Math.max(0, str.length - 2));
    const start = str.slice(0, 4);
    const end   = str.slice(-4);
    return `${start}${'*'.repeat(Math.max(0, str.length - 8))}${end}`;
  }

  btnMask.addEventListener('click', () => {
    masked = !masked;
    if (masked) {
      input.value = mask(original);
      btnMask.textContent = 'Mostrar';
    } else {
      input.value = original;
      btnMask.textContent = 'Ocultar';
    }
  });
}
</script>
