<?php

$VERIFY_TOKEN = 'FiberX2024';
$N8N_WEBHOOK = 'https://fiberx.app.n8n.cloud/webhook/whatsapp-6142528820';
$LOG_FILE = '/var/www/webhook/webhook_log.txt';

// Verificación de Meta
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (
        isset($_GET['hub_mode']) &&
        $_GET['hub_mode'] === 'subscribe' &&
        isset($_GET['hub_verify_token']) &&
        hash_equals($VERIFY_TOKEN, $_GET['hub_verify_token'])
    ) {
        echo $_GET['hub_challenge'];
        exit;
    }

    http_response_code(403);
    exit;
}

// Aceptar solamente solicitudes POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

// Leer el JSON original enviado por Meta
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);

// Conservar el registro actual
file_put_contents(
    $LOG_FILE,
    print_r($input, true) . PHP_EOL,
    FILE_APPEND | LOCK_EX
);

// Reenviar el JSON original hacia n8n
$curl = curl_init($N8N_WEBHOOK);

curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $rawInput,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json'
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 3,
    CURLOPT_TIMEOUT => 8
]);

$n8nResponse = curl_exec($curl);
$n8nError = curl_error($curl);
$n8nStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);

curl_close($curl);

// Registrar solamente errores del reenvío
if ($n8nError !== '' || $n8nStatus < 200 || $n8nStatus >= 300) {
    file_put_contents(
        $LOG_FILE,
        sprintf(
            "[N8N ERROR] HTTP %d | %s | Respuesta: %s\n",
            $n8nStatus,
            $n8nError,
            $n8nResponse
        ),
        FILE_APPEND | LOCK_EX
    );
}

// Confirmar recepción a Meta
http_response_code(200);
header('Content-Type: text/plain');
echo 'OK';
