<?php
/**
 * 论坛安装程序
 */

session_start();

// 检查是否已安装
if (file_exists(__DIR__ . '/../config/install.lock')) {
    die('论坛已经安装过了！如需重新安装，请删除 config/install.lock 文件。');
}

$step = isset($_GET['step']) ? intval($_GET['step']) : 1;
$error = '';
$success = '';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    switch ($step) {
        case 1:
            // 保存数据库配置到 session
            $_SESSION['db_host'] = $_POST['db_host'] ?? 'localhost';
            $_SESSION['db_user'] = $_POST['db_user'] ?? 'root';
            $_SESSION['db_pass'] = $_POST['db_pass'] ?? '';
            $_SESSION['db_name'] = $_POST['db_name'] ?? 'forum';
            $_SESSION['site_url'] = rtrim($_POST['site_url'] ?? '', '/');
            header('Location: ?step=2');
            exit;

        case 2:
            // 测试数据库连接
            try {
                $dsn = "mysql:host={$_SESSION['db_host']};charset=utf8mb4";
                $pdo = new PDO($dsn, $_SESSION['db_user'], $_SESSION['db_pass']);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // 创建数据库
                $pdo->exec("CREATE DATABASE IF NOT EXISTS {$_SESSION['db_name']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
                $pdo->exec("USE {$_SESSION['db_name']}");

                // 执行 SQL 文件
                $sql = file_get_contents(__DIR__ . '/database.sql');
                $pdo->exec($sql);

                header('Location: ?step=3');
                exit;
            } catch (PDOException $e) {
                $error = '数据库连接失败: ' . $e->getMessage();
            }
            break;

        case 3:
            // 创建管理员账号
            $username = trim($_POST['admin_username'] ?? '');
            $email = trim($_POST['admin_email'] ?? '');
            $password = $_POST['admin_password'] ?? '';
            $password_confirm = $_POST['admin_password_confirm'] ?? '';

            // 验证
            if (empty($username) || strlen($username) < 3 || strlen($username) > 20) {
                $error = '用户名长度必须在 3-20 个字符之间';
            } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
                $error = '用户名只能包含字母、数字和下划线';
            } elseif (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = '请输入有效的邮箱地址';
            } elseif (empty($password) || strlen($password) < 6) {
                $error = '密码长度至少为 6 位';
            } elseif ($password !== $password_confirm) {
                $error = '两次输入的密码不一致';
            } else {
                try {
                    $dsn = "mysql:host={$_SESSION['db_host']};dbname={$_SESSION['db_name']};charset=utf8mb4";
                    $pdo = new PDO($dsn, $_SESSION['db_user'], $_SESSION['db_pass']);
                    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    // 检查用户名是否已存在
                    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
                    $stmt->execute([$username]);
                    if ($stmt->fetch()) {
                        $error = '用户名已存在';
                    } else {
                        // 创建超级管理员账号 (role = 2)
                        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role, status) VALUES (?, ?, ?, 2, 1)");
                        $stmt->execute([$username, $email, $hashedPassword]);

                        // 处理 site_url，移除末尾的反斜杠
                        $siteUrl = rtrim($_SESSION['site_url'], '\\/');
                        
                        // 生成配置文件
                        $configContent = "<?php\n";
                        $configContent .= "/**\n";
                        $configContent .= " * 论坛配置文件\n";
                        $configContent .= " * 由安装程序自动生成\n";
                        $configContent .= " */\n\n";
                        $configContent .= "// 数据库配置\n";
                        $configContent .= "define('DB_HOST', '{$_SESSION['db_host']}');\n";
                        $configContent .= "define('DB_USER', '{$_SESSION['db_user']}');\n";
                        $configContent .= "define('DB_PASS', '{$_SESSION['db_pass']}');\n";
                        $configContent .= "define('DB_NAME', '{$_SESSION['db_name']}');\n";
                        $configContent .= "define('DB_CHARSET', 'utf8mb4');\n\n";
                        $configContent .= "// 网站配置\n";
                        $configContent .= "define('SITE_URL', '{$siteUrl}');\n";
                        $configContent .= "define('SITE_NAME', 'PHP论坛');\n\n";
                        $configContent .= "// 时区设置\n";
                        $configContent .= "date_default_timezone_set('Asia/Shanghai');\n\n";
                        $configContent .= "// 开启错误显示（开发环境）\n";
                        $configContent .= "error_reporting(E_ALL);\n";
                        $configContent .= "ini_set('display_errors', 1);\n\n";
                        $configContent .= "// 会话启动\n";
                        $configContent .= "if (session_status() === PHP_SESSION_NONE) {\n";
                        $configContent .= "    session_start();\n";
                        $configContent .= "}\n";

                        file_put_contents(__DIR__ . '/../config/config.php', $configContent);

                        // 创建安装锁文件
                        file_put_contents(__DIR__ . '/../config/install.lock', date('Y-m-d H:i:s'));

                        // 清除 session
                        session_destroy();

                        header('Location: ?step=4');
                        exit;
                    }
                } catch (PDOException $e) {
                    $error = '创建管理员失败: ' . $e->getMessage();
                }
            }
            break;
    }
}

