<?php

function coinfiraRequest(string $method, string $requestPath, ?array $payload = null): array
{
    $baseUrl = getenv('CF_API_BASE_URL') ?: 'https://coinfira.com';
    $apiKey = getenv('CF_API_KEY');
    $apiSecret = getenv('CF_API_SECRET');
    $timestamp = (new DateTimeImmutable('now', new DateTimeZone('UTC')))
        ->format('Y-m-d\TH:i:s.v\Z');
    $rawBody = $payload === null
        ? ''
        : json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
    $canonical = $timestamp . "\n" . strtoupper($method) . "\n"
        . $requestPath . "\n" . $rawBody;
    $signature = base64_encode(hash_hmac('sha256', $canonical, $apiSecret, true));

    $headers = [
        'Content-Type: application/json',
        'X-CF-API-Key: ' . $apiKey,
        'X-CF-Timestamp: ' . $timestamp,
        'X-CF-Signature: ' . $signature,
    ];
    $curl = curl_init($baseUrl . $requestPath);
    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => strtoupper($method),
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    if ($payload !== null) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $rawBody);
    }

    $responseBody = curl_exec($curl);
    if ($responseBody === false) {
        throw new RuntimeException(curl_error($curl));
    }
    $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
    curl_close($curl);
    $data = json_decode($responseBody, true, flags: JSON_THROW_ON_ERROR);
    if ($status < 200 || $status >= 300) {
        $code = $data['error']['code'] ?? 'unknown_error';
        $message = $data['error']['message'] ?? ('HTTP ' . $status);
        throw new RuntimeException($code . ': ' . $message, $status);
    }
    return ['status' => $status, 'data' => $data];
}

$result = coinfiraRequest('POST', '/api/v1/energy/estimate', [
    'from_address' => 'TESVFJJpXqHsTvdoHy58qFAvsZhHeqbQgZ',
    'to_address' => 'TSknn7sfj5qJEPYLesBuSDo9u1h87GveZk',
]);
print_r($result);
