<?php
/**
 * API - Obtener payload crudo de un webhook
 * Fecha: 20 de enero de 2026
 */

require_once '../config/config_enhanced.php';

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

// Modo debug: desactivar autenticación si existe el parámetro debug
$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: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

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

try {
    $db = Database::getInstance();

    $id = intval($_GET['id'] ?? 0);
    if (!$id) {
        http_response_code(400);
        echo json_encode(['error' => 'ID de webhook requerido']);
        exit;
    }

    $row = $db->fetch(
        'SELECT id, request_body, response_body, status_code, ip_address, created_at FROM webhook_logs WHERE id = ? LIMIT 1',
        [$id]
    );

    if (!$row) {
        http_response_code(404);
        echo json_encode(['error' => 'Registro no encontrado']);
        exit;
    }

    // Intentar parsear JSON bonito
    $pretty = null;
    $decoded = json_decode($row['request_body'], true);
    if ($decoded !== null) {
        $pretty = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }

    echo json_encode([
        'success' => true,
        'data' => [
            'id' => $row['id'],
            'request_body' => $row['request_body'],
            'request_body_pretty' => $pretty,
            'response_body' => $row['response_body'],
            'status_code' => $row['status_code'],
            'ip_address' => $row['ip_address'],
            'created_at' => $row['created_at']
        ]
    ]);

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