<?php
// api/relay-result.php — Store relay result in session/cache
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) $input = $_POST;

$key = preg_replace('/[^a-zA-Z0-9_]/', '', (string)($input['key'] ?? $input['ubrn'] ?? $_GET['key'] ?? $_GET['ubrn'] ?? ''));
$data = $input['data'] ?? null;
$source = $input['source'] ?? '';
$type = $input['type'] ?? 'unknown';

if (!$key) {
    echo json_encode(['ok' => false, 'error' => 'No key']);
    exit;
}

// Cache the result
$cacheDir = dirname(__DIR__) . '/cache';
if (!is_dir($cacheDir)) @mkdir($cacheDir, 0755, true);

$cacheFile = $cacheDir . '/relay_' . $key . '.json';
$cacheData = [
    'key'    => $key,
    'type'   => $type,
    'data'   => $data,
    'source' => $source,
    'time'   => time(),
];
@file_put_contents($cacheFile, json_encode($cacheData));

echo json_encode(['ok' => true, 'cached' => true, 'key' => $key]);
