<?php
session_start();

require_once __DIR__ . '/../common/version.php';

if (!function_exists('e')) {
    function e($str) {
        return htmlspecialchars((string) ($str ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('hasRequiredSg16Extension')) {
    function hasRequiredSg16Extension() {
        return function_exists('sg_load')
            || extension_loaded('sg16')
            || extension_loaded('sourceguardian')
            || extension_loaded('SourceGuardian');
    }
}

if (!function_exists('installFetchRemoteText')) {
    function installFetchRemoteText($url, $timeout = 3) {
        $url = trim((string) $url);
        if ($url === '') {
            return '';
        }

        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => max(2, (int) $timeout),
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_MAXREDIRS => 2,
                CURLOPT_USERAGENT => 'BeitaBlog/' . (defined('BTBLOG_VERSION') ? BTBLOG_VERSION : '2.0') . ' Installer',
            ]);
            $body = curl_exec($ch);
            $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            return $status === 200 ? trim((string) $body) : '';
        }

        $context = stream_context_create([
            'http' => [
                'timeout' => max(2, (int) $timeout),
                'header' => 'User-Agent: BeitaBlog/' . (defined('BTBLOG_VERSION') ? BTBLOG_VERSION : '2.0') . " Installer\r\n",
            ],
        ]);
        $body = @file_get_contents($url, false, $context);

        return $body === false ? '' : trim((string) $body);
    }
}