// 检查环境
function checkEnvironment() {
    $checks = [];

    // PHP 版本
    $checks['php_version'] = [
        'name' => 'PHP 版本 >= 7.4',
        'pass' => version_compare(PHP_VERSION, '7.4.0', '>='),
        'current' => PHP_VERSION
    ];

    // PDO 扩展
    $checks['pdo'] = [
        'name' => 'PDO 扩展',
        'pass' => extension_loaded('pdo'),
        'current' => extension_loaded('pdo') ? '已安装' : '未安装'
    ];

    // PDO MySQL
    $checks['pdo_mysql'] = [
        'name' => 'PDO MySQL 扩展',
        'pass' => extension_loaded('pdo_mysql'),
        'current' => extension_loaded('pdo_mysql') ? '已安装' : '未安装'
    ];

    // mbstring 扩展（用于中文处理）
    $checks['mbstring'] = [
        'name' => 'mbstring 扩展（中文支持）',
        'pass' => extension_loaded('mbstring'),
        'current' => extension_loaded('mbstring') ? '已安装' : '未安装'
    ];

    // GD 扩展（用于图片处理）
    $checks['gd'] = [
        'name' => 'GD 扩展（图片处理）',
        'pass' => extension_loaded('gd'),
        'current' => extension_loaded('gd') ? '已安装' : '未安装'
    ];

    // JSON 扩展
    $checks['json'] = [
        'name' => 'JSON 扩展',
        'pass' => extension_loaded('json'),
        'current' => extension_loaded('json') ? '已安装' : '未安装'
    ];

    // 文件写入权限
    $checks['config_writable'] = [
        'name' => 'config 目录可写',
        'pass' => is_writable(__DIR__ . '/../config'),
        'current' => is_writable(__DIR__ . '/../config') ? '可写' : '不可写'
    ];

    // uploads 目录可写
    $checks['uploads_writable'] = [
        'name' => 'uploads 目录可写',
        'pass' => is_writable(__DIR__ . '/../uploads'),
        'current' => is_writable(__DIR__ . '/../uploads') ? '可写' : '不可写'
    ];

    // Session
    $checks['session'] = [
        'name' => 'Session 支持',
        'pass' => function_exists('session_start'),
        'current' => function_exists('session_start') ? '支持' : '不支持'
    ];

    return $checks;
}

