<?php
/**
 * Monero wallet RPC balance proxy.
 * Forwards the exact JSON-RPC get_balance request server-side to avoid browser CORS.
 */
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(204);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$rpcUrl = 'https://monero.nationalelectricwatercooler.store/json_rpc';
$payload = json_encode([
    'jsonrpc' => '2.0',
    'id' => '0',
    'method' => 'get_balance'
]);

$ch = curl_init($rpcUrl);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($payload)
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => true
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($curlError) {
    http_response_code(502);
    echo json_encode(['error' => 'Upstream RPC error', 'detail' => $curlError]);
    exit;
}

http_response_code(($httpCode >= 200 && $httpCode < 300) ? 200 : $httpCode);
echo $response ?: '{}';
