<?php
/**
 * EnovelCms 升级程序：从 1.0 升级到 1.5
 * 运行前请务必备份数据库和文件！
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

define('ROOT_PATH', __DIR__ . '/');

$upgradeLock = ROOT_PATH . 'data/upgrade_1.5.lock';
if (file_exists($upgradeLock)) {
    die('升级已经执行过，如需重新升级请删除 data/upgrade_1.5.lock 文件。');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 1) {
        if (!isset($_POST['agree'])) {
            $error = '请确认已经备份数据库和文件，并同意继续升级。';
        } else {
            if (!file_exists(ROOT_PATH . 'includes/config.php')) {
                $error = '未找到 config.php，请确保已在 1.0 基础上覆盖了 1.5 的程序文件。';
            } else {
                require_once ROOT_PATH . 'includes/config.php';
                try {
                    $db->query("SELECT 1");
                } catch (Exception $e) {
                    $error = '数据库连接失败：' . $e->getMessage();
                }
                if (empty($error)) {
                    $_SESSION['upgrade_step2'] = true;
                    header('Location: upgrade.php?step=2');
                    exit;
                }
            }
        }
    } elseif ($step == 2) {
        if (empty($_SESSION['upgrade_step2'])) {
            header('Location: upgrade.php');
            exit;
        }
        @require_once ROOT_PATH . 'includes/config.php';

        $db->query("START TRANSACTION");
        try {
            $res = $db->query("SHOW COLUMNS FROM ads");
            $hasHtmlCode = false;
            while ($row = $db->fetch($res)) {
                if ($row['Field'] == 'html_code') $hasHtmlCode = true;
            }
            if (!$hasHtmlCode) {
                $db->query("ALTER TABLE ads ADD COLUMN html_code TEXT AFTER link");
                $message .= "✓ 已添加 ads.html_code 字段。<br>";
            }

            $db->query("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;");
            $message .= "✓ 已创建 volumes 表。<br>";

            $res = $db->query("SHOW COLUMNS FROM chapters");
            $hasVolumeId = false;
            $hasSourceUrl = false;
            while ($row = $db->fetch($res)) {
                if ($row['Field'] == 'volume_id') $hasVolumeId = true;
                if ($row['Field'] == 'source_url') $hasSourceUrl = true;
            }
            if (!$hasVolumeId) {
                $db->query("ALTER TABLE chapters ADD COLUMN volume_id INT(11) NOT NULL DEFAULT 0 AFTER novel_id");
                $message .= "✓ 已添加 chapters.volume_id 字段。<br>";
            }
            if (!$hasSourceUrl) {
                $db->query("ALTER TABLE chapters ADD COLUMN source_url VARCHAR(255) DEFAULT NULL AFTER file_path");
                $message .= "✓ 已添加 chapters.source_url 字段。<br>";
            }
            $db->query("ALTER TABLE chapters ADD INDEX (volume_id)");

            $novels = $db->fetchAll($db->query("SELECT id FROM novels"));
            foreach ($novels as $novel) {
                $defaultVol = $db->fetch($db->query("SELECT id FROM volumes WHERE novel_id = ? AND title = '默认卷'", [$novel['id']]));
                if (!$defaultVol) {
                    $db->query("INSERT INTO volumes (novel_id, title, sort) VALUES (?, '默认卷', 0)", [$novel['id']]);
                    $volId = $db->lastInsertId();
                } else {
                    $volId = $defaultVol['id'];
                }
                $db->query("UPDATE chapters SET volume_id = ? WHERE novel_id = ? AND volume_id = 0", [$volId, $novel['id']]);
            }
            $message .= "✓ 已为所有小说创建默认分卷并关联章节。<br>";

            $res = $db->query("SHOW COLUMNS FROM diy_blocks");
            $hasCustomIds = false;
            while ($row = $db->fetch($res)) {
                if ($row['Field'] == 'custom_ids') $hasCustomIds = true;
            }
            if (!$hasCustomIds) {
                $db->query("ALTER TABLE diy_blocks ADD COLUMN custom_ids TEXT AFTER cache_time");
                $message .= "✓ 已添加 diy_blocks.custom_ids 字段。<br>";
            }

            $db->query("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;");
            $message .= "✓ 已创建 crawl_rules 表。<br>";

            $settingKeys = ['keyword_links', 'library_per_page'];
            foreach ($settingKeys as $key) {
                $exists = $db->fetch($db->query("SELECT `key` FROM settings WHERE `key` = ?", [$key]));
                if (!$exists) {
                    $db->query("INSERT INTO settings (`key`, `value`) VALUES (?, '')", [$key]);
                    $message .= "✓ 已添加系统设置项：{$key}<br>";
                }
            }

            $defaultBlocks = [
                [
                    'name'       => 'featured_novels',
                    'title'      => '精选小说',
                    'num'        => 6,
                    'order_by'   => 'favorites',
                    'time_range' => 'all',
                    'cache_time' => 300
                ],
                [
                    'name'       => 'latest_updates',
                    'title'      => '最新更新',
                    'num'        => 20,
                    'order_by'   => 'update',
                    'time_range' => 'all',
                    'cache_time' => 300
                ],
                [
                    'name'       => 'rank_views',
                    'title'      => '点击榜',
                    'num'        => 10,
                    'order_by'   => 'views',
                    'time_range' => 'week',
                    'cache_time' => 300
                ],
                [
                    'name'       => 'rank_favorites',
                    'title'      => '收藏榜',
                    'num'        => 10,
                    'order_by'   => 'favorites',
                    'time_range' => 'week',
                    'cache_time' => 300
                ],
                [
                    'name'       => 'rank_words',
                    'title'      => '字数榜',
                    'num'        => 10,
                    'order_by'   => 'words',
                    'time_range' => 'all',
                    'cache_time' => 300
                ],
                [
                    'name'       => 'random_picks',
                    'title'      => '随机推荐',
                    'num'        => 12,
                    'order_by'   => 'random',
                    'time_range' => 'all',
                    'cache_time' => 300
                ],
                [
                    'name'       => 'related_novels',
                    'title'      => '相关推荐',
                    'num'        => 6,
                    'order_by'   => 'favorites',
                    'time_range' => 'all',
                    'cache_time' => 300
                ]
            ];

            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']
                        ]
                    );
                    $message .= "✓ 增加默认榜单：{$block['name']}<br>";
                }
            }

            file_put_contents($upgradeLock, date('Y-m-d H:i:s'));
            $db->query("COMMIT");
            $message .= "<strong style='color:green'>升级完成！您已成功从 1.0 升级到 1.5。</strong>";
            $step = 3; 
        } catch (Exception $e) {
            $db->query("ROLLBACK");
            $error = '升级失败：' . $e->getMessage();
        }
        unset($_SESSION['upgrade_step2']);
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>EnovelCms 1.0 → 1.5 升级程序</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f5f7fa; padding: 20px; }
        .container { max-width: 800px; margin: 50px auto; background: #fff; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { text-align: center; color: #2c3e50; }
        .warning { background: #fff3cd; border-left: 5px solid #ffc107; padding: 15px; margin: 20px 0; }
        .error { background: #f8d7da; color: #721c24; padding: 10px; border-radius: 5px; margin: 15px 0; }
        .success { background: #d4edda; color: #155724; padding: 10px; border-radius: 5px; margin: 15px 0; }
        button, .btn { background: #27ae60; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; text-decoration: none; display: inline-block; }
        .btn:hover { background: #219653; }
        .agree-check { margin: 20px 0; }
    </style>
</head>
<body>
<div class="container">
    <h1>EnovelCms 升级程序 (1.0 → 1.5)</h1>

    <?php if ($step == 1): ?>
        <div class="warning">
            <strong>⚠️ 重要：升级前请务必做好以下备份！</strong>
            <ul>
                <li>备份整个网站目录（特别是 data 目录和 includes/config.php）</li>
                <li>备份数据库（使用 phpMyAdmin 或 mysqldump）</li>
                <li>确认已将所有 1.5 版本的新文件（除了 config.php 和 data 目录）覆盖到网站根目录</li>
                <li>升级过程中会修改数据库结构，不会删除任何已有数据</li>
            </ul>
        </div>
        <?php if ($error): ?>
            <div class="error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <form method="post">
            <div class="agree-check">
                <input type="checkbox" name="agree" id="agree" required>
                <label for="agree">我已完整备份数据库和网站文件，并知晓升级风险，同意继续升级。</label>
            </div>
            <button type="submit">开始升级</button>
        </form>
    <?php elseif ($step == 2): ?>
        <div class="info">正在执行数据库升级，请勿关闭页面...</div>
        <form method="post" id="upgradeForm"></form>
        <script>document.getElementById('upgradeForm').submit();</script>
    <?php elseif ($step == 3): ?>
        <div class="success">
            <?= $message ?>
        </div>
        <p>您现在可以：</p>
        <ul>
            <li><a href="index.php">访问网站首页</a></li>
            <li><a href="admin/">登录后台管理</a>（使用原管理员账号）</li>
            <li>如果遇到任何问题，请检查 data/upgrade_1.5.lock 文件，如需重新升级请删除该文件后再运行 upgrade.php</li>
        </ul>
        <p><strong>建议：</strong> 删除本升级文件 upgrade.php 以避免重复执行。</p>
    <?php endif; ?>
</div>
</body>
</html>