<?php
declare(strict_types=1);

/**
 * 新手村 store_public API 請求標頭（金鑰 + 本站對外網址，供新手村比對金鑰綁定網域）。
 *
 * @return list<string>
 */
function fate_spa_http_request_headers(string $apiKey): array
{
    $headers = ['Accept: application/json'];
    if ($apiKey !== '') {
        $headers[] = 'X-Store-API-Key: ' . $apiKey;
    }
    if (!function_exists('fate_spa_member_site_url')) {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'spa_store_public_client_key.php';
    }
    $siteUrl = fate_spa_member_site_url();
    if ($siteUrl !== '') {
        $headers[] = 'X-Store-Site-Origin: ' . $siteUrl;
    }

    return $headers;
}

/**
 * @param int|null $timeoutSec 逾時秒數；null 時使用環境變數 FATE_SPA_HTTP_TIMEOUT_SEC（預設 50）
 * @return array{ok:bool,data?:array,error?:string,http:int,raw?:string}
 */
function fate_spa_http_get_json(string $url, string $apiKey, ?int $timeoutSec = null): array
{
    $headers = fate_spa_http_request_headers($apiKey);
    $t = $timeoutSec ?? max(10, min(120, (int) (getenv('FATE_SPA_HTTP_TIMEOUT_SEC') ?: '50')));
    $connT = min(15, max(5, (int) ceil($t / 4)));
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT => $t,
            CURLOPT_CONNECTTIMEOUT => $connT,
        ]);
        $raw = curl_exec($ch);
        $http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);
        if ($raw === false || $raw === '') {
            return ['ok' => false, 'error' => $err !== '' ? $err : '空回應', 'http' => $http];
        }
        $data = json_decode($raw, true);
        if (!is_array($data)) {
            return ['ok' => false, 'error' => '回應不是有效 JSON', 'http' => $http, 'raw' => $raw];
        }
        return ['ok' => true, 'data' => $data, 'http' => $http, 'raw' => $raw];
    }
    $ctx = [
        'http' => [
            'timeout' => $t,
            'header' => implode("\r\n", $headers),
        ],
    ];
    $raw = @file_get_contents($url, false, stream_context_create($ctx));
    if ($raw === false) {
        return ['ok' => false, 'error' => '無法連線（請確認 allow_url_fopen）', 'http' => 0];
    }
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        return ['ok' => false, 'error' => '回應不是有效 JSON', 'http' => 200, 'raw' => $raw];
    }
    return ['ok' => true, 'data' => $data, 'http' => 200, 'raw' => $raw];
}
