<?php

declare(strict_types=1);

require_once __DIR__ . '/config.php';
Security::headers(true);

$limit = Security::rateLimit('system-message|' . Security::clientIp(), 120, 60);
if (!$limit['allowed']) {
    Security::json(['ok' => false, 'error' => 'RATE_LIMIT'], 429);
}

$body = [];
if (str_contains(strtolower((string) ($_SERVER['CONTENT_TYPE'] ?? '')), 'application/json')) {
    $decoded = json_decode((string) file_get_contents('php://input'), true);
    if (is_array($decoded)) {
        $body = $decoded;
    }
}

$key = trim((string) ($_GET['key'] ?? $body['key'] ?? ''));
if ($key === '' || !preg_match('/^[A-Z0-9_]{2,50}$/', $key)) {
    Security::json(['ok' => false, 'error' => 'BAD_REQUEST', 'message' => 'Clave no válida.'], 400);
}

try {
    $stmt = $pdo->prepare('SELECT contenido FROM mensajes_sistema WHERE clave = ? LIMIT 1');
    $stmt->execute([$key]);
    $content = $stmt->fetchColumn();
    if (!is_string($content)) {
        Security::json(['ok' => false, 'key' => $key, 'content' => '', 'error' => 'NOT_FOUND'], 404);
    }
    Security::json(['ok' => true, 'key' => $key, 'content' => $content]);
} catch (Throwable $e) {
    error_log('Error en get_message.php: ' . $e->getMessage());
    Security::json(['ok' => false, 'error' => 'DB', 'message' => 'No se pudo cargar el mensaje.'], 500);
}
