<?php
/**
 * 小栈AI - SG16 环境检测 & 安装向导
 *
 * 两种用法：
 *   1. 被 xzdbk-ai.php require → 注册后台提示，引导用户跳转到本页面
 *   2. 用户直接访问（或带 ?xzd_wizard=1）→ 显示完整安装向导
 *
 * ⚠️ 本文件必须保持明文，不能被 SG16 加密！
 */

// ── 向导模式：直接访问时走这里，不依赖 WordPress ──
if (!defined('ABSPATH') || isset($_GET['xzd_wizard'])) {
    header('Content-Type: text/html; charset=utf-8');
    header('X-Robots-Tag: noindex');

    // 环境检测
    $phpVer   = phpversion();
    $phpMajor = substr($phpVer, 0, 3);
    $isWin    = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
    $isTS     = defined('ZEND_THREAD_SAFE') && ZEND_THREAD_SAFE;
    $tsTag    = $isTS ? 'ts' : '';
    $osName   = $isWin ? 'Windows' : 'Linux';
    $osKey    = $isWin ? 'win' : 'unix';
    $extName  = $isWin ? 'win' : 'lin';
    $loader   = "ixed.{$phpMajor}{$tsTag}.{$extName}";
    $dlUrl    = "https://www.xzdbk.com/wp-download/loader/{$osKey}/{$loader}";
    $sgOk     = function_exists('sg_load');

    $extDir   = ini_get('extension_dir');
    $iniFile  = php_ini_loaded_file();
    $sapi     = php_sapi_name();
    $bit      = PHP_INT_SIZE === 4 ? 32 : 64;

    // 不兼容扩展
    $incompat = [];
    foreach (get_loaded_extensions() as $ext) {
        foreach (['xdebug', 'ionCube', 'zend_loader'] as $bad) {
            if (stripos($ext, $bad) !== false) $incompat[] = $ext;
        }
    }
    $incompat = array_unique($incompat);

    $rows = [
        '操作系统'        => php_uname(),
        'PHP 版本'        => "{$phpVer}（" . ($isTS ? 'TS' : 'NTS') . " / {$bit}位）",
        '运行模式'        => $sapi,
        'PHP 配置文件'     => $iniFile ?: '未检测到',
        'PHP 扩展目录'     => $extDir ?: '未检测到',
        '需要的 Loader 文件' => "<code>{$loader}</code>",
        'SG16 状态'        => $sgOk
            ? '<span style="color:green;font-weight:bold;">✅ 已安装</span>'
            : '<span style="color:#d63638;font-weight:bold;">❌ 未安装</span>',
    ];

    $envHTML = '';
    foreach ($rows as $k => $v) {
        $envHTML .= '<tr><td class="lbl">' . $k . '</td><td>' . $v . '</td></tr>';
    }

    $incompatHTML = '';
    if ($incompat) {
        $incompatHTML = '<div class="warn"><strong>⚠ 注意：</strong>检测到 ' . implode('、', $incompat) . '，可能与 SG16 冲突，建议在 php.ini 中禁用。</div>';
    }

    $btnHTML = '';
    if ($sgOk) {
        $btnHTML = '<p style="text-align:center;margin-top:30px;">SG16 已就绪，<a href="javascript:history.back()">返回后台</a> 重新激活插件即可。</p>';
    } else {
        $btnHTML = '
        <div class="steps">
            <p><strong>步骤 1：</strong> <a class="btn" href="' . htmlspecialchars($dlUrl) . '">📥 下载 ' . htmlspecialchars($loader) . '</a></p>
            <p><strong>步骤 2：</strong> 把 <code>' . htmlspecialchars($loader) . '</code> 复制到 PHP 扩展目录：</p>
            <pre>' . htmlspecialchars($extDir ?: '请查看 phpinfo()') . '</pre>
            <p><strong>步骤 3：</strong> 编辑 <code>' . htmlspecialchars($iniFile ?: 'php.ini') . '</code>，在末尾加一行：</p>
            <pre>extension=' . htmlspecialchars($loader) . '</pre>
            <p><strong>步骤 4：</strong> 重启 Web 服务器 或 PHP-FPM</p>
            <p><strong>步骤 5：</strong> <a class="btn" href="javascript:location.reload()">🔄 刷新本页验证</a></p>
        </div>';
    }

    echo '<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SG16 安装向导 — 小栈AI</title>
<style>
    body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:#f5f5f5;color:#333;margin:0;padding:40px 20px;}
    .card{max-width:700px;margin:0 auto;background:#fff;border-radius:8px;box-shadow:0 2px 12px rgba(0,0,0,.08);overflow:hidden;}
    .head{background:#d63638;color:#fff;padding:24px 30px;text-align:center;}
    .head h2{margin:0;font-size:22px;}
    .head p{margin:6px 0 0;opacity:.85;font-size:14px;}
    .body{padding:24px 30px;}
    .body h3{font-size:16px;margin:20px 0 10px;border-bottom:2px solid #eee;padding-bottom:6px;}
    table{width:100%;border-collapse:collapse;}
    td{padding:8px 0;border-bottom:1px solid #f0f0f0;font-size:14px;}
    .lbl{font-weight:600;width:160px;color:#555;}
    code{background:#f0f0f0;color:#d63638;padding:2px 6px;border-radius:3px;font-size:13px;}
    pre{background:#2d2d2d;color:#f8f8f2;padding:12px 16px;border-radius:4px;font-size:13px;overflow-x:auto;}
    .btn{display:inline-block;padding:10px 22px;background:#d63638;color:#fff!important;text-decoration:none;border-radius:4px;font-weight:600;font-size:14px;transition:background .2s;}
    .btn:hover{background:#b32d2e;}
    .steps p{margin:14px 0;font-size:14px;}
    .warn{background:#fff3cd;border:1px solid #ffc107;border-radius:4px;padding:10px 14px;margin:14px 0;font-size:13px;}
</style>
</head>
<body>
<div class="card">
    <div class="head"><h2>SourceGuardian 安装向导</h2><p>小栈AI 插件需要 SG16 解码器才能运行 · 支持 PHP 8.0~8.4</p></div>
    <div class="body">
        <h3>📋 环境检测</h3>
        <table>' . $envHTML . '</table>
        ' . $incompatHTML . '
        <h3>🔧 安装步骤</h3>
        ' . $btnHTML . '
    </div>
</div>
</body>
</html>';
    exit;
}

// ── 正常模式：被插件加载时，注册后台提示 ──
namespace XZD\AI\V5\Core;

class LoaderInstaller
{
    public static function init(): void
    {
        add_action('admin_notices', [self::class, 'showNotice']);
    }

    public static function showNotice(): void
    {
        $phpVer  = phpversion();
        $phpMaj  = substr($phpVer, 0, 3);
        $isTS    = defined('ZEND_THREAD_SAFE') && ZEND_THREAD_SAFE;
        $tsTag   = $isTS ? 'ts' : '';
        $isWin   = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
        $extName = $isWin ? 'win' : 'lin';
        $loader  = "ixed.{$phpMaj}{$tsTag}.{$extName}";
        $osKey   = $isWin ? 'win' : 'unix';
        $dlUrl   = "https://www.xzdbk.com/wp-download/loader/{$osKey}/{$loader}";
        $wizUrl  = plugin_dir_url(defined('XZD_AI_FILE') ? XZD_AI_FILE : __DIR__ . '/../../../xzdbk-ai.php') . 'src/Core/LoaderInstaller.php?xzd_wizard=1';

        echo '<div class="notice notice-error" style="padding:16px 20px;border-left:4px solid #d63638;">
            <h3 style="margin:0 0 6px;">小栈AI助手没启动 — 还差一步</h3>
            <p style="margin:0 0 10px;font-size:14px;">
                服务器是 🐘 PHP ' . esc_html($phpVer) . '（' . ($isTS ? 'TS' : 'NTS') . '），
                需要 <code>' . esc_html($loader) . '</code> 才能运行。
            </p>
            <p style="margin:0;">
                <a href="' . esc_url($dlUrl) . '" class="button button-primary" target="_blank">下载解码文件</a>
                <a href="' . esc_url($wizUrl) . '" class="button" target="_blank">打开安装向导</a>
            </p>
        </div>';
    }
}
