<?php
/**
 * Proxy de Webhook - Evolua Painel
 * Recebe eventos via POST e encaminha para o webhook real (n8n)
 * Envia identificador do painel/usuário via headers:
 *  - X-Evolua-Tenant (token)
 *  - X-Evolua-Webhook (url completa usada)
 */

require_once __DIR__ . '/app/config.php';

// ===========================
// CORS (aberto - webhook)
// ===========================
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');

$reqHeaders = $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ?? '';
header('Access-Control-Allow-Headers: ' . ($reqHeaders ?: 'Content-Type, Authorization, X-Requested-With'));

header('Access-Control-Max-Age: 86400');

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['ok' => false, 'error' => 'Método não permitido. Use POST.'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
  exit;
}

$raw = file_get_contents('php://input');
if (!$raw) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Payload vazio'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
  exit;
}

if (!defined('EV_WABA_AGENT_WEBHOOK_URL') || !EV_WABA_AGENT_WEBHOOK_URL) {
  http_response_code(500);
  echo json_encode(['ok' => false, 'error' => 'EV_WABA_AGENT_WEBHOOK_URL não configurada'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
  exit;
}

// =====================================================
// Identificador do usuário/painel vindo na URL
// Ex: https://.../apioficial.php?w=TOKEN
// =====================================================
$tenant = trim((string)($_GET['w'] ?? ''));
if ($tenant === '') $tenant = 'unknown';

// URL completa que foi chamada (pra auditoria)
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$proxyUrlFull = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . ($_SERVER['REQUEST_URI'] ?? '');

// Encaminha pro destino real
$ch = curl_init(EV_WABA_AGENT_WEBHOOK_URL);

curl_setopt_array($ch, [
  CURLOPT_POST           => true,
  CURLOPT_POSTFIELDS     => $raw,
  CURLOPT_HTTPHEADER     => [
    'Content-Type: application/json',
    'X-Evolua-Source: apioficial-proxy',
    'X-Evolua-Timestamp: ' . time(),
    'X-Evolua-Tenant: ' . $tenant,
    'X-Evolua-Webhook: ' . $proxyUrlFull,
    'User-Agent: Evolua-Webhook-Proxy/1.0',
  ],
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT        => 30,
]);

$response = curl_exec($ch);
$errno    = curl_errno($ch);
$error    = curl_error($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($errno) {
  http_response_code(502);
  echo json_encode([
    'ok' => false,
    'error' => 'Falha ao redirecionar webhook',
    'detail' => $error
  ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
  exit;
}

http_response_code(200);
echo json_encode([
  'ok' => true,
  'proxied' => true,
  'tenant' => $tenant,
  'target_status' => $httpCode,
  'timestamp' => time()
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
