<?php
session_start();

if (file_exists('../config.php')) {
    header('Content-Type: text/html; charset=UTF-8');
    
    // 清除安装时遗留的session数据，防止绕过登录
    unset($_SESSION['admin_user']);
    unset($_SESSION['admin_pass']);
    unset($_SESSION['db_host']);
    unset($_SESSION['db_port']);
    unset($_SESSION['db_user']);
    unset($_SESSION['db_pwd']);
    unset($_SESSION['db_name']);
    unset($_SESSION['site_url']);
    unset($_SESSION['import_count']);
    unset($_SESSION['import_errors']);
    
    exit('系统已经安装，如需重新安装请删除 config.php 文件');
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $step = isset($_POST['step']) ? intval($_POST['step']) : 1;
}

if ($step == 2 && $_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['db_host'] = $_POST['db_host'];
    $_SESSION['db_port'] = $_POST['db_port'];
    $_SESSION['db_user'] = $_POST['db_user'];
    $_SESSION['db_pwd'] = $_POST['db_pwd'];
    $_SESSION['db_name'] = $_POST['db_name'];
    
    try {
        $conn = new mysqli($_SESSION['db_host'], $_SESSION['db_user'], $_SESSION['db_pwd'], '', $_SESSION['db_port']);
        if ($conn->connect_error) {
            $error = '数据库连接失败: ' . $conn->connect_error;
        } else {
            $conn->select_db($_SESSION['db_name']);
            $step = 3;
        }
    } catch (Exception $e) {
        $error = '数据库连接失败: ' . $e->getMessage();
    }
}