$checks = checkEnvironment();
$allPassed = true;
foreach ($checks as $check) {
    if (!$check['pass']) {
        $allPassed = false;
        break;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP 论坛安装程序</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .install-container {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 600px;
            padding: 40px;
        }
        .install-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .install-header h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
        }
        .install-header p {
            color: #666;
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        .step {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 10px;
            font-weight: bold;
            color: #666;
        }
        .step.active {
            background: #4CAF50;
            color: #fff;
        }
        .step.completed {
            background: #81C784;
            color: #fff;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        .form-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        .form-group input:focus {
            outline: none;
            border-color: #4CAF50;
        }
        .form-group small {
            display: block;
            margin-top: 5px;
            color: #666;
        }
        .btn {
            display: inline-block;
            padding: 12px 30px;
            background: #4CAF50;
            color: #fff;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
            text-decoration: none;
        }
        .btn:hover {
            background: #45a049;
        }
        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .btn-block {
            width: 100%;
        }
        .alert {
            padding: 12px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .alert-error {
            background: #ffebee;
            color: #c62828;
            border: 1px solid #ef9a9a;
        }
        .alert-success {
            background: #e8f5e9;
            color: #2e7d32;
            border: 1px solid #a5d6a7;
        }
        .check-list {
            list-style: none;
        }
        .check-list li {
            padding: 12px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .check-list li:last-child {
            border-bottom: none;
        }
        .check-status {
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 12px;
        }
        .check-status.pass {
            background: #e8f5e9;
            color: #2e7d32;
        }
        .check-status.fail {
            background: #ffebee;
            color: #c62828;
        }
        .success-icon {
            font-size: 60px;
            color: #4CAF50;
            text-align: center;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="install-header">
            <h1>🚀 PHP 论坛安装</h1>
            <p>简单、快速、优雅的论坛系统</p>
        </div>

        <div class="step-indicator">
            <div class="step <?php echo $step >= 1 ? ($step > 1 ? 'completed' : 'active') : ''; ?>">1</div>
            <div class="step <?php echo $step >= 2 ? ($step > 2 ? 'completed' : 'active') : ''; ?>">2</div>
            <div class="step <?php echo $step >= 3 ? ($step > 3 ? 'completed' : 'active') : ''; ?>">3</div>
            <div class="step <?php echo $step >= 4 ? 'completed' : ''; ?>">4</div>
        </div>

        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <?php if ($step == 1): ?>
            <!-- 步骤 1: 环境检测和数据库配置 -->
            <h3 style="margin-bottom: 20px;">环境检测</h3>
            <ul class="check-list" style="margin-bottom: 30px;">
                <?php foreach ($checks as $check): ?>
                    <li>
                        <span><?php echo $check['name']; ?></span>
                        <span class="check-status <?php echo $check['pass'] ? 'pass' : 'fail'; ?>">
                            <?php echo $check['pass'] ? '✓ 通过' : '✗ ' . $check['current']; ?>
                        </span>
                    </li>
                <?php endforeach; ?>
            </ul>

            <?php if ($allPassed): ?>
                <h3 style="margin-bottom: 20px;">数据库配置</h3>
                <form method="POST" action="?step=1">
                    <div class="form-group">
                        <label>数据库主机</label>
                        <input type="text" name="db_host" value="<?php echo $_SESSION['db_host'] ?? 'localhost'; ?>" required>
                        <small>通常是 localhost 或 127.0.0.1</small>
                    </div>
                    <div class="form-group">
                        <label>数据库用户名</label>
                        <input type="text" name="db_user" value="<?php echo $_SESSION['db_user'] ?? 'root'; ?>" required>
                    </div>
                    <div class="form-group">
                        <label>数据库密码</label>
                        <input type="password" name="db_pass" value="<?php echo $_SESSION['db_pass'] ?? ''; ?>">
                    </div>
                    <div class="form-group">
                        <label>数据库名称</label>
                        <input type="text" name="db_name" value="<?php echo $_SESSION['db_name'] ?? 'forum'; ?>" required>
                        <small>如果不存在会自动创建</small>
                    </div>
                    <div class="form-group">
                        <label>网站地址</label>
                        <input type="url" name="site_url" value="<?php echo $_SESSION['site_url'] ?? 'http://' . $_SERVER['HTTP_HOST'] . dirname(dirname($_SERVER['PHP_SELF'])); ?>" required>
                        <small>例如: http://localhost/forum</small>
                    </div>
                    <button type="submit" class="btn btn-block">下一步</button>
                </form>
            <?php else: ?>
                <div class="alert alert-error" style="margin-top: 20px;">
                    环境检测未通过，请修复上述问题后刷新页面重试。
                </div>
            <?php endif; ?>

        <?php elseif ($step == 2): ?>
            <!-- 步骤 2: 数据库安装 -->
            <h3 style="margin-bottom: 20px;">安装数据库</h3>
            <p style="margin-bottom: 20px; color: #666;">
                即将在数据库 <strong><?php echo htmlspecialchars($_SESSION['db_name']); ?></strong> 中创建数据表。<br>
                请确认数据库配置正确后点击安装。
            </p>
            <form method="POST" action="?step=2">
                <button type="submit" class="btn btn-block">开始安装</button>
            </form>
            <p style="margin-top: 15px; text-align: center;">
                <a href="?step=1" style="color: #666;">返回上一步</a>
            </p>

        <?php elseif ($step == 3): ?>
            <!-- 步骤 3: 创建管理员 -->
            <h3 style="margin-bottom: 20px;">创建管理员账号</h3>
            <form method="POST" action="?step=3">
                <div class="form-group">
                    <label>用户名</label>
                    <input type="text" name="admin_username" required placeholder="3-20位字母数字下划线">
                </div>
                <div class="form-group">
                    <label>邮箱</label>
                    <input type="email" name="admin_email" required placeholder="admin@example.com">
                </div>
                <div class="form-group">
                    <label>密码</label>
                    <input type="password" name="admin_password" required placeholder="至少6位">
                </div>
                <div class="form-group">
                    <label>确认密码</label>
                    <input type="password" name="admin_password_confirm" required>
                </div>
                <button type="submit" class="btn btn-block">完成安装</button>
            </form>

        <?php elseif ($step == 4): ?>
            <!-- 步骤 4: 安装完成 -->
            <meta http-equiv="refresh" content="3;url=../index.php">
            <div class="success-icon">✓</div>
            <h3 style="text-align: center; margin-bottom: 20px;">安装成功！</h3>
            <p style="text-align: center; color: #666; margin-bottom: 30px;">
                您的论坛已经安装完成，3秒后自动跳转到首页...
            </p>
            <div style="text-align: center;">
                <a href="../index.php" class="btn">立即访问论坛首页</a>
                <a href="../login.php" class="btn" style="margin-left: 10px; background: #2196F3;">登录</a>
            </div>
            <p style="margin-top: 30px; padding: 15px; background: #fff3cd; border-radius: 4px; color: #856404; font-size: 14px;">
                <strong>安全提示：</strong>建议删除 install 目录以防止重复安装。
            </p>
        <?php endif; ?>
    </div>
</body>
</html>
