<?php
/**
 * API - Reproducir payload de webhook (simulación)
 * Fecha: 20 de enero de 2026
 */

require_once __DIR__ . '/../config/config_enhanced.php';
require_once __DIR__ . '/webhook.php';
error_log('webhook_replay loaded');

// Suprimir errores para obtener JSON limpio
error_reporting(E_ERROR | E_PARSE);

$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
if (!$debugMode) {
    requireAuthentication();
}

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Método no permitido. Use POST.']);
    exit;
}

try {
    error_log('webhook_replay START');
    $raw = file_get_contents('php://input');
    error_log('webhook_replay raw length: ' . strlen($raw));
    $data = json_decode($raw, true);
    if (!$data) {
        error_log('webhook_replay: invalid json');
        http_response_code(400);
        echo json_encode(['error' => 'JSON inválido o vacío']);
        exit;
    }

    $webhook = new WhatsAppWebhook();
    $ok = $webhook->processPayload($data);

    if ($ok) {
        echo json_encode(['success' => true, 'message' => 'Payload reproducido correctamente']);
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'El payload no contenía entradas válidas']);
    }

} catch (Exception $e) {
    error_log('Error in webhook_replay.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor']);
}
