<?php
declare(strict_types=1);

/**
 * 主题解密急救页（须已授权域名，否则不解密）
 * 访问：https://您的域名/yuser_theme_unlock.php
 * 完成后请删除本文件。
 */

$publicRoot = __DIR__;
$themeDir = $publicRoot . '/themes/clientarea/default';
$bootstrap = $themeDir . '/yuser/bootstrap.php';
$licenseVerify = $themeDir . '/yuser/license_verify.php';

if (!is_file($bootstrap)) {
    header('Content-Type: text/html; charset=utf-8');
    http_response_code(404);
    echo '<p>未找到主题目录 themes/clientarea/default</p>';
    exit;
}

require_once $licenseVerify;

$lic = yuser_license_assert_authorized();
if (empty($lic['authorized'])) {
    yuser_license_render_install_blocked($lic, '无法解密主题');
    exit;
}

require_once $bootstrap;

if (!function_exists('openssl_decrypt')) {
    header('Content-Type: text/html; charset=utf-8');
    http_response_code(500);
    echo '<p>服务器未启用 OpenSSL 扩展，无法解密主题。</p>';
    exit;
}

if (!is_writable($themeDir)) {
    header('Content-Type: text/html; charset=utf-8');
    http_response_code(500);
    echo '<p>主题目录不可写，请 chmod 755/775：<code>' . htmlspecialchars($themeDir, ENT_QUOTES, 'UTF-8') . '</code></p>';
    exit;
}

$result = yuser_theme_install_unlock($themeDir);
$ready = yuser_theme_is_ready($themeDir);

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>主题解密</title>
  <style>body{font-family:system-ui,sans-serif;padding:32px;max-width:640px;margin:0 auto;color:#1d2129}code{background:#f2f3f5;padding:2px 6px;border-radius:4px}.ok{color:#00b42a}.bad{color:#f53f3f}</style>
</head>
<body>
  <h1>主题解密</h1>
  <p>域名授权已通过（<code><?php echo htmlspecialchars((string) $lic['domain'], ENT_QUOTES, 'UTF-8'); ?></code>）。</p>
  <p>解密文件：<strong><?php echo (int) $result['files']; ?></strong>，失败：<strong><?php echo (int) $result['errors']; ?></strong></p>
  <p>合并入口模板：<?php echo htmlspecialchars(implode('、', $result['merged']) ?: '无', ENT_QUOTES, 'UTF-8'); ?></p>
  <p>清理旧 .yenc：<strong><?php echo (int) $result['yenc_removed']; ?></strong> 个</p>
  <?php if (!empty($result['failed'])): ?>
  <p>失败文件：<code><?php echo htmlspecialchars(implode(', ', array_slice($result['failed'], 0, 10)), ENT_QUOTES, 'UTF-8'); ?></code></p>
  <?php endif; ?>
  <p class="<?php echo $ready ? 'ok' : 'bad'; ?>">
    <?php echo $ready ? '✓ 主题已就绪，请刷新客户区页面。' : '✗ 仍异常，请检查目录权限或重新运行 install.php'; ?>
  </p>
  <p>完成后请删除 <code>yuser_theme_unlock.php</code>。</p>
</body>
</html>
