<?php
/**
 * 版本更新系统
 * 重构版本：合并 includes/version.php 和 install/update.php
 */

// 如果未初始化，尝试初始化数据库连接
if (!defined('SYSTEM_ROOT') || !isset($DB)) {
    $root = dirname(__FILE__) . '/../';
    
    // 引入配置文件
    if(file_exists($root . 'config.php')) {
        require_once $root . 'config.php';
    }
    
    // 引入自动加载器
    if(file_exists($root . 'includes/autoloader.php')) {
        require_once $root . 'includes/autoloader.php';
        Autoloader::register();
    }
    
    // 创建数据库连接
    if(isset($dbconfig)) {
        $DB = new \lib\PdoHelper($dbconfig);
    }
}

// 加载全局配置
if (!isset($conf) || empty($conf)) {
    $conf = [];
    if(isset($DB)) {
        $rs = $DB->query("SELECT * FROM pre_config");
        if($rs) {
            while($res = $rs->fetch()) {
                $conf[$res['k']] = $res['v'];
            }
        }
    }
}

if (!function_exists('get_auth_version')) {
    function get_auth_version() {
        $auth_file = dirname(__FILE__) . '/Auth.php';
        if (!file_exists($auth_file)) {
            return null;
        }
        $auth_config = include $auth_file;
        return isset($auth_config['app_version']) ? $auth_config['app_version'] : null;
    }
}

if (!function_exists('get_db_version')) {
    function get_db_version() {
        global $conf;
        return $conf['version'] ?? '1.0';
    }
}

if (!function_exists('get_update_sql_files')) {
    function get_update_sql_files($install_dir) {
        $files = glob($install_dir . '/update*.sql');
        $versions = [];
        foreach ($files as $file) {
            $basename = basename($file);
            // 匹配 update1.79.sql 或 update_1.79.sql 格式
            if (preg_match('/update[_]?([\d.]+)\.sql/', $basename, $matches)) {
                $versions[] = [
                    'version' => $matches[1],
                    'file' => $file
                ];
            }
        }
        usort($versions, function($a, $b) {
            return version_compare($a['version'], $b['version']);
        });
        return $versions;
    }
}

if (!function_exists('run_update_sql')) {
    function run_update_sql($sql_file) {
        global $DB;
        
        if (!file_exists($sql_file)) {
            return ['code' => 0, 'msg' => 'SQL文件不存在'];
        }
        
        $sqls = file_get_contents($sql_file);
        if (mb_substr($sqls, -1) == ';') {
            $sqls = rtrim($sqls, ';');
        }
        
        $explode = explode(';', $sqls);
        $success = 0;
        $error = 0;
        $errorMsg = null;
        
        foreach ($explode as $sql) {
            if ($sql = trim($sql)) {
                if ($DB->exec($sql) === false) {
                    $error++;
                    $errorMsg = $sql . '<br>' . $DB->error() . '<br><hr>';
                } else {
                    $success++;
                }
            }
        }
        
        return [
            'code' => $error > 0 ? -1 : 1,
            'success' => $success,
            'error' => $error,
            'errorMsg' => $errorMsg
        ];
    }
}