$lockFile = __DIR__ . '/install.lock';
if (file_exists($lockFile)) {
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Beita Blog 已安装</title>
        <style>
            * { box-sizing: border-box; margin: 0; padding: 0; }
            body {
                min-height: 100vh;
                display: grid;
                place-items: center;
                padding: 20px;
                color: #eef6ff;
                font-family: 'Microsoft YaHei', sans-serif;
                background: linear-gradient(160deg, #09111d, #10182b 36%, #0a1120);
            }
            .box {
                width: min(560px, 100%);
                padding: 38px;
                border-radius: 28px;
                background: linear-gradient(135deg, rgba(255,255,255,.09), rgba(255,255,255,.04));
                border: 1px solid rgba(255,255,255,.12);
                box-shadow: 0 24px 60px rgba(0,0,0,.24);
            }
            h1 { margin-bottom: 14px; }
            p { color: rgba(255,255,255,.68); line-height: 1.8; }
            .actions { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 22px; }
            .actions a {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                text-decoration: none;
                color: #fff;
                padding: 12px 18px;
                border-radius: 14px;
                background: linear-gradient(135deg, #66ccff, #3aa9ff);
            }
            .actions a.secondary {
                background: transparent;
                border: 1px solid rgba(255,255,255,.14);
                color: rgba(255,255,255,.82);
            }
            code {
                padding: 2px 6px;
                border-radius: 8px;
                background: rgba(255,255,255,.08);
            }
        </style>
    </head>
    <body>
        <div class="box">
                    <h1>Beita Blog 已经安装完成</h1>
            <p>如果你需要重新安装，请先删除 <code>install/install.lock</code> 文件，再重新访问安装页。</p>
            <div class="actions">
                <a href="../index.php">访问首页</a>
                <a class="secondary" href="../admin/login.php">进入后台</a>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

$step = max(1, min(4, (int) ($_GET['step'] ?? 1)));
$error = $_SESSION['install_error'] ?? '';
$success = $_SESSION['install_success'] ?? '';
$installDb = $_SESSION['install_db'] ?? [];
$installSite = $_SESSION['install_site'] ?? [];
$installFinalizePayload = $_SESSION['install_finalize_payload'] ?? [];
$runtimeProbePassed = !empty($_SESSION['install_runtime_probe_passed']);
unset($_SESSION['install_error'], $_SESSION['install_success']);

$currentVersion = defined('BTBLOG_VERSION') ? BTBLOG_VERSION : '2.0';
$remoteVersion = preg_replace('/^\xEF\xBB\xBF/', '', installFetchRemoteText(defined('BTBLOG_UPDATE_VERSION_URL') ? BTBLOG_UPDATE_VERSION_URL : 'https://www.btblog.cn/ver.txt', 3));
$remoteVersion = trim((string) $remoteVersion);
$hasNewVersion = $remoteVersion !== ''
    && preg_match('/^\d+(?:\.\d+)*$/', $remoteVersion)
    && version_compare($remoteVersion, $currentVersion, '>');

if ($step > 1 && !hasRequiredSg16Extension()) {
    $_SESSION['install_error'] = '检测到当前 PHP 环境未安装 SG16 / SourceGuardian Loader，请先安装扩展后再继续安装。';
    header('Location: index.php?step=1');
    exit;
}

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$basePath = rtrim(str_replace('\\', '/', dirname(dirname($_SERVER['SCRIPT_NAME'] ?? '/install/index.php'))), '/');
if ($basePath === '.' || $basePath === '/') {
    $basePath = '';
}
$defaultSiteUrl = $scheme . '://' . $host . $basePath;

$checks = [
    ['PHP 7.2+', version_compare(PHP_VERSION, '7.2.0', '>=')],
    ['SG16 / SourceGuardian Loader', hasRequiredSg16Extension()],
    ['PDO 扩展', extension_loaded('pdo')],
    ['PDO MySQL 驱动', extension_loaded('pdo_mysql')],
    ['mbstring 扩展', extension_loaded('mbstring')],
    ['json 扩展', extension_loaded('json')],
    ['GD 扩展（可选）', extension_loaded('gd'), true],
    ['项目根目录可写', is_writable(dirname(__DIR__))],
    ['uploads 目录可写', is_dir(dirname(__DIR__) . '/uploads') ? is_writable(dirname(__DIR__) . '/uploads') : @mkdir(dirname(__DIR__) . '/uploads', 0755, true)],
    ['install 目录可写', is_writable(__DIR__)],
];

$allPassed = true;
foreach ($checks as $check) {
    $isOptional = $check[2] ?? false;
    if (!$isOptional && !$check[1]) {
        $allPassed = false;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Beita Blog 安装</title>
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            min-height: 100vh;
            padding: 32px 20px;
            font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
            color: #edf7ff;
            background:
                radial-gradient(circle at 20% 20%, rgba(102,204,255,.16), transparent 28%),
                radial-gradient(circle at 80% 18%, rgba(102,204,255,.10), transparent 26%),
                linear-gradient(160deg, #09111d, #10182b 36%, #0a1120);
        }
        .container {
            width: min(760px, 100%);
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 28px;
        }
        .header h1 {
            font-size: 2.2rem;
            margin-bottom: 10px;
        }
        .header p {
            color: rgba(255,255,255,.52);
        }
        .steps {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin-bottom: 24px;
        }
        .step {
            padding: 14px;
            border-radius: 16px;
            text-align: center;
            background: rgba(255,255,255,.05);
            border: 1px solid rgba(255,255,255,.08);
            color: rgba(255,255,255,.42);
        }
        .step.active,
        .step.done {
            color: #fff;
            background: rgba(102,204,255,.12);
            border-color: rgba(102,204,255,.24);
        }
        .card {
            padding: 30px;
            border-radius: 24px;
            background: linear-gradient(135deg, rgba(255,255,255,.09), rgba(255,255,255,.04));
            border: 1px solid rgba(255,255,255,.12);
            box-shadow: 0 24px 60px rgba(0,0,0,.22);
        }
        .card h2 {
            font-size: 1.3rem;
            margin-bottom: 20px;
        }
        .alert {
            padding: 14px 16px;
            border-radius: 14px;
            margin-bottom: 18px;
        }
        .alert-error {
            background: rgba(248,113,113,.14);
            border: 1px solid rgba(248,113,113,.24);
            color: #fca5a5;
        }
        .alert-success {
            background: rgba(16,185,129,.14);
            border: 1px solid rgba(16,185,129,.24);
            color: #86efac;
        }
        .alert-warning {
            background: rgba(245,158,11,.14);
            border: 1px solid rgba(245,158,11,.24);
            color: #fbbf24;
        }
        .check-list {
            list-style: none;
        }
        .check-list li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            padding: 12px 14px;
            border-radius: 14px;
            background: rgba(255,255,255,.04);
            margin-bottom: 10px;
        }
        .status {
            padding: 4px 10px;
            border-radius: 999px;
            font-size: .8rem;
        }
        .pass {
            color: #86efac;
            background: rgba(16,185,129,.12);
        }
        .fail {
            color: #fca5a5;
            background: rgba(248,113,113,.12);
        }
        .form-group {
            margin-bottom: 18px;
        }
        .form-row {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 16px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: rgba(255,255,255,.68);
            font-size: .9rem;
        }
        small {
            display: block;
            margin-top: 6px;
            color: rgba(255,255,255,.34);
        }
        input,
        select {
            width: 100%;
            padding: 12px 14px;
            border-radius: 12px;
            border: 1px solid rgba(255,255,255,.1);
            background: rgba(255,255,255,.06);
            color: #fff;
            outline: none;
            font: inherit;
        }
        .actions {
            display: flex;
            justify-content: space-between;
            gap: 12px;
            margin-top: 22px;
        }
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px 18px;
            border-radius: 12px;
            text-decoration: none;
            border: none;
            cursor: pointer;
            font: inherit;
            font-weight: 700;
        }
        .btn-primary {
            background: linear-gradient(135deg, #66ccff, #3aa9ff);
            color: #fff;
        }
        .btn-outline {
            background: transparent;
            border: 1px solid rgba(255,255,255,.14);
            color: rgba(255,255,255,.84);
        }
        .btn[disabled] {
            opacity: .45;
            cursor: not-allowed;
        }
        .test-result {
            display: none;
            margin-top: 12px;
            padding: 12px 14px;
            border-radius: 12px;
            font-size: .9rem;
        }
        .info-list {
            display: grid;
            gap: 10px;
        }
        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 12px 14px;
            border-radius: 12px;
            background: rgba(255,255,255,.04);
        }
        .muted {
            color: rgba(255,255,255,.52);
        }
        @media (max-width: 720px) {
            .steps,
            .form-row,
            .actions {
                grid-template-columns: 1fr;
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
                    <h1>Beita Blog 安装向导</h1>
            <p>按步骤完成环境检测、数据库配置和站点初始化。</p>
        </div>

        <div class="steps">
            <div class="step <?php echo $step === 1 ? 'active' : ($step > 1 ? 'done' : ''); ?>">1. 环境检测</div>
            <div class="step <?php echo $step === 2 ? 'active' : ($step > 2 ? 'done' : ''); ?>">2. 数据库</div>
            <div class="step <?php echo $step === 3 ? 'active' : ($step > 3 ? 'done' : ''); ?>">3. 站点设置</div>
            <div class="step <?php echo $step === 4 ? 'active done' : ''; ?>">4. 完成</div>
        </div>

        <?php if ($error !== ''): ?>
            <div class="alert alert-error"><?php echo e($error); ?></div>
        <?php endif; ?>
        <?php if ($success !== ''): ?>
            <div class="alert alert-success"><?php echo e($success); ?></div>
        <?php endif; ?>
        <?php if ($hasNewVersion): ?>
            <div class="alert alert-warning">
                检测到新版本 <?php echo e($remoteVersion); ?>，当前安装包版本为 <?php echo e($currentVersion); ?>。你可以先去官网下载新版本，也可以继续安装当前旧版本。
            </div>
        <?php endif; ?>

        <?php if ($step === 1): ?>
            <div class="card">
                <h2>环境检测</h2>
                <ul class="check-list">
                    <?php foreach ($checks as $check): ?>
                        <li>
                            <span><?php echo e($check[0]); ?></span>
                            <span class="status <?php echo $check[1] ? 'pass' : 'fail'; ?>"><?php echo $check[1] ? '通过' : '未通过'; ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <div class="actions">
                    <span class="muted">Beita Blog v<?php echo e($currentVersion); ?> · PHP <?php echo PHP_VERSION; ?></span>
                    <?php if ($allPassed): ?>
                        <a class="btn btn-primary" href="?step=2">下一步 <i class="ri-arrow-right-line"></i></a>
                    <?php else: ?>
                        <button class="btn btn-primary" disabled>请先修复未通过项</button>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($step === 2): ?>
            <div class="card">
                <h2>数据库配置</h2>
                <form id="dbForm" method="post" action="steps.php">
                    <input type="hidden" name="step" value="2">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="db_host">数据库主机</label>
                            <input id="db_host" type="text" name="db_host" value="<?php echo e($installDb['db_host'] ?? 'localhost'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="db_port">端口</label>
                            <input id="db_port" type="text" name="db_port" value="<?php echo e($installDb['db_port'] ?? '3306'); ?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="db_name">数据库名</label>
                        <input id="db_name" type="text" name="db_name" value="<?php echo e($installDb['db_name'] ?? 'glass_blog'); ?>" required>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="db_user">用户名</label>
                            <input id="db_user" type="text" name="db_user" value="<?php echo e($installDb['db_user'] ?? 'root'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="db_pass">密码</label>
                            <input id="db_pass" type="password" name="db_pass" value="<?php echo e($installDb['db_pass'] ?? ''); ?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="db_prefix">表前缀</label>
                        <input id="db_prefix" type="text" name="db_prefix" value="<?php echo e($installDb['db_prefix'] ?? ''); ?>" placeholder="可选，例如 blog_">
                    </div>
                    <button class="btn btn-outline" type="button" onclick="testConnection()">测试连接</button>
                    <div id="testResult" class="test-result"></div>
                    <div class="actions">
                        <a class="btn btn-outline" href="?step=1"><i class="ri-arrow-left-line"></i>上一步</a>
                        <button class="btn btn-primary" type="submit">下一步 <i class="ri-arrow-right-line"></i></button>
                    </div>
                </form>
            </div>
        <?php endif; ?>

        <?php if ($step === 3): ?>
            <div class="card">
                <h2>站点设置</h2>
                <form method="post" action="steps.php">
                    <input type="hidden" name="step" value="3">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="site_title">网站标题</label>
                            <input id="site_title" type="text" name="site_title" value="<?php echo e($installSite['site_title'] ?? 'Beita Blog'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="site_subtitle">副标题</label>
                            <input id="site_subtitle" type="text" name="site_subtitle" value="<?php echo e($installSite['site_subtitle'] ?? '记录生活，分享技术'); ?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="site_description">网站简介</label>
                        <input id="site_description" type="text" name="site_description" value="<?php echo e($installSite['site_description'] ?? ''); ?>">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="site_url">站点 URL</label>
                            <input id="site_url" type="text" name="site_url" value="<?php echo e($installSite['site_url'] ?? $defaultSiteUrl); ?>" required>
                            <small>请填写完整地址，不要以斜杠结尾。</small>
                        </div>
                        <div class="form-group">
                            <label for="theme_color">默认主题色</label>
                            <div style="display:flex;gap:10px;align-items:center;">
                                <input type="color" value="<?php echo e($installSite['theme_color'] ?? '#66CCFF'); ?>" oninput="document.getElementById('theme_color').value=this.value" style="width:60px;padding:4px;">
                                <input id="theme_color" type="text" name="theme_color" value="<?php echo e($installSite['theme_color'] ?? '#66CCFF'); ?>">
                            </div>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="admin_user">管理员用户名</label>
                            <input id="admin_user" type="text" name="admin_user" value="<?php echo e($installSite['admin_user'] ?? 'admin'); ?>" required minlength="3">
                        </div>
                        <div class="form-group">
                            <label for="admin_pass">管理员密码</label>
                            <input id="admin_pass" type="password" name="admin_pass" required minlength="6">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="admin_pass2">确认密码</label>
                        <input id="admin_pass2" type="password" name="admin_pass2" required minlength="6">
                    </div>
                    <div class="actions">
                        <a class="btn btn-outline" href="?step=2"><i class="ri-arrow-left-line"></i>上一步</a>
                        <button class="btn btn-primary" type="submit">开始安装 <i class="ri-install-line"></i></button>
                    </div>
                </form>
            </div>
        <?php endif; ?>

        <?php if ($step === 4): ?>
            <div class="card">
                <h2>运行环境自检</h2>
                <div class="info-list">
                    <div class="info-item"><span class="muted">站点地址</span><strong><?php echo e($installSite['site_url'] ?? ''); ?></strong></div>
                    <div class="info-item"><span class="muted">管理员</span><strong><?php echo e($installSite['admin_user'] ?? 'admin'); ?></strong></div>
                    <div class="info-item"><span class="muted">主题色</span><strong><?php echo e($installSite['theme_color'] ?? '#66CCFF'); ?></strong></div>
                </div>
                <p class="muted" style="margin-top:18px;">安装器会使用当前 Web 运行环境实际检测加密后的核心文件。检测通过后，才会正式写入 <code>install.lock</code> 并开放前后台入口。</p>
                <div id="runtimeProbeResult" class="test-result" style="display:block;margin-top:16px;"><?php echo $runtimeProbePassed ? '已通过运行环境自检，可以完成安装。' : '正在检测加密后的核心文件，请稍候...'; ?></div>
                <?php if (!empty($installFinalizePayload) && is_array($installFinalizePayload)): ?>
                    <form method="post" action="steps.php">
                        <input type="hidden" name="step" value="finalize">
                        <div class="actions" style="margin-top:24px;">
                            <button class="btn btn-outline" id="retryProbeButton" type="button" onclick="runRuntimeProbe()">重新检测</button>
                            <button class="btn btn-primary" id="finalizeInstallButton" type="submit" <?php echo $runtimeProbePassed ? '' : 'disabled'; ?>>完成安装</button>
                        </div>
                    </form>
                <?php else: ?>
                    <div class="actions" style="margin-top:24px;">
                        <a class="btn btn-outline" href="?step=3"><i class="ri-arrow-left-line"></i>返回上一步</a>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function testConnection() {
            var result = document.getElementById('testResult');
            var formData = new FormData(document.getElementById('dbForm'));
            formData.set('step', 'test');

            fetch('steps.php', { method: 'POST', body: formData })
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    result.style.display = 'block';
                    result.textContent = data.message;
                    if (data.success) {
                        result.style.background = 'rgba(16,185,129,.12)';
                        result.style.border = '1px solid rgba(16,185,129,.24)';
                        result.style.color = '#86efac';
                    } else {
                        result.style.background = 'rgba(248,113,113,.12)';
                        result.style.border = '1px solid rgba(248,113,113,.24)';
                        result.style.color = '#fca5a5';
                    }
                })
                .catch(function() {
                    result.style.display = 'block';
                    result.textContent = '测试请求失败，请稍后再试。';
                    result.style.background = 'rgba(248,113,113,.12)';
                    result.style.border = '1px solid rgba(248,113,113,.24)';
                    result.style.color = '#fca5a5';
                });
        }

        function runRuntimeProbe() {
            var result = document.getElementById('runtimeProbeResult');
            var finalizeButton = document.getElementById('finalizeInstallButton');
            var retryButton = document.getElementById('retryProbeButton');

            if (!result) {
                return;
            }

            result.style.display = 'block';
            result.textContent = '正在检测加密后的核心文件，请稍候...';
            result.style.background = 'rgba(102,204,255,.10)';
            result.style.border = '1px solid rgba(102,204,255,.22)';
            result.style.color = '#c6ebff';

            if (finalizeButton) {
                finalizeButton.disabled = true;
            }
            if (retryButton) {
                retryButton.disabled = true;
            }

            fetch('runtime_probe.php', { method: 'GET', cache: 'no-store' })
                .then(function(response) {
                    return response.json();
                })
                .then(function(data) {
                    result.textContent = data.message || '检测完成。';
                    if (data.success) {
                        result.style.background = 'rgba(16,185,129,.12)';
                        result.style.border = '1px solid rgba(16,185,129,.24)';
                        result.style.color = '#86efac';
                        if (finalizeButton) {
                            finalizeButton.disabled = false;
                        }
                    } else {
                        result.style.background = 'rgba(248,113,113,.12)';
                        result.style.border = '1px solid rgba(248,113,113,.24)';
                        result.style.color = '#fca5a5';
                    }
                })
                .catch(function() {
                    result.textContent = '检测失败：当前 Web 运行环境无法正常加载加密后的核心文件，请检查 SG16 / SourceGuardian Loader、PHP 版本和 OPcache。';
                    result.style.background = 'rgba(248,113,113,.12)';
                    result.style.border = '1px solid rgba(248,113,113,.24)';
                    result.style.color = '#fca5a5';
                })
                .finally(function() {
                    if (retryButton) {
                        retryButton.disabled = false;
                    }
                });
        }

        <?php if ($step === 4 && !$runtimeProbePassed && !empty($installFinalizePayload) && is_array($installFinalizePayload)): ?>
        runRuntimeProbe();
        <?php endif; ?>
    </script>
</body>
</html>
