<?php
/* views/pages/webhook.php */
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/helpers.php';
require_once __DIR__ . '/../../app/license_guard.php';
license_guard_or_die();

if (empty($_SESSION['user']['id']) || empty($_SESSION['user']['email'])) {
  header('Location: ' . BASE_URL . 'login.php');
  exit;
}

$pdo = db();

function getOrCreateUserBySession(PDO $pdo): array {
  $sid   = $_SESSION['user']['id'];
  $email = $_SESSION['user']['email'];
  $name  = $_SESSION['user']['name'] ?? null;

  $q = $pdo->prepare("SELECT id,email,name,webhook_token,webhook_enabled,meta FROM users WHERE id=? LIMIT 1");
  $q->execute([$sid]);
  $u = $q->fetch(PDO::FETCH_ASSOC);
  if ($u) return $u;

  $q = $pdo->prepare("SELECT id,email,name,webhook_token,webhook_enabled,meta FROM users WHERE email=? LIMIT 1");
  $q->execute([$email]);
  $u = $q->fetch(PDO::FETCH_ASSOC);
  if ($u) {
    $_SESSION['user']['id'] = $u['id'];
    return $u;
  }

  $ins = $pdo->prepare("
    INSERT INTO users (id,email,name,meta,created_at,updated_at)
    VALUES (gen_random_uuid(), ?, ?, '{}'::jsonb, now(), now())
    RETURNING id,email,name,webhook_token,webhook_enabled,meta
  ");
  $ins->execute([$email, $name]);
  $u = $ins->fetch(PDO::FETCH_ASSOC);
  $_SESSION['user']['id'] = $u['id'];
  return $u;
}

$u = getOrCreateUserBySession($pdo);

if (empty($u['webhook_token'])) {
  try { $newToken = bin2hex(random_bytes(16)); }
  catch (Throwable $e) { $newToken = bin2hex(openssl_random_pseudo_bytes(16)); }

  $pdo->prepare("UPDATE users SET webhook_token=?, webhook_enabled=COALESCE(webhook_enabled, TRUE) WHERE id=?")
      ->execute([$newToken, $u['id']]);

  $q = $pdo->prepare("SELECT id,email,name,webhook_token,webhook_enabled,meta FROM users WHERE id=?");
  $q->execute([$u['id']]);
  $u = $q->fetch(PDO::FETCH_ASSOC);
}

$token     = (string)($u['webhook_token'] ?? '');
$myWebhook = $token ? user_webhook_url($token) : (rtrim(base_url(), '/') . '/webhook/');

$csrf = $_SESSION['csrf'] ?? '';
$API  = rtrim(BASE_URL, '/') . '/api/webhook_settings.php';
?>

<div class="p-6">
  <h1 class="text-2xl font-semibold mb-4">Webhook</h1>

  <!-- Bloco único: Endpoint pessoal -->
  <div class="bg-white border rounded-xl p-5">
    <h2 class="text-lg font-semibold mb-2">Seu endpoint pessoal</h2>
    <p class="text-sm text-gray-600 mb-3">Use este link no seu Extrator.</p>

    <div class="flex items-center gap-2 mb-2">
      <input id="wb-url" class="w-full border rounded px-3 py-2 text-sm" readonly value="<?= htmlspecialchars($myWebhook) ?>">
      <button onclick="navigator.clipboard.writeText(document.getElementById('wb-url').value)"
              class="px-3 py-2 text-sm rounded bg-gray-900 text-white">Copiar</button>
    </div>

    <div class="flex items-center gap-3 mt-3">
      <span class="text-xs px-2 py-1 rounded <?= $u['webhook_enabled'] ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700' ?>">
        <?= $u['webhook_enabled'] ? 'Ativo' : 'Desativado' ?>
      </span>
      <button id="btn-toggle" class="text-sm px-3 py-2 rounded border">
        <?= $u['webhook_enabled'] ? 'Desativar' : 'Ativar' ?>
      </button>
      <button id="btn-rotate" class="text-sm px-3 py-2 rounded border">Rotacionar token</button>
    </div>

    <p class="text-xs text-gray-500 mt-3">
      Qualquer payload enviado para este endpoint será salvo e processado pelo sistema.
    </p>
  </div>
</div>

<script>
const CSRF = <?= json_encode($csrf) ?>;
const API  = <?= json_encode($API) ?>;

async function jfetch(url, opts = {}) {
  const r = await fetch(url, {
    credentials: 'same-origin',
    headers: { 'X-CSRF': CSRF, ...(opts.headers || {}) },
    ...opts
  });
  const ct = r.headers.get('content-type') || '';
  if (!ct.includes('application/json')) {
    const txt = await r.text().catch(()=> '');
    throw new Error('Resposta não JSON: ' + r.status + ' ' + txt);
  }
  return r.json();
}

// Alternar habilitado
document.getElementById('btn-toggle').onclick = async () => {
  try {
    const j = await jfetch(`${API}?action=toggle`, { method:'POST' });
    if (j.ok) location.reload(); else alert(j.error || 'Erro ao alternar');
  } catch (e) { alert('Erro ao alternar: ' + e.message); }
};

// Rotacionar token
document.getElementById('btn-rotate').onclick = async () => {
  if (!confirm('Gerar novo token? Isso invalida a URL anterior.')) return;
  try {
    const j = await jfetch(`${API}?action=rotate`, { method:'POST' });
    if (j.ok) location.reload(); else alert(j.error || 'Erro ao rotacionar');
  } catch (e) { alert('Erro ao rotacionar: ' + e.message); }
};
</script>