// 处理强制更新版本号
if (isset($_POST['force_update']) && $_POST['force_update'] == '1') {
    global $DB;
    $auth_version = get_auth_version();
    $target_version = isset($_POST['target_version']) ? $_POST['target_version'] : $auth_version;
    
    if(isset($DB)) {
        $DB->query("REPLACE INTO pre_config SET v='" . $target_version . "',k='version'");
    }
    
    header('Content-type:text/html;charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>版本号已更新</title>
        <script src="../assets/js/tailwind.js"></script>
        <link rel="stylesheet" href="../assets/css/all.min.css">
        <style>
            .gradient-bg { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        </style>
    </head>
    <body class="bg-gray-50 min-h-screen flex items-center justify-center p-4">
        <div class="w-full max-w-md">
            <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
                <div class="gradient-bg p-6 text-white text-center">
                    <div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-check text-3xl"></i>
                    </div>
                    <h1 class="text-2xl font-bold">版本号已更新</h1>
                </div>
                <div class="p-6 text-center">
                    <p class="text-green-600 font-medium mb-2">数据库版本已强制更新到：<?php echo $target_version; ?></p>
                    <p class="text-gray-400 text-sm mb-6">请确保已手动执行了所有必要的SQL更新</p>
                    <a href="/admin" class="inline-flex items-center gap-2 px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors">
                        <i class="fas fa-home"></i>
                        <span>返回后台</span>
                    </a>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// 版本检测和更新
$auth_version = get_auth_version();
$db_version = get_db_version();

// 如果数据库版本低于授权版本，显示更新页面
if ($auth_version !== null && version_compare($auth_version, $db_version) > 0) {
    $install_dir = dirname(__FILE__) . '/../install';
    $update_files = get_update_sql_files($install_dir);
    
    header('Content-type:text/html;charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>系统升级</title>
        <script src="../assets/js/tailwind.js"></script>
        <link rel="stylesheet" href="../assets/css/all.min.css">
        <style>
            .gradient-bg { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        </style>
    </head>
    <body class="bg-gray-50 min-h-screen flex items-center justify-center p-4">
        <div class="w-full max-w-2xl">
            <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
                <div class="gradient-bg p-6 text-white">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                            <i class="fas fa-arrow-up text-2xl"></i>
                        </div>
                        <div>
                            <h1 class="text-2xl font-bold">检测到新版本</h1>
                            <p class="text-white/80 text-sm">自动升级中...</p>
                        </div>
                    </div>
                </div>
                <div class="p-6">
                    <?php if (!empty($update_files)): ?>
                        <?php
                        $updated = false;
                        $results = [];
                        $found = false;
                        
                        foreach ($update_files as $update) {
                            $version = $update['version'];
                            $file = $update['file'];
                            
                            if (version_compare($version, $db_version) > 0 && version_compare($version, $auth_version) <= 0) {
                                $found = true;
                                $result = run_update_sql($file);
                                $results[] = [
                                    'version' => $version,
                                    'result' => $result
                                ];
                                
                                if ($result['code'] > 0) {
                                    $updated = true;
                                    $versionDb = daddslashes($version);
                                    $DB->query("REPLACE INTO pre_config SET v='" . $versionDb . "',k='version'");
                                }
                            }
                        }
                        
                        // 如果没有找到需要更新的文件
                        if (!$found) {
                            ?>
                            <div class="text-center py-8">
                                <div class="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i class="fas fa-info-circle text-yellow-500 text-2xl"></i>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-800 mb-2">未找到对应更新</h3>
                                <p class="text-gray-500 mb-6">未找到版本 <?php echo $auth_version; ?> 对应的更新SQL文件</p>
                                
                                <div class="mt-8 pt-6 border-t border-gray-100">
                                    <h4 class="font-medium text-gray-700 mb-3">强制更新版本号</h4>
                                    <div class="bg-yellow-50 rounded-lg p-4 mb-4 text-left">
                                        <p class="text-yellow-700 text-sm flex items-start gap-2">
                                            <i class="fas fa-exclamation-triangle mt-0.5"></i>
                                            <span>警告：强制更新版本号不会执行任何SQL更新，仅更新数据库中的版本号。请确保已手动执行了所有必要的SQL更新！</span>
                                        </p>
                                    </div>
                                    <form method="post" action="" class="flex justify-center">
                                        <input type="hidden" name="force_update" value="1">
                                        <input type="hidden" name="target_version" value="<?php echo $auth_version; ?>">
                                        <button type="submit" class="inline-flex items-center gap-2 px-6 py-3 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors">
                                            <i class="fas fa-bolt"></i>
                                            <span>强制更新版本号到 <?php echo $auth_version; ?></span>
                                        </button>
                                    </form>
                                </div>
                            </div>
                            <?php
                            exit;
                        }
                        ?>
                        
                        <?php if ($updated): ?>
                            <div class="text-center py-8">
                                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i class="fas fa-check-circle text-green-500 text-2xl"></i>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-800 mb-2">升级成功</h3>
                                <p class="text-gray-500 mb-6">成功执行所有更新SQL文件</p>
                                
                                <?php if (!empty($results)): ?>
                                <div class="bg-gray-50 rounded-xl p-4 mb-6 text-left">
                                    <h4 class="font-medium text-gray-700 mb-3">升级详情</h4>
                                    <div class="space-y-2">
                                        <?php foreach ($results as $item): ?>
                                        <div class="flex items-center justify-between py-2 px-3 bg-white rounded-lg">
                                            <span class="text-sm text-gray-600">版本 <?php echo $item['version']; ?></span>
                                            <span class="text-sm text-green-600 flex items-center gap-1">
                                                <i class="fas fa-check"></i>
                                                成功
                                            </span>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <a href="/admin" class="inline-flex items-center gap-2 px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors">
                                    <i class="fas fa-home"></i>
                                    <span>返回后台</span>
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-8">
                                <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i class="fas fa-times-circle text-red-500 text-2xl"></i>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-800 mb-2">升级失败</h3>
                                <p class="text-gray-500 mb-6">升级过程中出现错误</p>
                                
                                <!-- 错误详情 -->
                                <div class="bg-red-50 rounded-xl p-4 mb-6 text-left">
                                    <h4 class="font-medium text-red-700 mb-3">错误信息</h4>
                                    <div class="space-y-2">
                                        <?php foreach ($results as $item): ?>
                                            <?php if ($item['result']['code'] < 0): ?>
                                            <div class="text-sm text-red-600">
                                                <p class="font-medium">版本 <?php echo $item['version']; ?>:</p>
                                                <p class="text-red-500"><?php echo $item['result']['errorMsg']; ?></p>
                                            </div>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                
                                <div class="mt-8 pt-6 border-t border-gray-100">
                                    <h4 class="font-medium text-gray-700 mb-3">强制更新版本号</h4>
                                    <div class="bg-yellow-50 rounded-lg p-4 mb-4 text-left">
                                        <p class="text-yellow-700 text-sm flex items-start gap-2">
                                            <i class="fas fa-exclamation-triangle mt-0.5"></i>
                                            <span>警告：强制更新版本号不会执行任何SQL更新，仅更新数据库中的版本号。请确保已手动执行了所有必要的SQL更新！</span>
                                        </p>
                                    </div>
                                    <form method="post" action="" class="flex justify-center">
                                        <input type="hidden" name="force_update" value="1">
                                        <input type="hidden" name="target_version" value="<?php echo $auth_version; ?>">
                                        <button type="submit" class="inline-flex items-center gap-2 px-6 py-3 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors">
                                            <i class="fas fa-bolt"></i>
                                            <span>强制更新版本号到 <?php echo $auth_version; ?></span>
                                        </button>
                                    </form>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="text-center py-8">
                            <div class="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-folder-open text-yellow-500 text-2xl"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-800 mb-2">未找到更新SQL文件</h3>
                            <p class="text-gray-500 mb-6">未找到版本 <?php echo $auth_version; ?> 对应的更新SQL文件</p>
                            
                            <div class="mt-8 pt-6 border-t border-gray-100">
                                <h4 class="font-medium text-gray-700 mb-3">强制更新版本号</h4>
                                <div class="bg-yellow-50 rounded-lg p-4 mb-4 text-left">
                                    <p class="text-yellow-700 text-sm flex items-start gap-2">
                                        <i class="fas fa-exclamation-triangle mt-0.5"></i>
                                        <span>警告：强制更新版本号不会执行任何SQL更新，仅更新数据库中的版本号。请确保已手动执行了所有必要的SQL更新！</span>
                                    </p>
                                </div>
                                <form method="post" action="" class="flex justify-center">
                                    <input type="hidden" name="force_update" value="1">
                                    <input type="hidden" name="target_version" value="<?php echo $auth_version; ?>">
                                    <button type="submit" class="inline-flex items-center gap-2 px-6 py-3 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors">
                                        <i class="fas fa-bolt"></i>
                                        <span>强制更新版本号到 <?php echo $auth_version; ?></span>
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="mt-4 text-center">
                <div class="inline-flex items-center gap-4 text-sm text-gray-500">
                    <span class="flex items-center gap-1">
                        <i class="fas fa-database text-indigo-500"></i>
                        数据库版本: <?php echo $db_version; ?>
                    </span>
                    <span class="text-gray-300">|</span>
                    <span class="flex items-center gap-1">
                        <i class="fas fa-key text-purple-500"></i>
                        授权版本: <?php echo $auth_version; ?>
                    </span>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// 定义当前版本
define('VERSION', get_db_version());