if ($step == 4 && $_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['admin_user'] = $_POST['admin_user'];
    $_SESSION['admin_pass'] = md5($_POST['admin_pass']);
    $_SESSION['site_url'] = $_POST['site_url'];
    
    try {
        $conn = new mysqli($_SESSION['db_host'], $_SESSION['db_user'], $_SESSION['db_pwd'], $_SESSION['db_name'], $_SESSION['db_port']);
        
        $sql_dir = __DIR__ . '/sql/';
        $order_file = $sql_dir . 'tables_order.txt';
        $import_errors = array();
        $import_count = 0;
        
        if (file_exists($order_file)) {
            $tables = file($order_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            
            foreach ($tables as $table) {
                $sql_file = $sql_dir . $table . '.sql';
                if (file_exists($sql_file)) {
                    $sql_content = file_get_contents($sql_file);
                    
                    if ($conn->multi_query($sql_content)) {
                        do {
                            if ($result = $conn->store_result()) {
                                $result->free();
                            }
                        } while ($conn->more_results() && $conn->next_result());
                        $import_count++;
                    } else {
                        $import_errors[] = "表 {$table} 导入失败: " . $conn->error;
                    }
                }
            }
        } else {
            $error = 'SQL文件目录不存在，请检查 install/sql/ 目录';
        }
        
        if (empty($error)) {
            $conn->query("UPDATE `config` SET `user`='{$_SESSION['admin_user']}',`pwd`='{$_SESSION['admin_pass']}' WHERE `id`=1");
            
            $config_content = "<?php\nreturn array(\n";
            $config_content .= "    'host' => '{$_SESSION['db_host']}',\n";
            $config_content .= "    'port' => {$_SESSION['db_port']},\n";
            $config_content .= "    'user' => '{$_SESSION['db_user']}',\n";
            $config_content .= "    'pwd' => '{$_SESSION['db_pwd']}',\n";
            $config_content .= "    'dbname' => '{$_SESSION['db_name']}'\n";
            $config_content .= ");\n?>";
            
            if (@file_put_contents('../config.php', $config_content) === false) {
                $error = '写入 config.php 失败，请检查根目录写入权限或手动创建 config.php 文件，内容如下：<pre>' . htmlspecialchars($config_content) . '</pre>';
            } else {
                $_SESSION['import_count'] = $import_count;
                $_SESSION['import_errors'] = $import_errors;
                $step = 5;
            }
        }
        
        $conn->close();
    } catch (Exception $e) {
        $error = '安装失败: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统安装 - MLEOE宝塔系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
            line-height: 1.5;
            font-size: 13px;
            min-height: 100vh;
        }
        
        /* 顶部导航 */
        .header {
            background: #fff;
            border-bottom: 1px solid #e8eaed;
            padding: 0 24px;
            height: 64px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }
        
        .header-brand {
            display: flex;
            align-items: center;
            font-size: 18px;
            font-weight: 600;
            color: #1a73e8;
        }
        
        .header-brand i {
            margin-right: 10px;
            font-size: 24px;
        }
        
        .header-info {
            color: #5f6368;
            font-size: 13px;
        }
        
        /* 主容器 */
        .main-container {
            padding-top: 64px;
            display: flex;
            min-height: 100vh;
        }
        
        /* 功能介绍区域 - 与页面协调 */
        .features-intro {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid #e8eaed;
        }
        
        .features-intro h3 {
            font-size: 16px;
            font-weight: 600;
            color: #202124;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .features-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;
        }
        
        .feature-card {
            background: #fff;
            border-radius: 8px;
            padding: 16px;
            border: 1px solid #e8eaed;
        }
        
        .feature-card h4 {
            font-size: 13px;
            font-weight: 600;
            color: #1a73e8;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
        }
        
        .feature-card h4 i {
            margin-right: 8px;
            width: 16px;
        }
        
        .feature-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }
        
        .feature-tag {
            background: #e8f0fe;
            color: #1967d2;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
        }
        
        /* 右侧安装区域 */
        .install-content {
            flex: 1;
            padding: 40px;
            display: flex;
            justify-content: center;
            align-items: flex-start;
        }
        
        .install-box {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 1px 2px 0 rgba(60,64,67,0.3), 0 1px 3px 1px rgba(60,64,67,0.15);
            width: 100%;
            max-width: 600px;
            padding: 32px;
        }
        
        .install-header {
            text-align: center;
            margin-bottom: 32px;
        }
        
        .install-header h2 {
            color: #202124;
            font-weight: 600;
            font-size: 20px;
            margin-bottom: 8px;
        }
        
        .install-header p {
            color: #5f6368;
            font-size: 13px;
        }
        
        /* 步骤指示器 */
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 32px;
            padding: 0 20px;
        }
        
        .step-item {
            text-align: center;
            flex: 1;
            position: relative;
        }
        
        .step-item:not(:last-child):after {
            content: '';
            position: absolute;
            top: 16px;
            left: 60%;
            width: 80%;
            height: 2px;
            background: #e8eaed;
        }
        
        .step-item.active:not(:last-child):after,
        .step-item.completed:not(:last-child):after {
            background: #1a73e8;
        }
        
        .step-circle {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #f1f3f4;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 8px;
            font-weight: 600;
            font-size: 13px;
            color: #5f6368;
            position: relative;
            z-index: 1;
        }
        
        .step-item.active .step-circle {
            background: #1a73e8;
            color: #fff;
        }
        
        .step-item.completed .step-circle {
            background: #188038;
            color: #fff;
        }
        
        .step-label {
            font-size: 12px;
            color: #5f6368;
        }
        
        .step-item.active .step-label {
            color: #1a73e8;
            font-weight: 500;
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            font-weight: 500;
            color: #202124;
            font-size: 13px;
            margin-bottom: 6px;
        }
        
        .form-control {
            border: 1px solid #dadce0;
            border-radius: 4px;
            padding: 10px 12px;
            font-size: 13px;
            transition: all 0.2s;
        }
        
        .form-control:focus {
            border-color: #1a73e8;
            box-shadow: 0 0 0 2px rgba(26,115,232,0.1);
        }
        
        .btn-install {
            background: #1a73e8;
            border: none;
            padding: 12px 24px;
            font-size: 14px;
            font-weight: 500;
            border-radius: 4px;
            transition: all 0.2s;
        }
        
        .btn-install:hover {
            background: #1557b0;
            box-shadow: 0 1px 2px 0 rgba(60,64,67,0.3), 0 1px 3px 1px rgba(60,64,67,0.15);
        }
        
        /* 提示框 */
        .alert {
            border-radius: 4px;
            padding: 12px 16px;
            font-size: 13px;
            margin-bottom: 20px;
        }
        
        .alert-info {
            background: #e8f0fe;
            color: #1967d2;
            border: 1px solid #c4d7f5;
        }
        
        .alert-danger {
            background: #fce8e6;
            color: #c5221f;
            border: 1px solid #fad2cf;
        }
        
        .alert-success {
            background: #e6f4ea;
            color: #137333;
            border: 1px solid #ceead6;
        }
        
        /* 成功页面 */
        .success-icon {
            font-size: 64px;
            color: #188038;
            text-align: center;
            margin-bottom: 16px;
        }
        
        /* 系统要求列表 */
        .requirements-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .requirements-list li {
            padding: 8px 0;
            color: #5f6368;
            font-size: 13px;
            display: flex;
            align-items: center;
        }
        
        .requirements-list li i {
            margin-right: 8px;
            color: #188038;
        }
        
        /* 进度条 */
        .progress {
            height: 4px;
            background: #e8eaed;
            border-radius: 2px;
        }
        
        .progress-bar {
            background: #1a73e8;
        }
        
        /* 响应式 */
        @media (max-width: 992px) {
            .features-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航 -->
    <div class="header">
        <div class="header-brand">
            <i class="fas fa-server"></i>
            <span>宝塔主机管理系统</span>
        </div>
        <div class="header-info">
            <i class="fas fa-code-branch"></i> 安装向导
        </div>
    </div>
    
    <div class="main-container">
        <!-- 安装区域 -->
        <div class="install-content">
            <div class="install-box">
                <div class="install-header">
                    <h2>系统安装向导</h2>
                    <p>请按照步骤完成系统安装配置</p>
                </div>
                
                <!-- 步骤指示器 -->
                <div class="step-indicator">
                    <div class="step-item <?php echo $step >= 1 ? 'active' : ''; ?>">
                        <div class="step-circle <?php echo $step > 1 ? 'completed' : ''; ?>">1</div>
                        <div class="step-label">环境检查</div>
                    </div>
                    <div class="step-item <?php echo $step >= 2 ? 'active' : ''; ?>">
                        <div class="step-circle <?php echo $step > 2 ? 'completed' : ''; ?>">2</div>
                        <div class="step-label">数据库配置</div>
                    </div>
                    <div class="step-item <?php echo $step >= 3 ? 'active' : ''; ?>">
                        <div class="step-circle <?php echo $step > 3 ? 'completed' : ''; ?>">3</div>
                        <div class="step-label">管理员设置</div>
                    </div>
                    <div class="step-item <?php echo $step >= 5 ? 'active' : ''; ?>">
                        <div class="step-circle <?php echo $step >= 5 ? 'completed' : ''; ?>">4</div>
                        <div class="step-label">安装完成</div>
                    </div>
                </div>
                
                <?php if ($step == 1): ?>
                <!-- 步骤1：环境检查 -->
                <div class="text-center">
                    <h4 style="color: #202124; margin-bottom: 16px;">欢迎使用MLEOE宝塔系统</h4>
                    <p style="color: #5f6368; margin-bottom: 24px;">本系统将帮助您快速搭建虚拟主机管理平台</p>
                </div>
                
                <!-- 功能介绍 -->
                <div class="features-intro">
                    <h3><i class="fas fa-star"></i> 系统功能亮点</h3>
                    <div class="features-grid">
                        <div class="feature-card">
                            <h4><i class="fas fa-user"></i> 用户前台</h4>
                            <div class="feature-tags">
                                <span class="feature-tag">虚拟空间管理</span>
                                <span class="feature-tag">域名绑定</span>
                                <span class="feature-tag">PHP切换</span>
                                <span class="feature-tag">文件管理</span>
                                <span class="feature-tag">数据库</span>
                                <span class="feature-tag">SSL部署</span>
                                <span class="feature-tag">流量统计</span>
                                <span class="feature-tag">程序安装</span>
                            </div>
                        </div>
                        <div class="feature-card">
                            <h4><i class="fas fa-cog"></i> 后台管理</h4>
                            <div class="feature-tags">
                                <span class="feature-tag">用户管理</span>
                                <span class="feature-tag">空间管理</span>
                                <span class="feature-tag">程序资源</span>
                                <span class="feature-tag">系统同步</span>
                                <span class="feature-tag">API密钥</span>
                                <span class="feature-tag">自动停止</span>
                                <span class="feature-tag">日志记录</span>
                            </div>
                        </div>
                        <div class="feature-card">
                            <h4><i class="fas fa-shield-alt"></i> 安全防护</h4>
                            <div class="feature-tags">
                                <span class="feature-tag">CSRF防护</span>
                                <span class="feature-tag">XSS过滤</span>
                                <span class="feature-tag">SQL注入防护</span>
                                <span class="feature-tag">文件上传限制</span>
                                <span class="feature-tag">危险文件检测</span>
                            </div>
                        </div>
                        <div class="feature-card">
                            <h4><i class="fas fa-plug"></i> 宝塔集成</h4>
                            <div class="feature-tags">
                                <span class="feature-tag">网站创建</span>
                                <span class="feature-tag">数据库创建</span>
                                <span class="feature-tag">FTP管理</span>
                                <span class="feature-tag">SSL申请</span>
                                <span class="feature-tag">流量监控</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="alert alert-info">
                    <strong><i class="fas fa-check-circle"></i> 系统要求</strong>
                    <ul class="requirements-list mt-2">
                        <?php
                        $php_version = PHP_VERSION;
                        $php_major = intval(substr($php_version, 0, 1));
                        $php_minor = intval(substr($php_version, 2, 1));
                        $php_ok = ($php_major == 7 && $php_minor == 4);
                        $php_class = $php_ok ? 'text-success' : 'text-danger';
                        $php_icon = $php_ok ? 'fa-check' : 'fa-exclamation-triangle';
                        ?>
                        <li class="<?php echo $php_class; ?>"><i class="fas <?php echo $php_icon; ?>"></i> PHP版本 7.4.x（当前: <?php echo $php_version; ?>）<?php if(!$php_ok): ?> - 请切换到PHP 7.4<?php endif; ?></li>
                        <li><i class="fas fa-check"></i> MySQL版本 >= 5.0</li>
                        <li><i class="fas fa-check"></i> 支持mysqli扩展</li>
                        <li><i class="fas fa-check"></i> 目录具有写入权限</li>
                        <li><i class="fas fa-check"></i> 支持curl扩展</li>
                        <li><i class="fas fa-check"></i> 支持zip扩展</li>
                    </ul>
                </div>
                
                <?php if ($php_ok): ?>
                <a href="?step=2" class="btn btn-primary btn-install btn-block">
                    <i class="fas fa-arrow-right"></i> 开始安装
                </a>
                <?php else: ?>
                <div class="alert alert-warning">
                    <strong><i class="fas fa-exclamation-triangle"></i> PHP版本不兼容</strong>
                    <p class="mb-0 mt-2">当前PHP版本为 <strong><?php echo $php_version; ?></strong>，系统要求PHP 7.4.x</p>
                    <p class="mb-0">请在宝塔面板中切换PHP版本后刷新此页面</p>
                </div>
                <button class="btn btn-secondary btn-install btn-block" disabled>
                    <i class="fas fa-arrow-right"></i> 开始安装
                </button>
                <?php endif; ?>
                
                <?php elseif ($step == 2): ?>
                <!-- 步骤2：数据库配置 -->
                <h4 style="color: #202124; margin-bottom: 20px;"><i class="fas fa-database"></i> 数据库配置</h4>
                
                <?php if (isset($error)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
                </div>
                <?php endif; ?>
                
                <form method="post">
                    <input type="hidden" name="step" value="2">
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group">
                                <label for="db_host">数据库服务器</label>
                                <input type="text" class="form-control" id="db_host" name="db_host" value="localhost" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="db_port">端口</label>
                                <input type="text" class="form-control" id="db_port" name="db_port" value="3306" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="db_name">数据库名称</label>
                        <input type="text" class="form-control" id="db_name" name="db_name" placeholder="请输入数据库名称" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="db_user">数据库用户名</label>
                        <input type="text" class="form-control" id="db_user" name="db_user" placeholder="请输入数据库用户名" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="db_pwd">数据库密码</label>
                        <input type="password" class="form-control" id="db_pwd" name="db_pwd" placeholder="请输入数据库密码">
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <a href="?step=1" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> 上一步
                        </a>
                        <button type="submit" class="btn btn-primary btn-install">
                            <i class="fas fa-arrow-right"></i> 下一步
                        </button>
                    </div>
                </form>
                
                <?php elseif ($step == 3): ?>
                <!-- 步骤3：管理员设置 -->
                <h4 style="color: #202124; margin-bottom: 20px;"><i class="fas fa-user-shield"></i> 管理员设置</h4>
                
                <form method="post">
                    <input type="hidden" name="step" value="4">
                    
                    <div class="form-group">
                        <label for="admin_user">管理员账号</label>
                        <input type="text" class="form-control" id="admin_user" name="admin_user" value="admin" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_pass">管理员密码</label>
                        <input type="password" class="form-control" id="admin_pass" name="admin_pass" placeholder="请设置管理员密码" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="site_url">网站地址</label>
                        <input type="text" class="form-control" id="site_url" name="site_url" value="http://<?php echo $_SERVER['HTTP_HOST']; ?>" required>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> 安装完成后，请使用上述账号密码登录后台管理系统
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <a href="?step=2" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> 上一步
                        </a>
                        <button type="submit" class="btn btn-primary btn-install">
                            <i class="fas fa-check"></i> 开始安装
                        </button>
                    </div>
                </form>
                
                <?php elseif ($step == 4): ?>
                <!-- 步骤4：安装中 -->
                <div class="text-center">
                    <h4 style="color: #202124; margin-bottom: 24px;">正在安装系统...</h4>
                    <div class="progress mb-3">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 100%"></div>
                    </div>
                    <p style="color: #5f6368;">请稍候，正在初始化数据库和配置文件...</p>
                </div>
                <script>
                setTimeout(function() {
                    location.href = '?step=5';
                }, 2000);
                </script>
                
                <?php elseif ($step == 5): ?>
                <?php
                // 安装完成后清除session，强制重新登录
                $admin_user_display = isset($_SESSION['admin_user']) ? $_SESSION['admin_user'] : 'admin';
                $import_count_display = isset($_SESSION['import_count']) ? $_SESSION['import_count'] : 0;
                $import_errors_display = isset($_SESSION['import_errors']) ? $_SESSION['import_errors'] : array();
                unset($_SESSION['admin_user']);
                unset($_SESSION['admin_pass']);
                unset($_SESSION['db_host']);
                unset($_SESSION['db_port']);
                unset($_SESSION['db_user']);
                unset($_SESSION['db_pwd']);
                unset($_SESSION['db_name']);
                unset($_SESSION['site_url']);
                unset($_SESSION['import_count']);
                unset($_SESSION['import_errors']);
                session_destroy();
                ?>
                <!-- 步骤5：安装完成 -->
                <div class="text-center">
                    <div class="success-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h4 style="color: #202124; margin-bottom: 8px;">安装完成！</h4>
                    <p style="color: #5f6368; margin-bottom: 24px;">系统已成功安装，现在可以开始使用了</p>
                    
                    <div class="alert alert-success text-left">
                        <strong><i class="fas fa-database"></i> 数据库导入：</strong>成功导入 <?php echo $import_count_display; ?> 个表<br>
                        <strong><i class="fas fa-user"></i> 管理员账号：</strong><?php echo $admin_user_display; ?><br>
                        <strong><i class="fas fa-lock"></i> 管理员密码：</strong>您设置的密码<br>
                        <strong><i class="fas fa-link"></i> 后台地址：</strong><a href="../admin/" target="_blank">../admin/</a>
                    </div>
                    
                    <?php if (!empty($import_errors_display)): ?>
                    <div class="alert alert-warning text-left" style="font-size: 12px;">
                        <strong><i class="fas fa-exclamation-triangle"></i> 部分警告：</strong>
                        <ul style="margin: 8px 0 0 0; padding-left: 20px;">
                            <?php foreach ($import_errors_display as $err): ?>
                            <li><?php echo htmlspecialchars($err); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>
                    
                    <div class="d-grid gap-2">
                        <a href="../admin/" class="btn btn-primary btn-install btn-block">
                            <i class="fas fa-sign-in-alt"></i> 进入后台管理
                        </a>
                        <a href="../" class="btn btn-outline-secondary btn-block mt-2">
                            <i class="fas fa-home"></i> 访问前台首页
                        </a>
                    </div>
                    
                    <div class="alert alert-warning mt-3" style="font-size: 12px;">
                        <i class="fas fa-exclamation-triangle"></i> <strong>安全提示：</strong>为了系统安全，建议安装完成后删除 install 目录
                    </div>
                </div>
                
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
</body>
</html>
