<?php
declare(strict_types=1);

/**
 * 安装 / 急救解密用授权校验（明文，不依赖 .vault 内 license/）。
 * 与 license/remote.php 使用同一 Finally API。
 */

const YUSER_LICENSE_VENDOR = 'https://www.finally.chat';

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

function yuser_license_normalize_domain(string $host): string
{
    $h = strtolower(trim($host));
    $h = preg_replace('/:\d+$/', '', $h) ?? $h;
    if (str_starts_with($h, 'www.')) {
        $h = substr($h, 4);
    }
    return $h;
}

function yuser_license_local_portal_url(): string
{
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $doc = rtrim((string) ($_SERVER['DOCUMENT_ROOT'] ?? ''), '/\\');
    $rel = '/clientarea_default_theme_editor/';
    if ($doc !== '') {
        if (!is_dir($doc . $rel) && is_dir($doc . '/public' . $rel)) {
            $rel = '/public' . $rel;
        }
    }
    return $scheme . '://' . $host . $rel;
}

function yuser_license_cache_dir(): string
{
    $docRoot = rtrim((string) ($_SERVER['DOCUMENT_ROOT'] ?? ''), '/');
    if ($docRoot !== '') {
        $d = dirname($docRoot) . '/data/theme_license_cache';
        $parent = dirname($d);
        if (is_dir($parent) || @mkdir($parent, 0755, true)) {
            if (!is_dir($d)) {
                @mkdir($d, 0755, true);
            }
            if (is_dir($d) && is_writable($d)) {
                return $d;
            }
        }
    }
    $fallback = rtrim(sys_get_temp_dir(), '/') . '/finally_theme_license_cache';
    if (!is_dir($fallback)) {
        @mkdir($fallback, 0755, true);
    }
    return $fallback;
}

function yuser_license_cache_file(string $normalizedDomain): string
{
    return yuser_license_cache_dir() . '/' . hash('sha256', $normalizedDomain) . '.json';
}

/** @return array<string, mixed>|null */
function yuser_license_cache_read(string $normalizedDomain): ?array
{
    $file = yuser_license_cache_file($normalizedDomain);
    if (!is_file($file)) {
        return null;
    }
    $j = json_decode((string) file_get_contents($file), true);
    if (!is_array($j) || !isset($j['expires'], $j['result']) || !is_array($j['result'])) {
        return null;
    }
    if ((int) $j['expires'] < time()) {
        @unlink($file);
        return null;
    }
    return $j['result'];
}

/** @param array<string, mixed> $result */
function yuser_license_cache_write(string $normalizedDomain, array $result, int $ttlSeconds): void
{
    $file = yuser_license_cache_file($normalizedDomain);
    $payload = [
        'expires' => time() + max(60, $ttlSeconds),
        'result' => $result,
    ];
    @file_put_contents($file, json_encode($payload, JSON_UNESCAPED_UNICODE));
}

/** @return array<string, mixed>|null */
function yuser_license_remote_verify(string $host): ?array
{
    $norm = yuser_license_normalize_domain($host);
    if ($norm === '') {
        return null;
    }
    $url = YUSER_LICENSE_VENDOR . '/theme_license_api/index.php?action=verify&domain=' . rawurlencode($norm);
    $ctx = stream_context_create(['http' => ['timeout' => 8, 'header' => "User-Agent: FinallyTheme-Install/1\r\n"]]);
    $raw = @file_get_contents($url, false, $ctx);
    if ($raw === false) {
        return null;
    }
    $j = json_decode($raw, true);
    return is_array($j) ? $j : null;
}

/** @return array<string, mixed>|null */
function yuser_license_remote_verify_cached(?string $host = null): ?array
{
    $host = $host ?? ($_SERVER['HTTP_HOST'] ?? '');
    $norm = yuser_license_normalize_domain($host);
    if ($norm === '') {
        return null;
    }
    $cached = yuser_license_cache_read($norm);
    if ($cached !== null) {
        return $cached;
    }
    $result = yuser_license_remote_verify($host);
    if ($result === null) {
        return null;
    }
    if (($result['status'] ?? '') === 'rate_limited') {
        $stale = yuser_license_cache_read($norm);
        if ($stale !== null) {
            return $stale;
        }
        return $result;
    }
    $ttl = !empty($result['authorized']) ? 3600 : 300;
    yuser_license_cache_write($norm, $result, $ttl);
    return $result;
}

/**
 * @return array{authorized: bool, message: string, domain: string, status: string}
 */
function yuser_license_assert_authorized(?string $host = null): array
{
    $host = $host ?? ($_SERVER['HTTP_HOST'] ?? '');
    $domain = yuser_license_normalize_domain($host);
    $remote = yuser_license_remote_verify_cached($host);
    if ($remote === null) {
        return [
            'authorized' => false,
            'message' => '无法连接授权服务器，请稍后重试',
            'domain' => $domain,
            'status' => 'unreachable',
        ];
    }
    $authorized = !empty($remote['authorized']);
    return [
        'authorized' => $authorized,
        'message' => (string) ($remote['message'] ?? ($authorized ? '已授权' : '当前域名未授权，无法安装主题')),
        'domain' => (string) ($remote['domain'] ?? $domain),
        'status' => (string) ($remote['status'] ?? 'unknown'),
    ];
}

/** @param array{authorized: bool, message: string, domain: string} $verify */
function yuser_license_render_install_blocked(array $verify, string $title = '无法安装主题'): void
{
    $msg = (string) ($verify['message'] ?? '当前域名未授权');
    $domain = (string) ($verify['domain'] ?? '');
    http_response_code(403);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
    echo '<title>' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</title>';
    echo '<style>body{margin:0;font-family:system-ui,sans-serif;background:#f2f3f5;display:flex;align-items:center;justify-content:center;min-height:100vh;padding:24px}';
    echo '.box{max-width:480px;background:#fff;border-radius:12px;padding:32px;box-shadow:0 8px 24px rgba(0,0,0,.08);text-align:center}';
    echo 'h1{color:#f53f3f;font-size:22px;margin:0 0 12px}p{color:#4e5969;line-height:1.6;font-size:14px}code{background:#f2f3f5;padding:2px 6px;border-radius:4px}';
    echo 'a.btn{display:inline-block;margin-top:20px;padding:10px 20px;background:#165dff;color:#fff;text-decoration:none;border-radius:6px;font-weight:600}</style></head><body>';
    echo '<div class="box"><h1>' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</h1>';
    echo '<p>' . htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') . '</p>';
    if ($domain !== '') {
        echo '<p>当前域名：<code>' . htmlspecialchars($domain, ENT_QUOTES, 'UTF-8') . '</code></p>';
    }
    echo '<p>请前往主题管理后台绑定域名并申请授权。</p>';
    $portalUrl = yuser_license_local_portal_url();
    echo '<a class="btn" href="' . htmlspecialchars($portalUrl, ENT_QUOTES, 'UTF-8') . '">主题管理后台</a>';
    echo '<p style="margin-top:16px;font-size:12px;color:#86909c">正版授权咨询：云脉智慧平台 · www.finally.chat</p></div></body></html>';
}
