<?php
// Proxy endpoint for JSON-RPC calls to RPC providers configured in config/rpc.php
// Usage: POST /app/api/rpc/proxy.php?chain=137 with JSON-RPC body

header('Content-Type: application/json');
$base = realpath(__DIR__ . '/../../../');
if (file_exists($base . '/config/rpc.php')) $rpc = include $base . '/config/rpc.php';
if (!isset($rpc) || !is_array($rpc)) { http_response_code(500); echo json_encode(['error'=>'rpc_not_configured']); exit; }

$chain = isset($_GET['chain']) ? intval($_GET['chain']) : 0;
if (!$chain || !isset($rpc[$chain])) { http_response_code(400); echo json_encode(['error'=>'invalid_chain']); exit; }

// Read raw JSON body
$raw = file_get_contents('php://input');
if (!$raw) { http_response_code(400); echo json_encode(['error'=>'empty_body']); exit; }

$payload = json_decode($raw, true);
if (!$payload) { http_response_code(400); echo json_encode(['error'=>'invalid_json']); exit; }

// Allow only read methods to avoid proxying sends
$allowed_methods = [
    'eth_getTransactionReceipt',
    'eth_getTransactionByHash',
    'eth_call',
    'eth_blockNumber',
    'eth_getBlockByNumber',
    'eth_getTransactionCount',
    'eth_getLogs'
];

$method = isset($payload['method']) ? $payload['method'] : '';
if (!in_array($method, $allowed_methods, true)) {
    http_response_code(403);
    echo json_encode(['error'=>'method_not_allowed','method'=>$method]);
    exit;
}

$rpc_url = $rpc[$chain];

$ch = curl_init($rpc_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $raw);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);

$res = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($res === false) {
    http_response_code(502);
    echo json_encode(['error'=>'upstream_request_failed','errno'=>$errno,'errmsg'=>$err]);
    exit;
}

// Forward upstream response verbatim
http_response_code($http_code ? $http_code : 200);
echo $res;
?>