<?php
// public/api/webhook_ingress.php
require_once __DIR__ . '/../../app/config.php';
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/helpers.php';

header('Content-Type: application/json; charset=utf-8');

// ---- CORS (preflight para extensão/navegador) ----
$origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
header('Access-Control-Allow-Origin: ' . $origin);
header('Vary: Origin');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Max-Age: 86400');

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method === 'OPTIONS') {
  http_response_code(204);
  exit;
}

// ---- helpers ----
function jexit($payload, $status = 200) {
  http_response_code($status);
  echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

// ---- valida token ----
$token = $_GET['token'] ?? '';
if (!$token) jexit(['ok' => false, 'error' => 'Token ausente'], 400);

$pdo = db();

// ---- resolve usuário ----
$stmt = $pdo->prepare("
  SELECT id, email, name, meta, webhook_enabled
  FROM users
  WHERE webhook_token = ?
  LIMIT 1
");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user)                   jexit(['ok' => false, 'error' => 'Webhook inválido'], 404);
if (!$user['webhook_enabled']) jexit(['ok' => false, 'error' => 'Webhook desabilitado'], 403);

// ---- captura request ----
$raw       = file_get_contents('php://input');
$contentTp = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
$body      = null;

if ($raw !== '') {
  // tenta decodificar JSON
  $decoded = json_decode($raw, true);
  if (json_last_error() === JSON_ERROR_NONE) {
    $body = $decoded;
  } else {
    // quando não é JSON, guarda cru e adiciona wrapper simples
    $body = ['_raw' => $raw];
  }
}

// Normalização para o formato da extensão (array com um objeto e este contém "body": [...])
$normalized = $body;
if (is_array($body) && isset($body[0]) && is_array($body[0]) && array_key_exists('body', $body[0]) && is_array($body[0]['body'])) {
  $normalized = [
    'leads'       => $body[0]['body'], // leads principais
    'source_full' => $body,            // payload completo original
    'source'      => 'ext_gmaps'
  ];
}

// ---- extras de log ----
$headersIn = function_exists('getallheaders') ? getallheaders() : [];
$ip        = $_SERVER['REMOTE_ADDR'] ?? null;
$query     = $_GET;
unset($query['token']); // não gravar o token nos params
$statusVal = ($method === 'POST') ? 'new' : 'ping'; // marca pings e GETs

// ---- grava na tabela leads_webhook_brutos ----
/** 3) Grava na tabela leads_webhook_brutos */
try {
  $sql = "
    INSERT INTO leads_webhook_brutos
      (user_id, token, method, ip, headers, query, body_raw, body_json, status)
    VALUES
      (?, ?, ?, ?, ?::jsonb, ?::jsonb, ?, ?::jsonb, 'new')
    RETURNING id
  ";

  $headersJson = $headersIn ? json_encode($headersIn, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) : null;
  $queryJson   = $query     ? json_encode($query,     JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) : null;
  $bodyJsonStr = $body !== null ? json_encode($body, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) : null;

  $stmt = $pdo->prepare($sql);
  $stmt->execute([
    $user['id'],
    $token,
    $method,
    $ip,
    $headersJson,
    $queryJson,
    $raw !== '' ? $raw : null,
    $bodyJsonStr
  ]);

  $id = (int)$stmt->fetchColumn();

  // opcional: atualizar last_seen do usuário
  $pdo->prepare("UPDATE users SET webhook_last_seen = now() WHERE id = ?")->execute([$user['id']]);

  /* ------------------------------------------------------------------
   *  3.1) Dispara o webhook do extrator com TUDO do registro inserido
   * ------------------------------------------------------------------ */
  if (defined('EXTRACTOR_WEBHOOK_URL') && EXTRACTOR_WEBHOOK_URL) {
      // payload enxuto e direto, contendo tudo o que recebemos
      $toSend = [
        'id'          => $id,
        'user'        => ['id' => $user['id'], 'email' => $user['email'], 'name' => $user['name']],
        'token'       => $token,
        'method'      => $method,
        'ip'          => $ip,
        'headers'     => $headersIn,
        'query'       => $query,
        'body'        => $body,            // array decodificado
        'body_raw'    => ($raw !== '' ? $raw : null),
        'received_at' => date('c'),
      ];

      // manda JSON; 20s de timeout
      $relay = http_post_json(EXTRACTOR_WEBHOOK_URL, $toSend, 20);

      if ($relay['ok']) {
        $pdo->prepare("UPDATE leads_webhook_brutos SET status='processed' WHERE id=?")->execute([$id]);
      } else {
        $pdo->prepare("UPDATE leads_webhook_brutos SET status='error', error=? WHERE id=?")
            ->execute([('relay_failed: '.$relay['status'].' '.$relay['error']), $id]);
      }
  }

  jexit(['ok' => true, 'record_id' => $id], 201);

} catch (Throwable $e) {
  jexit(['ok' => false, 'error' => 'Falha ao salvar', 'detail' => $e->getMessage()], 500);
}

