<?php
declare(strict_types=1);

/**
 * 客户区 header 用：不依赖 DOCUMENT_ROOT 定位 license/（避免 public 路径不一致导致 500）。
 */

require_once __DIR__ . '/bootstrap.php';

function yuser_ensure_license_plain_files(string $root): void
{
    $boot = $root . '/license/bootstrap.php';
    if (is_file($boot) && filesize($boot) > 32) {
        $head = (string) file_get_contents($boot, false, null, 0, 4);
        if (strncmp($head, 'YENC', 4) !== 0 && strncmp($head, '<?php', 5) === 0) {
            return;
        }
    }
    if (!is_dir($root . '/license')) {
        @mkdir($root . '/license', 0755, true);
    }
    foreach (['remote.php', 'bootstrap.php'] as $name) {
        $vault = $root . '/.vault/license/' . $name;
        $plain = $root . '/license/' . $name;
        if (!is_file($vault)) {
            continue;
        }
        yuser_write_plain_from_encrypted($vault, $plain);
    }
}

function yuser_load_license_bootstrap(): void
{
    $root = yuser_theme_root();
    yuser_ensure_license_plain_files($root);
    $boot = $root . '/license/bootstrap.php';
    if (!is_file($boot)) {
        http_response_code(500);
        header('Content-Type: text/html; charset=utf-8');
        echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>主题错误</title></head><body style="font-family:system-ui;padding:32px">';
        echo '<h1>无法加载授权模块</h1><p>未找到：<code>' . htmlspecialchars($boot, ENT_QUOTES, 'UTF-8') . '</code></p>';
        echo '<p>请重新运行 <code>/install.php</code> 或 <code>/yuser_theme_unlock.php</code>。</p></body></html>';
        exit;
    }
    require_once $boot;
}
