<?php

if (version_compare(PHP_VERSION, '8.0.0', '<') || version_compare(PHP_VERSION, '8.5.0', '>=')) {
    die('当前PHP版本为 ' . PHP_VERSION . '，EnovelCms 1.5 要求 PHP 8.0 ~ 8.4，请升级或切换PHP版本后重新安装');
}

if (!extension_loaded('mbstring')) {
    die('缺少 mbstring 扩展，请安装并启用 mbstring 扩展后重新安装');
}

$lockFile = __DIR__ . '/data/install.lock';
if (file_exists($lockFile)) {
    header('Location: index.php');
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 1) {
        if (!isset($_POST['agree'])) {
            $error = '请阅读并同意用户协议后才能继续安装';
        } else {
            $db_host = addslashes(trim($_POST['db_host'] ?? ''));
            $db_name = addslashes(trim($_POST['db_name'] ?? ''));
            $db_user = addslashes(trim($_POST['db_user'] ?? ''));
            $db_pass = addslashes($_POST['db_pass'] ?? '');
            $site_name = addslashes(trim($_POST['site_name'] ?? ''));
            $admin_user = addslashes(trim($_POST['admin_user'] ?? ''));
            $admin_pass = addslashes($_POST['admin_pass'] ?? '');

            if (empty($db_host) || empty($db_name) || empty($db_user)) {
                $error = '请填写数据库主机、数据库名和用户名';
            } elseif (strlen($admin_user) < 3) {
                $error = '管理员用户名至少3个字符';
            } elseif (strlen($admin_pass) < 6) {
                $error = '管理员密码至少6个字符';
            } else {
                $testConn = new mysqli($db_host, $db_user, $db_pass);
                if ($testConn->connect_error) {
                    $error = '数据库连接失败：' . $testConn->connect_error;
                } else {
                    if (!$testConn->select_db($db_name)) {
                        $sql = "CREATE DATABASE IF NOT EXISTS `$db_name` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci";
                        if (!$testConn->query($sql)) {
                            $error = '创建数据库失败：' . $testConn->error;
                        } else {
                            $testConn->select_db($db_name);
                        }
                    }
                    if (empty($error)) {
                        $configContent = "<?php\n";
                        $configContent .= "if (session_status() === PHP_SESSION_NONE) session_start();\n";
                        $configContent .= "define('ROOT_PATH', realpath(__DIR__ . '/../') . '/');\n";
                        $configContent .= "define('BASE_URL', (isset(\$_SERVER['HTTPS']) && \$_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . \$_SERVER['HTTP_HOST']);\n\n";
                        $configContent .= "define('DB_HOST', '$db_host');\n";
                        $configContent .= "define('DB_NAME', '$db_name');\n";
                        $configContent .= "define('DB_USER', '$db_user');\n";
                        $configContent .= "define('DB_PASS', '$db_pass');\n";
                        $configContent .= "define('DB_CHARSET', 'utf8mb4');\n";
                        $configContent .= "\$dirs = [ROOT_PATH . 'data', ROOT_PATH . 'data/chapters', ROOT_PATH . 'data/covers', ROOT_PATH . 'assets/uploads/ads', ROOT_PATH . 'assets/uploads/logo'];\n";
                        $configContent .= "foreach (\$dirs as \$dir) { if (!is_dir(\$dir)) mkdir(\$dir, 0755, true); }\n\n";
                        $configContent .= "spl_autoload_register(function (\$class) {\n";
                        $configContent .= "    \$base_dir = ROOT_PATH . 'includes/';\n";
                        $configContent .= "    \$file = \$base_dir . str_replace('\\\\', '/', \$class) . '.php';\n";
                        $configContent .= "    if (file_exists(\$file)) { require \$file; return true; }\n";
                        $configContent .= "    return false;\n";
                        $configContent .= "});\n\n";
                        $configContent .= "require_once ROOT_PATH . 'includes/functions.php';\n";
                        $configContent .= "\$db = new Database();\n";
                        $configContent .= "\$lang = new Language();\n";
                        $configContent .= "\$GLOBALS['db'] = \$db;\n";
                        $configContent .= "\$GLOBALS['lang'] = \$lang;\n";
                        $configContent .= "?>";

                        if (file_put_contents(__DIR__ . '/includes/config.php', $configContent) === false) {
                            $error = '无法写入 config.php 文件，请检查目录权限';
                        } else {
                            session_start();
                            $_SESSION['install_data'] = [
                                'site_name' => $site_name,
                                'admin_user' => $admin_user,
                                'admin_pass' => $admin_pass,
                            ];
                            header('Location: install.php?step=2');
                            exit;
                        }
                    }
                }
                $testConn->close();
            }
        }
    } elseif ($step == 2) {
        session_start();
        if (!isset($_SESSION['install_data'])) {
            header('Location: install.php');
            exit;
        }
        $site_name = $_SESSION['install_data']['site_name'];
        $admin_user = $_SESSION['install_data']['admin_user'];
        $admin_pass = $_SESSION['install_data']['admin_pass'];

        $configFile = __DIR__ . '/includes/config.php';
        if (!file_exists($configFile)) {
            $error = 'config.php 文件不存在，请返回上一步重新生成';
        } else {
            $configContent = file_get_contents($configFile);
            preg_match("/define\('DB_HOST',\s*'([^']+)'\);/", $configContent, $hostMatch);
            preg_match("/define\('DB_NAME',\s*'([^']+)'\);/", $configContent, $nameMatch);
            preg_match("/define\('DB_USER',\s*'([^']+)'\);/", $configContent, $userMatch);
            preg_match("/define\('DB_PASS',\s*'([^']*)'\);/", $configContent, $passMatch);

            $db_host = $hostMatch[1] ?? 'localhost';
            $db_name = $nameMatch[1] ?? '';
            $db_user = $userMatch[1] ?? '';
            $db_pass = $passMatch[1] ?? '';

            if (empty($db_name)) {
                $error = '无法解析数据库配置，请检查config.php';
            } else {
                $mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
                if ($mysqli->connect_error) {
                    $error = '数据库连接失败：' . $mysqli->connect_error;
                } else {
                    $mysqli->set_charset('utf8mb4');

                    $tables = [
                        "CREATE TABLE IF NOT EXISTS `users` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `username` varchar(50) NOT NULL,
                            `password` varchar(255) NOT NULL,
                            `email` varchar(100) DEFAULT NULL,
                            `avatar` varchar(255) DEFAULT '/assets/images/default_avatar.png',
                            `gold` int(11) DEFAULT '0',
                            `vip_level` tinyint(1) DEFAULT '0',
                            `vip_expire` datetime DEFAULT NULL,
                            `sign_days` int(11) DEFAULT '0',
                            `last_sign` date DEFAULT NULL,
                            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `novels` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `title` varchar(100) NOT NULL,
                            `author` varchar(50) DEFAULT NULL,
                            `category_id` int(11) DEFAULT NULL,
                            `cover` varchar(255) DEFAULT NULL,
                            `description` text,
                            `status` tinyint(1) DEFAULT '0',
                            `views` int(11) DEFAULT '0',
                            `total_words` int(11) DEFAULT '0',
                            `favorites` int(11) NOT NULL DEFAULT '0',
                            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                            `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `categories` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `name` varchar(50) NOT NULL,
                            `sort` int(11) DEFAULT '0',
                            PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `chapters` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `novel_id` int(11) NOT NULL,
                            `volume_id` int(11) NOT NULL DEFAULT '0',
                            `title` varchar(200) NOT NULL,
                            `word_count` int(11) DEFAULT '0',
                            `file_path` varchar(255) DEFAULT NULL,
                            `source_url` varchar(255) DEFAULT NULL,
                            `sort` int(11) DEFAULT '0',
                            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`),
                            KEY `novel_id` (`novel_id`),
                            KEY `volume_id` (`volume_id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `volumes` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `novel_id` int(11) NOT NULL,
                            `title` varchar(100) NOT NULL,
                            `sort` int(11) DEFAULT '0',
                            PRIMARY KEY (`id`),
                            KEY `novel_id` (`novel_id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `bookshelf` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `user_id` int(11) NOT NULL,
                            `novel_id` int(11) NOT NULL,
                            `last_read_chapter` int(11) DEFAULT NULL,
                            `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`),
                            UNIQUE KEY `user_novel` (`user_id`,`novel_id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `reading_history` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `user_id` int(11) NOT NULL,
                            `novel_id` int(11) NOT NULL,
                            `chapter_id` int(11) NOT NULL,
                            `read_at` datetime DEFAULT CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`),
                            KEY `user_id` (`user_id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `orders` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `out_trade_no` varchar(32) NOT NULL,
                            `user_id` int(11) NOT NULL,
                            `money` decimal(10,2) NOT NULL,
                            `type` varchar(20) DEFAULT 'vip',
                            `months` int(11) DEFAULT 1,
                            `status` tinyint(1) DEFAULT '0',
                            `pay_time` datetime DEFAULT NULL,
                            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`),
                            UNIQUE KEY `out_trade_no` (`out_trade_no`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `settings` (
                            `key` varchar(50) NOT NULL,
                            `value` text,
                            PRIMARY KEY (`key`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `ads` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `name` varchar(100) DEFAULT NULL,
                            `position` varchar(30) DEFAULT 'home',
                            `html_code` text,
                            `sort` int(11) DEFAULT '0',
                            `enabled` tinyint(1) DEFAULT '1',
                            PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `admins` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `username` varchar(50) NOT NULL,
                            `password` varchar(255) NOT NULL,
                            PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `seo_settings` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `page` varchar(50) NOT NULL,
                            `title` varchar(200) DEFAULT NULL,
                            `keywords` varchar(255) DEFAULT NULL,
                            `description` text,
                            PRIMARY KEY (`id`),
                            UNIQUE KEY `page` (`page`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `diy_blocks` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `name` varchar(50) NOT NULL,
                            `title` varchar(100) DEFAULT NULL,
                            `num` int(11) DEFAULT '10',
                            `category_id` int(11) DEFAULT '0',
                            `status` varchar(20) DEFAULT 'all',
                            `min_words` int(11) DEFAULT '0',
                            `max_words` int(11) DEFAULT '0',
                            `order_by` varchar(20) DEFAULT 'views',
                            `time_range` varchar(30) DEFAULT 'all',
                            `cache_time` int(11) DEFAULT '300',
                            `custom_ids` text,
                            `data` longtext,
                            `updated_at` datetime DEFAULT NULL,
                            PRIMARY KEY (`id`),
                            UNIQUE KEY `name` (`name`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `stats_visit` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `visit_date` date NOT NULL,
                            `spider_count` int(11) DEFAULT '0',
                            `real_count` int(11) DEFAULT '0',
                            `pv` int(11) DEFAULT '0',
                            PRIMARY KEY (`id`),
                            UNIQUE KEY `visit_date` (`visit_date`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `gold_logs` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `user_id` int(11) NOT NULL,
                            `type` varchar(20) NOT NULL,
                            `gold_change` int(11) NOT NULL,
                            `gold_after` int(11) NOT NULL,
                            `remark` varchar(255) DEFAULT NULL,
                            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`),
                            KEY `user_id` (`user_id`),
                            UNIQUE KEY `unique_sign` (`user_id`, `type`, `created_at`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `email_verify` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `email` varchar(100) NOT NULL,
                            `code` varchar(10) NOT NULL,
                            `expire` datetime NOT NULL,
                            `used` tinyint(1) DEFAULT '0',
                            PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
                        "CREATE TABLE IF NOT EXISTS `crawl_rules` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `rule_key` varchar(50) NOT NULL,
                            `name` varchar(100) NOT NULL,
                            `site_url` varchar(255) DEFAULT NULL,
                            `charset` varchar(20) DEFAULT 'UTF-8',
                            `config` longtext NOT NULL,
                            `status` tinyint(1) NOT NULL DEFAULT '1',
                            `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                            PRIMARY KEY (`id`),
                            UNIQUE KEY `rule_key` (`rule_key`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
                    ];

                    try {
                        foreach ($tables as $sql) {
                            if (!$mysqli->query($sql)) {
                                throw new Exception($mysqli->error);
                            }
                        }
                        $mysqli->close();

                        require_once __DIR__ . '/includes/config.php';

                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('site_name', ?)", [$site_name]);
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('site_lang', 'zh-cn')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('sign_base_gold', '10')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('sign_continue_percent', '5')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('sign_max_continue_bonus', '100')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('sign_min_continue_bonus', '1')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('vip_price_per_month', '30')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('vip_gold_per_month', '3000')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('smtp_host', '')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('smtp_port', '25')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('smtp_secure', '')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('smtp_user', '')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('smtp_pass', '')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('smtp_from', '')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('smtp_fromname', 'EnovelCms')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('site_logo', '/assets/images/default_logo.png')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('library_per_page', '20')");
                        $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('keyword_links', '')");

                        $catCheck = $db->fetch($db->query("SELECT id FROM categories WHERE name='玄幻'"));
                        if (!$catCheck) {
                            $db->query("INSERT INTO categories (name, sort) VALUES ('玄幻',1),('都市',2),('言情',3),('历史',4),('科幻',5)");
                        }

                        $defaultSeo = [
                            ['home', '{site_name} - 首页', '{site_keywords}', '{site_description}'],
                            ['library', '{site_name} - 书库', '小说书库,{site_keywords}', '全部小说列表'],
                            ['rank', '{site_name} - 排行榜', '小说排行榜,{site_keywords}', '最热小说排行'],
                            ['author', '{site_name} - 作者列表', '作者大全,{site_keywords}', '本站入驻作者'],
                            ['novel_detail', '{novel_title} - {site_name}', '{novel_keywords}', '{novel_description}'],
                            ['read', '{chapter_title} - {novel_title} - {site_name}', '{novel_keywords}', '阅读{chapter_title}'],
                            ['search', '{keyword} - {site_name} 搜索结果', '{keyword},小说搜索,{site_keywords}', '关于"{keyword}"的搜索结果 - {site_name}']
                        ];
                        foreach ($defaultSeo as $seo) {
                            $db->query("INSERT INTO seo_settings (page, title, keywords, description) VALUES (?,?,?,?)", $seo);
                        }

                        $hashed = password_hash($admin_pass, PASSWORD_DEFAULT);
                        $db->query("INSERT INTO admins (username, password) VALUES (?, ?)", [$admin_user, $hashed]);

                        $userCheck = $db->fetch($db->query("SELECT id FROM users LIMIT 1"));
                        if (!$userCheck) {
                            $userPass = password_hash('123456', PASSWORD_DEFAULT);
                            $db->query("INSERT INTO users (username, password, email, gold) VALUES ('test', ?, 'test@example.com', 100)", [$userPass]);
                        }

                        $defaultBlocks = [
                            [
                                'name'       => 'featured_novels',
                                'title'      => '精选小说',
                                'num'        => 6,
                                'order_by'   => 'favorites',
                                'time_range' => 'all',
                                'cache_time' => 300,
                                'custom_ids' => ''
                            ],
                            [
                                'name'       => 'latest_updates',
                                'title'      => '最新更新',
                                'num'        => 20,
                                'order_by'   => 'update',
                                'time_range' => 'all',
                                'cache_time' => 300,
                                'custom_ids' => ''
                            ],
                            [
                                'name'       => 'rank_views',
                                'title'      => '点击榜',
                                'num'        => 10,
                                'order_by'   => 'views',
                                'time_range' => 'week',
                                'cache_time' => 300,
                                'custom_ids' => ''
                            ],
                            [
                                'name'       => 'rank_favorites',
                                'title'      => '收藏榜',
                                'num'        => 10,
                                'order_by'   => 'favorites',
                                'time_range' => 'week',
                                'cache_time' => 300,
                                'custom_ids' => ''
                            ],
                            [
                                'name'       => 'rank_words',
                                'title'      => '字数榜',
                                'num'        => 10,
                                'order_by'   => 'words',
                                'time_range' => 'all',
                                'cache_time' => 300,
                                'custom_ids' => ''
                            ],
                            [
                                'name'       => 'random_picks',
                                'title'      => '随机推荐',
                                'num'        => 12,
                                'order_by'   => 'random',
                                'time_range' => 'all',
                                'cache_time' => 300,
                                'custom_ids' => ''
                            ],
                            [
                                'name'       => 'related_novels',
                                'title'      => '相关推荐',
                                'num'        => 6,
                                'order_by'   => 'favorites',
                                'time_range' => 'all',
                                'cache_time' => 300,
                                'custom_ids' => ''
                            ]
                        ];
                        foreach ($defaultBlocks as $block) {
                            $exists = $db->fetch($db->query("SELECT id FROM diy_blocks WHERE name = ?", [$block['name']]));
                            if (!$exists) {
                                $db->query(
                                    "INSERT INTO diy_blocks 
                                    (name, title, num, category_id, status, min_words, max_words, order_by, time_range, cache_time, custom_ids) 
                                    VALUES (?, ?, ?, 0, 'all', 0, 0, ?, ?, ?, ?)",
                                    [
                                        $block['name'],
                                        $block['title'],
                                        $block['num'],
                                        $block['order_by'],
                                        $block['time_range'],
                                        $block['cache_time'],
                                        $block['custom_ids']
                                    ]
                                );
                            }
                        }

                        if (!is_dir(__DIR__ . '/data')) {
                            mkdir(__DIR__ . '/data', 0755, true);
                        }
                        file_put_contents($lockFile, date('Y-m-d H:i:s') . "\n");

                        $installPath = __DIR__ . '/install.php';
                        if (file_exists($installPath)) {
                            $newName = 'install_' . time() . '_' . substr(bin2hex(random_bytes(4)), 0, 8) . '.bak';
                            $newPath = __DIR__ . '/data/' . $newName;
                            rename($installPath, $newPath);
                        }

                        unset($_SESSION['install_data']);
                        header('Location: index.php');
                        exit;
                    } catch (Exception $e) {
                        $error = '安装失败：' . $e->getMessage();
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>EnovelCms 1.5 系统安装向导</title>
    <style>
        body { font-family: 'Helvetica Neue', Arial, sans-serif; background: #f5f7fa; margin: 0; padding: 20px; }
        .container { max-width: 700px; margin: 50px auto; background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h2 { text-align: center; margin-bottom: 20px; color: #2c3e50; }
        h3 { margin-top: 25px; }
        label { display: block; margin: 15px 0 5px; font-weight: bold; }
        input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        button { background: #27ae60; color: #fff; padding: 12px 20px; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; width: 100%; margin-top: 20px; }
        .error { color: #e74c3c; background: #fadbd8; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
        .info { color: #3498db; margin-bottom: 20px; }
        .agreement-box { border: 1px solid #ddd; background: #fefefe; padding: 12px; height: 200px; overflow-y: scroll; margin: 15px 0; font-size: 12px; line-height: 1.5; color: #333; }
        .agree-check { margin: 10px 0; }
        .agree-check label { display: inline; font-weight: normal; }
        #configSection { display: none; }
    </style>
    <script>
        function toggleConfig(el) {
            var agreementSection = document.getElementById('agreementSection');
            var configSection = document.getElementById('configSection');
            if (el.checked) {
                agreementSection.style.display = 'none';
                configSection.style.display = 'block';
            } else {
                agreementSection.style.display = 'block';
                configSection.style.display = 'none';
            }
        }
    </script>
</head>
<body>
<div class="container">
    <h2>EnovelCms 1.5 系统安装向导</h2>
    <?php if (!empty($error)): ?>
        <div class="error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>
    
    <?php if ($step == 1): ?>
        <form method="post">
            <div id="agreementSection">
                <h3>用户协议</h3>
                <div class="agreement-box">
                    <strong>Enovel CMS 用户协议</strong><br><br>
                    感谢您选择 Enovel 小说系统（以下简称“本软件”）。在安装或使用本软件前，请仔细阅读以下条款。一旦安装、复制或以其他方式使用本软件，即表示您同意接受本协议约束。<br><br>
                    <strong>1. 许可范围</strong><br>
                    您可以在遵守本协议的前提下，在单个网站域名下自由使用本软件，不得对软件进行反向工程、反编译或试图提取源代码（开源部分除外）。再尊重版权的前提下允许你基于本程序免费商用和二开，但是本程序官网不会提供任何二开技术支持。<br><br>
                    <strong>2. 使用限制</strong><br>
                    您不得利用本软件从事任何违法违规活动，包括但不限于传播色情、赌博、暴力、政治敏感内容或侵犯他人知识产权的内容。因使用本软件产生的任何法律后果由您自行承担，软件作者不承担连带责任。<br><br>
                    <strong>3. 免责声明</strong><br>
                    本软件按“现状”提供，不提供任何明示或暗示的担保。作者不对因使用本软件造成的任何数据丢失、业务中断或经济损失负责。建议您定期备份数据。<br><br>
                    <strong>4. 保留权利</strong><br>
                    本软件的知识产权（包括版权、商标权等）归原作者所有。未经授权不得去除或修改软件中的版权标识。<br><br>
                    <strong>5. 其他</strong><br>
                    本协议受中华人民共和国法律管辖。如有任何争议，双方应友好协商解决。作者保留随时更新本协议的权利，更新后继续使用即视为接受修改。<br><br>
                    如果您不同意以上条款，请停止安装并删除所有相关文件。
                </div>
                <div class="agree-check">
                    <input type="checkbox" name="agree" value="1" id="agreeCheck" onchange="toggleConfig(this)" required>
                    <label for="agreeCheck">我已经阅读并同意上述用户协议</label>
                </div>
            </div>

            <div id="configSection">
                <h3>数据库配置</h3>
                <label>数据库主机 *</label>
                <input type="text" name="db_host" value="localhost" required>
                <label>数据库名 *</label>
                <input type="text" name="db_name" value="enovel" required>
                <label>数据库用户名 *</label>
                <input type="text" name="db_user" value="root" required>
                <label>数据库密码</label>
                <input type="password" name="db_pass">
                
                <h3>网站信息</h3>
                <label>网站名称</label>
                <input type="text" name="site_name" value="EnovelCms">
                
                <h3>管理员账号</h3>
                <label>管理员用户名 *</label>
                <input type="text" name="admin_user" value="admin" required>
                <label>管理员密码 *</label>
                <input type="password" name="admin_pass" value="" required>
            </div>

            <button type="submit">下一步：创建数据表</button>
        </form>
    <?php elseif ($step == 2): ?>
        <div class="info">正在安装，请稍候...</div>
        <form method="post" id="installForm"></form>
        <script>document.getElementById('installForm').submit();</script>
    <?php endif; ?>
</div>
</body>
</html>