<?php
declare(strict_types=1);

/**
 * 客户站门户 — 仅通过 HTTP 调用 Yuser 官方 theme_license_api，不依赖 theme_hub_common。
 */

if (!function_exists('str_contains')) {
    function str_contains(string $haystack, string $needle): bool
    {
        return $needle === '' || strpos($haystack, $needle) !== false;
    }
}

if (!function_exists('str_starts_with')) {
    function str_starts_with(string $haystack, string $needle): bool
    {
        return $needle === '' || strncmp($haystack, $needle, strlen($needle)) === 0;
    }
}

/** @return array<string, mixed> */
function portal_hub_default_config(): array
{
    return [
        'hub_api_base' => 'https://www.finally.chat/theme_license_api/index.php',
        'geetest_captcha_id' => 'f178e6f69841ca812f755c3f3af49670',
        'update_manifest_url' => '',
        'update_download_key' => '',
    ];
}

/** @return array<string, mixed> */
function portal_hub_config(): array
{
    static $cfg = null;
    if ($cfg !== null) {
        return $cfg;
    }
    $file = __DIR__ . '/config.php';
    if (is_file($file)) {
        $loaded = require $file;
        $cfg = is_array($loaded) ? $loaded : portal_hub_default_config();
        return $cfg;
    }
    $example = __DIR__ . '/config.example.php';
    if (is_file($example)) {
        $loaded = require $example;
        $cfg = is_array($loaded) ? $loaded : portal_hub_default_config();
        return $cfg;
    }
    $cfg = portal_hub_default_config();
    return $cfg;
}

/** 无 config.php 时静默生成（未跑 install.php 也可进主题后台） */
function portal_ensure_config_file(): void
{
    $file = __DIR__ . '/config.php';
    if (is_file($file) || !is_writable(__DIR__)) {
        return;
    }
    $cfg = portal_hub_config();
    $lines = ["<?php", "return ["];
    foreach ($cfg as $k => $v) {
        $lines[] = '    ' . var_export($k, true) . ' => ' . var_export($v, true) . ',';
    }
    $lines[] = '];';
    $lines[] = '';
    @file_put_contents($file, implode("\n", $lines));
}

function portal_hub_api_base(): string
{
    $cfg = portal_hub_config();
    $base = trim((string) ($cfg['hub_api_base'] ?? 'https://www.finally.chat/theme_license_api/index.php'));
    if ($base === '') {
        $base = 'https://www.finally.chat/theme_license_api/index.php';
    }
    return rtrim($base, '?&');
}

function portal_geetest_captcha_id(): string
{
    $cfg = portal_hub_config();
    $id = trim((string) ($cfg['geetest_captcha_id'] ?? 'f178e6f69841ca812f755c3f3af49670'));
    return $id !== '' ? $id : 'f178e6f69841ca812f755c3f3af49670';
}

/**
 * @param array<string, mixed> $payload
 * @return array<string, mixed>
 */
function portal_hub_request(string $action, array $payload = [], string $method = 'POST'): array
{
    $url = portal_hub_api_base() . (str_contains(portal_hub_api_base(), '?') ? '&' : '?') . 'action=' . rawurlencode($action);
    if ($method === 'GET' && $payload !== []) {
        $url .= '&' . http_build_query($payload);
    }
    $opts = [
        'http' => [
            'method' => $method,
            'timeout' => 20,
            'header' => "Content-Type: application/json\r\nUser-Agent: YuserThemePortal/2\r\n",
            'ignore_errors' => true,
        ],
        'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
    ];
    if ($method === 'POST') {
        $opts['http']['content'] = json_encode($payload, JSON_UNESCAPED_UNICODE);
    }
    $raw = @file_get_contents($url, false, stream_context_create($opts));
    if ($raw === false) {
        return ['ok' => false, 'error' => '无法连接 Yuser 授权服务器'];
    }
    $j = json_decode($raw, true);
    return is_array($j) ? $j : ['ok' => false, 'error' => '授权服务器返回异常'];
}
