<?php
require_once __DIR__ . '/../MPHX/common.php';
require_once __DIR__ . '/../MPHX/AuthManager.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$admin = is_admin_login();

// 当前版本
$current_version = 'v1.1.2';

// 从远程获取更新信息
$remote_version = '';
$update_info = array();
$fetch_error = '';

try {
    $authManager = new AuthManager($DB);
    
    // 获取token
    $token_result = $authManager->getToken();
    
    if ($token_result['code'] == 200) {
        $token = $token_result['data']['token'];
        
        // 保存token到session供心跳使用
        $_SESSION['auth_token'] = $token;
        $_SESSION['auth_token_expire'] = strtotime($token_result['data']['expire_time'] ?? '') ?: (time() + 86400);
        
        // 发送心跳获取版本信息
        $heartbeat = $authManager->heartbeat($token);
        
        if ($heartbeat['code'] == 200) {
            // 版本信息在 latest_version 中
            if (isset($heartbeat['data']['cloud']['latest_version']['version'])) {
                $latest_version = $heartbeat['data']['cloud']['latest_version'];
                $remote_version = 'v' . $latest_version['version'];
                $update_info = array(
                    'version' => $remote_version,
                    'size' => $latest_version['file_size'] ? formatBytes($latest_version['file_size']) : '未知',
                    'time' => date('Y-m-d'),
                    'log' => $latest_version['changelog'] ?? '暂无更新日志',
                    'download_url' => $latest_version['download_url'] ?? ''
                );
            } else {
                $fetch_error = '未获取到版本信息';
            }
        } else {
            $fetch_error = '心跳接口调用失败: ' . ($heartbeat['message'] ?? '未知错误');
        }
    } elseif ($token_result['code'] == 403 && isset($token_result['data']['need_auth'])) {
        // 需要购买授权
        $fetch_error = '更新服务：' . $token_result['message'] . '，请联系管理员购买正式授权。';
    } else {
        $fetch_error = '获取授权失败: ' . ($token_result['message'] ?? '未知错误');
    }
} catch (Exception $e) {
    $fetch_error = '获取更新信息失败: ' . $e->getMessage();
}

// 格式化字节大小函数
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

// 检查是否有新版本
$has_update = !empty($remote_version) && version_compare(ltrim($remote_version, 'v'), ltrim($current_version, 'v'), '>');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>系统更新 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css?v=<?php echo time(); ?>">
    <link rel="stylesheet" href="/static/css/all.min.css?v=<?php echo time(); ?>">
    <link rel="stylesheet" href="css/style.css?v=2026040501">
</head>
<body>
    <div class="content-area">
        <div class="card">
            <h3><i class="fas fa-sync-alt"></i> 系统更新</h3>
            
            <div class="version-info">
                <h4 style="color: #fff; margin-bottom: 8px;">当前版本: <?php echo $current_version; ?></h4>
                <p style="color: #fff; margin: 0;"><?php echo $has_update ? '发现新版本: ' . $remote_version : '系统运行正常'; ?></p>
            </div>
            
            <div class="alert">
                <i class="fas fa-info-circle"></i> 
                <strong>更新说明：</strong>
                <ul style="color: #5f6368; font-size: 13px; line-height: 1.8; margin: 12px 0 0 0; padding-left: 20px;">
                    <li>更新前请备份数据库和重要文件</li>
                    <li>更新过程中请勿关闭浏览器</li>
                    <li>更新完成后建议清除浏览器缓存</li>
                </ul>
            </div>
            
            <div class="form-group">
                <label>检查更新</label>
                <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <button class="btn btn-primary" onclick="checkUpdate(this)">
                        <i class="fas fa-sync-alt"></i> 检查更新
                    </button>
                    <button class="btn btn-warning" onclick="repairSystem(this)">
                        <i class="fas fa-wrench"></i> 系统修复
                    </button>
                    <button class="btn btn-secondary" onclick="checkDbTables(this)">
                        <i class="fas fa-database"></i> 数据库表检查
                    </button>
                    <button class="btn btn-danger" onclick="cleanOldFiles(this)">
                        <i class="fas fa-broom"></i> 清理旧文件
                    </button>
                    <a href="author.php" class="btn btn-info" target="_blank">
                        <i class="fas fa-user"></i> 作者说明
                    </a>
                </div>
            </div>
            
            <!-- 数据库表检查结果 -->
            <div id="dbCheckResult" style="display:none; margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e8eaed;">
                <h4 style="margin-bottom: 15px; color: #333;"><i class="fas fa-database"></i> 数据库表检查结果</h4>
                <div id="dbCheckContent"></div>
                <div style="margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap;">
                    <button class="btn btn-success" id="repairDbBtn" style="display:none;" onclick="repairDbTables(this)">
                        <i class="fas fa-tools"></i> 修复数据库表
                    </button>
                    <button class="btn btn-danger" id="deleteExtraBtn" style="display:none;" onclick="deleteExtraTables(this)">
                        <i class="fas fa-trash"></i> 删除多余表
                    </button>
                    <button class="btn btn-secondary" onclick="$('#dbCheckResult').hide()">
                        <i class="fas fa-times"></i> 关闭
                    </button>
                </div>
            </div>
            
            <div id="updateInfo" style="display:none;">
                <div class="alert" style="background: #e6f4ea; border: 1px solid #ceead6;">
                    <h4 style="color: #137333; margin-bottom: 12px;"><i class="fas fa-check-circle"></i> 发现新版本</h4>
                    <p style="color: #137333; margin-bottom: 8px;"><strong>最新版本：</strong> <span id="newVersion"></span></p>
                    <p style="color: #137333; margin-bottom: 8px;"><strong>更新大小：</strong> <span id="updateSize"></span></p>
                    <p style="color: #137333; margin: 0;"><strong>更新时间：</strong> <span id="updateTime"></span></p>
                </div>
                
                <div class="form-group">
                    <label>更新日志</label>
                    <div class="log-box" id="updateLog"></div>
                </div>
                
                <button class="btn btn-success" onclick="startUpdate(this)">
                    <i class="fas fa-download"></i> 立即更新
                </button>
            </div>
            
            <div id="updateProgress" style="display:none; margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e8eaed;">
                <h4 style="margin-bottom: 15px; color: #333;"><i class="fas fa-spinner fa-spin" id="progressIcon"></i> <span id="progressTitle">正在更新...</span></h4>
                
                <!-- 阶段指示器 -->
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 11px; color: #666; flex-wrap: wrap; gap: 5px;">
                    <div id="stage1" class="upgrade-stage" style="flex: 1; min-width: 100px; text-align: center; padding: 8px; border-radius: 4px; background: #e3f2fd; color: #1976d2; font-weight: bold;">
                        <i class="fas fa-save"></i> 创建备份
                    </div>
                    <div style="width: 10px; display: flex; align-items: center; justify-content: center; color: #ccc;">→</div>
                    <div id="stage2" class="upgrade-stage" style="flex: 1; min-width: 100px; text-align: center; padding: 8px; border-radius: 4px; background: #f5f5f5; color: #999;">
                        <i class="fas fa-download"></i> 下载更新
                    </div>
                    <div style="width: 10px; display: flex; align-items: center; justify-content: center; color: #ccc;">→</div>
                    <div id="stage3" class="upgrade-stage" style="flex: 1; min-width: 100px; text-align: center; padding: 8px; border-radius: 4px; background: #f5f5f5; color: #999;">
                        <i class="fas fa-database"></i> 更新数据库
                    </div>
                    <div style="width: 10px; display: flex; align-items: center; justify-content: center; color: #ccc;">→</div>
                    <div id="stage4" class="upgrade-stage" style="flex: 1; min-width: 100px; text-align: center; padding: 8px; border-radius: 4px; background: #f5f5f5; color: #999;">
                        <i class="fas fa-copy"></i> 更新文件
                    </div>
                    <div style="width: 10px; display: flex; align-items: center; justify-content: center; color: #ccc;">→</div>
                    <div id="stage5" class="upgrade-stage" style="flex: 1; min-width: 100px; text-align: center; padding: 8px; border-radius: 4px; background: #f5f5f5; color: #999;">
                        <i class="fas fa-check-circle"></i> 完成
                    </div>
                </div>
                
                <div class="progress" style="margin-bottom: 16px; height: 25px; background-color: #e9ecef; border-radius: 4px; overflow: hidden;">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%; height: 100%; background: linear-gradient(45deg, #1a73e8, #1557b0); transition: width 0.3s ease;" id="progressBar"></div>
                </div>
                <div class="log-box" id="updateOutput" style="min-height: 150px; max-height: 300px; overflow-y: auto;"></div>
                
                <!-- 回滚按钮 -->
                <div id="rollbackSection" style="display:none; margin-top: 15px; padding-top: 15px; border-top: 1px solid #e8eaed;">
                    <button class="btn btn-danger" onclick="rollbackUpdate()">
                        <i class="fas fa-undo"></i> 回滚到更新前状态
                    </button>
                    <span style="color: #666; font-size: 12px; margin-left: 10px;">如果更新后出现问题，可以点击此按钮恢复</span>
                </div>
            </div>
        </div>
    </div>
    
    <script src="/static/js/jquery.min.js?v=<?php echo time(); ?>"></script>
    <script>
    var updateDownloadUrl = '';
    
    function checkUpdate(btn) {
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.addClass('btn-loading').prop('disabled', true);
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php?v=' + new Date().getTime(),
            data: {egn: 'checkupdate'},
            dataType: 'json',
            success: function(data) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                if(data.code == 200) {
                    if(data.has_update) {
                        updateDownloadUrl = data.download_url || '';
                        $('#updateInfo').show();
                        $('#newVersion').text(data.remote_version || 'v1.0.1');
                        $('#updateSize').text(data.update_size || '未知');
                        $('#updateTime').text(data.update_time || '刚刚');
                        $('#updateLog').text(data.update_log || '1. 优化系统性能\n2. 修复已知问题\n3. 新增功能模块');
                        alert('发现新版本: ' + data.remote_version);
                    } else {
                        alert(data.message || '当前已是最新版本');
                        $('#updateInfo').hide();
                    }
                } else {
                    alert(data.message || '检查更新失败');
                }
            },
            error: function(xhr, status, error) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                console.error('AJAX Error:', status, error);
                console.error('Response:', xhr.responseText);
                alert('操作失败: ' + status + ' - ' + error);
            }
        });
    }
    
    function startUpdate(btn) {
        var $btn = $(btn);
        var originalText = $btn.html();
        
        // 检查是否有下载地址
        if(!updateDownloadUrl) {
            alert('请先点击"检查更新"按钮获取更新信息');
            return;
        }
        
        $btn.addClass('btn-loading').prop('disabled', true);
        
        $('#updateProgress').show();
        $('#updateInfo').hide();
        $('#rollbackSection').hide();
        $('#updateOutput').html('');
        
        // 阶段名称
        var stageNames = [
            '创建备份',
            '下载更新包',
            '更新数据库',
            '更新文件',
            '完成更新'
        ];
        
        // 阶段切换函数
        function updateStage(stage) {
            // 重置所有阶段
            for (var i = 1; i <= 5; i++) {
                $('#stage' + i).css({'background': '#f5f5f5', 'color': '#999', 'font-weight': 'normal'});
            }
            
            // 设置当前阶段及之前的阶段为完成状态
            for (var i = 1; i <= stage; i++) {
                if (i < stage) {
                    // 已完成的阶段
                    $('#stage' + i).css({'background': '#e8f5e9', 'color': '#2e7d32', 'font-weight': 'bold'});
                } else {
                    // 当前阶段
                    $('#stage' + i).css({'background': '#e3f2fd', 'color': '#1976d2', 'font-weight': 'bold'});
                }
            }
            
            // 更新标题
            $('#progressTitle').text('正在' + stageNames[stage - 1] + '...');

            // 更新进度条
            var progress = Math.round((stage / 5) * 100);
            $('#progressBar').css('width', progress + '%');
        }
        
        // 添加日志输出
        function addLog(message) {
            var time = new Date().toLocaleTimeString();
            $('#updateOutput').append('[' + time + '] ' + message + '<br>');
            $('#updateOutput').scrollTop($('#updateOutput')[0].scrollHeight);
        }
        
        // 执行升级步骤
        var currentStep = 'backup';
        var steps = ['backup', 'download', 'database', 'files', 'complete'];
        var stepIndex = 0;
        
        function executeStep() {
            if (stepIndex >= steps.length) {
                return;
            }
            
            var step = steps[stepIndex];
            updateStage(stepIndex + 1);
            addLog('🔄 开始' + stageNames[stepIndex] + '...');
            
            $.ajax({
                type: 'POST',
                url: 'upgrade_handler.php',
                data: {
                    action: step,
                    download_url: updateDownloadUrl
                },
                dataType: 'json',
                success: function(data) {
                    if(data.code == 200) {
                        addLog('✅ ' + data.message);
                        
                        // 显示详细日志
                        if(data.log && data.log.length > 0) {
                            data.log.forEach(function(logMsg) {
                                addLog('   ' + logMsg);
                            });
                        }
                        
                        if(data.completed) {
                            // 升级完成
                            $('#stage5').css({'background': '#e8f5e9', 'color': '#2e7d32'});
                            $('#stage5').html('<i class="fas fa-check-circle"></i> 完成');
                            $('#progressIcon').removeClass('fa-spinner fa-spin').addClass('fa-check-circle');
                            $('#progressTitle').text('更新完成！');
                            $('#progressBar').css('width', '100%');
                            
                            addLog('🎉 系统更新成功！');
                            addLog('🔄 页面将在3秒后自动刷新...');
                            
                            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                            
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        } else {
                            // 继续下一步
                            stepIndex++;
                            executeStep();
                        }
                    } else {
                        // 步骤失败
                        showError(data.message || '更新失败');
                    }
                },
                error: function(xhr, status, error) {
                    showError('请求失败: ' + status);
                }
            });
        }
        
        function showError(message) {
            // 显示错误状态
            for (var i = 1; i <= 5; i++) {
                $('#stage' + i).css({'background': '#ffebee', 'color': '#c62828'});
            }
            $('#progressIcon').removeClass('fa-spinner fa-spin').addClass('fa-exclamation-circle');
            $('#progressTitle').text('更新失败');
            
            addLog('❌ ' + message);
            
            // 显示回滚按钮
            $('#rollbackSection').show();
            
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            alert(message);
        }
        
        // 开始执行
        executeStep();
    }
    
    // 回滚功能
    function rollbackUpdate() {
        if(!confirm('确定要回滚到更新前的状态吗？这将恢复所有文件和数据库。')) {
            return;
        }
        
        $('#progressIcon').removeClass('fa-exclamation-circle').addClass('fa-spinner fa-spin');
        $('#progressTitle').text('正在回滚...');
        addLog('🔄 开始回滚操作...');
        
        $.ajax({
            type: 'POST',
            url: 'upgrade_handler.php',
            data: {action: 'rollback'},
            dataType: 'json',
            success: function(data) {
                if(data.code == 200) {
                    addLog('✅ ' + data.message);
                    
                    if(data.log && data.log.length > 0) {
                        data.log.forEach(function(logMsg) {
                            addLog('   ' + logMsg);
                        });
                    }
                    
                    $('#progressTitle').text('回滚完成！');
                    $('#progressIcon').removeClass('fa-spinner fa-spin').addClass('fa-check-circle');
                    
                    alert('回滚成功！页面将刷新。');
                    location.reload();
                } else {
                    addLog('❌ 回滚失败: ' + data.message);
                    alert('回滚失败: ' + data.message);
                }
            },
            error: function(xhr, status, error) {
                addLog('❌ 回滚请求失败: ' + status);
                alert('回滚请求失败');
            }
        });
    }
    
    // 系统修复功能 - 强制重新下载并安装最新更新包
    function repairSystem(btn) {
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.addClass('btn-loading').prop('disabled', true);
        
        // 先检查更新获取下载地址
        $.ajax({
            type: 'POST',
            url: 'ajax.php?v=' + new Date().getTime(),
            data: {egn: 'checkupdate'},
            dataType: 'json',
            success: function(data) {
                if(data.code == 200 && data.download_url) {
                    // 直接开始修复（重新安装）
                    if(confirm('确定要执行系统修复吗？这将重新下载并安装最新更新包。')) {
                        $('#updateProgress').show();
                        $('#updateInfo').hide();
                        $('#rollbackSection').hide();
                        $('#updateOutput').html('');
                        
                        // 阶段名称
                        var stageNames = [
                            '创建备份',
                            '下载更新包',
                            '更新数据库',
                            '更新文件',
                            '完成修复'
                        ];
                        
                        // 阶段切换函数
                        function updateStage(stage) {
                            for (var i = 1; i <= 5; i++) {
                                $('#stage' + i).css({'background': '#f5f5f5', 'color': '#999', 'font-weight': 'normal'});
                            }

                            for (var i = 1; i <= stage; i++) {
                                if (i < stage) {
                                    $('#stage' + i).css({'background': '#e8f5e9', 'color': '#2e7d32', 'font-weight': 'bold'});
                                } else {
                                    $('#stage' + i).css({'background': '#e3f2fd', 'color': '#1976d2', 'font-weight': 'bold'});
                                }
                            }

                            $('#progressTitle').text('正在' + stageNames[stage - 1] + '...');
                            var progress = Math.round((stage / 5) * 100);
                            $('#progressBar').css('width', progress + '%');
                        }
                        
                        // 添加日志输出
                        function addLog(message) {
                            var time = new Date().toLocaleTimeString();
                            $('#updateOutput').append('[' + time + '] ' + message + '<br>');
                            $('#updateOutput').scrollTop($('#updateOutput')[0].scrollHeight);
                        }
                        
                        addLog('🔧 开始系统修复...');
                        
                        // 执行修复步骤
                        var steps = ['backup', 'download', 'database', 'files', 'complete'];
                        var stepIndex = 0;
                        
                        function executeStep() {
                            if (stepIndex >= steps.length) {
                                return;
                            }
                            
                            var step = steps[stepIndex];
                            updateStage(stepIndex + 1);
                            addLog('🔄 开始' + stageNames[stepIndex] + '...');
                            
                            $.ajax({
                                type: 'POST',
                                url: 'upgrade_handler.php',
                                data: {
                                    action: step,
                                    download_url: data.download_url,
                                    repair: 1
                                },
                                dataType: 'json',
                                success: function(result) {
                                    if(result.code == 200) {
                                        addLog('✅ ' + result.message);
                                        
                                        if(result.log && result.log.length > 0) {
                                            result.log.forEach(function(logMsg) {
                                                addLog('   ' + logMsg);
                                            });
                                        }
                                        
                                        if(result.completed) {
                                            $('#stage5').css({'background': '#e8f5e9', 'color': '#2e7d32'});
                                            $('#stage5').html('<i class="fas fa-check-circle"></i> 完成');
                                            $('#progressIcon').removeClass('fa-spinner fa-spin').addClass('fa-check-circle');
                                            $('#progressTitle').text('修复完成！');
                                            $('#progressBar').css('width', '100%');
                                            
                                            addLog('🎉 系统修复成功！');
                                            addLog('🔄 页面将在3秒后自动刷新...');
                                            
                                            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                                            
                                            setTimeout(function() {
                                                location.reload();
                                            }, 3000);
                                        } else {
                                            stepIndex++;
                                            executeStep();
                                        }
                                    } else {
                                        showError(result.message || '修复失败');
                                    }
                                },
                                error: function(xhr, status, error) {
                                    showError('请求失败: ' + status);
                                }
                            });
                        }
                        
                        function showError(message) {
                            for (var i = 1; i <= 5; i++) {
                                $('#stage' + i).css({'background': '#ffebee', 'color': '#c62828'});
                            }
                            $('#progressIcon').removeClass('fa-spinner fa-spin').addClass('fa-exclamation-circle');
                            $('#progressTitle').text('修复失败');
                            
                            addLog('❌ ' + message);
                            $('#rollbackSection').show();
                            
                            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                            alert(message);
                        }
                        
                        executeStep();
                    } else {
                        $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    }
                } else {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert(data.message || '获取更新信息失败，请检查网络连接');
                }
            },
            error: function(xhr, status, error) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                console.error('AJAX Error:', status, error);
                alert('操作失败: ' + status + ' - ' + error);
            }
        });
    }
    
    // 数据库表检查功能
    function checkDbTables(btn) {
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.addClass('btn-loading').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 检查中...');
        
        $('#dbCheckResult').show();
        $('#dbCheckContent').html('<div style="text-align:center;padding:20px;"><i class="fas fa-spinner fa-spin"></i> 正在检查数据库表...</div>');
        $('#repairDbBtn').hide();
        $('#deleteExtraBtn').hide();
        window.extraTables = [];
        
        $.ajax({
            type: 'POST',
            url: 'db_table_check.php?t=' + new Date().getTime(),
            data: {action: 'check'},
            dataType: 'json',
            cache: false,
            xhrFields: {
                withCredentials: true
            },
            success: function(data) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                
                if(data.code == 200) {
                    var html = '<div style="margin-bottom:15px;">';
                    html += '<p><strong>SQL文件数量:</strong> ' + data.sql_count + '</p>';
                    html += '<p><strong>数据库表数量:</strong> ' + data.db_count + '</p>';
                    html += '<p><strong>检查结果:</strong> ' + (data.has_differences ? '<span style="color:#c62828;">发现差异</span>' : '<span style="color:#2e7d32;">一致</span>') + '</p>';
                    html += '</div>';
                    
                    if(data.missing_in_db && data.missing_in_db.length > 0) {
                        html += '<div style="background:#ffebee;padding:10px;border-radius:4px;margin-bottom:10px;">';
                        html += '<h5 style="color:#c62828;margin-bottom:8px;"><i class="fas fa-exclamation-triangle"></i> 数据库缺少的表 (' + data.missing_in_db.length + '个)</h5>';
                        html += '<ul style="margin:0;padding-left:20px;color:#c62828;">';
                        data.missing_in_db.forEach(function(table) {
                            html += '<li>' + table + '</li>';
                        });
                        html += '</ul></div>';
                    }
                    
                    if(data.extra_in_db && data.extra_in_db.length > 0) {
                        html += '<div style="background:#fff3e0;padding:10px;border-radius:4px;margin-bottom:10px;">';
                        html += '<h5 style="color:#e65100;margin-bottom:8px;"><i class="fas fa-info-circle"></i> 数据库多余的表 (' + data.extra_in_db.length + '个)</h5>';
                        html += '<ul style="margin:0;padding-left:20px;color:#e65100;">';
                        data.extra_in_db.forEach(function(table) {
                            html += '<li>' + table + '</li>';
                        });
                        html += '</ul></div>';
                        window.extraTables = data.extra_in_db;
                    }
                    
                    if(data.table_differences && Object.keys(data.table_differences).length > 0) {
                        html += '<div style="background:#fff8e1;padding:10px;border-radius:4px;margin-bottom:10px;">';
                        html += '<h5 style="color:#f57f17;margin-bottom:8px;"><i class="fas fa-columns"></i> 字段差异的表</h5>';
                        for(var table in data.table_differences) {
                            html += '<p style="margin:5px 0;"><strong>' + table + ':</strong> 缺少字段 ' + data.table_differences[table].join(', ') + '</p>';
                        }
                        html += '</div>';
                    }
                    
                    $('#dbCheckContent').html(html);
                    
                    if(data.has_differences) {
                        $('#repairDbBtn').show();
                    }
                    if(data.extra_in_db && data.extra_in_db.length > 0) {
                        $('#deleteExtraBtn').show();
                    }
                } else if(data.code == 401) {
                    var debugHtml = '<div style="color:#c62828;"><i class="fas fa-exclamation-circle"></i> 登录状态已过期，请刷新页面后重试';
                    if(data.debug) {
                        debugHtml += '<br><small style="color:#666;">调试信息: ' + JSON.stringify(data.debug) + '</small>';
                    }
                    debugHtml += '</div>';
                    $('#dbCheckContent').html(debugHtml);
                } else {
                    $('#dbCheckContent').html('<div style="color:#c62828;"><i class="fas fa-exclamation-circle"></i> 检查失败: ' + data.message + '</div>');
                }
            },
            error: function(xhr, status, error) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                var errorMsg = '请求失败: ' + status;
                if (xhr.responseText) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        errorMsg += '<br>详细信息: ' + (resp.message || resp.debug ? JSON.stringify(resp.debug || resp.message) : xhr.responseText.substring(0, 200));
                    } catch(e) {
                        errorMsg += '<br>响应: ' + xhr.responseText.substring(0, 200);
                    }
                }
                if (xhr.status) {
                    errorMsg += '<br>HTTP状态: ' + xhr.status;
                }
                if (error) {
                    errorMsg += '<br>错误: ' + error;
                }
                $('#dbCheckContent').html('<div style="color:#c62828;"><i class="fas fa-exclamation-circle"></i> ' + errorMsg + '</div>');
            }
        });
    }
    
    // 修复数据库表
    function repairDbTables(btn) {
        if(!confirm('确定要修复数据库表吗？这将根据安装目录的SQL文件创建缺失的表和字段。')) {
            return;
        }
        
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.addClass('btn-loading').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 修复中...');
        
        $('#dbCheckContent').append('<div style="margin-top:10px;padding:10px;background:#e3f2fd;border-radius:4px;"><i class="fas fa-spinner fa-spin"></i> 正在修复数据库表...</div>');
        
        $.ajax({
            type: 'POST',
            url: 'db_table_check.php?t=' + new Date().getTime(),
            data: {action: 'repair'},
            dataType: 'json',
            cache: false,
            xhrFields: {
                withCredentials: true
            },
            success: function(data) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                
                if(data.code == 200) {
                    var html = '<div style="margin-top:15px;padding:15px;background:#e8f5e9;border-radius:4px;">';
                    html += '<h5 style="color:#2e7d32;margin-bottom:10px;"><i class="fas fa-check-circle"></i> 修复完成</h5>';
                    html += '<p style="color:#2e7d32;">' + data.message + '</p>';
                    
                    if(data.repaired && data.repaired.length > 0) {
                        html += '<p style="margin-top:10px;"><strong>修复项:</strong></p>';
                        html += '<ul style="margin:0;padding-left:20px;">';
                        data.repaired.forEach(function(item) {
                            html += '<li>' + item + '</li>';
                        });
                        html += '</ul>';
                    }
                    
                    if(data.errors && data.errors.length > 0) {
                        html += '<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;">';
                        html += '<p style="color:#c62828;"><strong>错误:</strong></p>';
                        html += '<ul style="margin:0;padding-left:20px;color:#c62828;">';
                        data.errors.forEach(function(error) {
                            html += '<li>' + error + '</li>';
                        });
                        html += '</ul></div>';
                    }
                    
                    html += '</div>';
                    $('#dbCheckContent').append(html);
                    $('#repairDbBtn').hide();
                } else {
                    $('#dbCheckContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;color:#c62828;"><i class="fas fa-exclamation-circle"></i> 修复失败: ' + data.message + '</div>');
                }
            },
            error: function(xhr, status, error) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                var errorMsg = '请求失败: ' + status;
                if (xhr.responseText) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        errorMsg += '<br>详细信息: ' + (resp.message || resp.debug ? JSON.stringify(resp.debug || resp.message) : xhr.responseText.substring(0, 200));
                    } catch(e) {
                        errorMsg += '<br>响应: ' + xhr.responseText.substring(0, 200);
                    }
                }
                if (xhr.status) {
                    errorMsg += '<br>HTTP状态: ' + xhr.status;
                }
                if (error) {
                    errorMsg += '<br>错误: ' + error;
                }
                $('#dbCheckContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;color:#c62828;"><i class="fas fa-exclamation-circle"></i> ' + errorMsg + '</div>');
            }
        });
    }
    
    // 删除多余的表
    function deleteExtraTables(btn) {
        var tablesToDelete = window.extraTables;
        if(!tablesToDelete || tablesToDelete.length === 0) {
            alert('没有需要删除的表');
            return;
        }
        
        if(!confirm('确定要删除这些多余的表吗？\n\n删除的表：' + tablesToDelete.join(', ') + '\n\n此操作不可恢复！请谨慎操作！')) {
            return;
        }
        
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.addClass('btn-loading').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 删除中...');
        
        $('#dbCheckContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;"><i class="fas fa-spinner fa-spin"></i> 正在删除多余的表...</div>');
        
        $.ajax({
            type: 'POST',
            url: 'db_table_check.php?t=' + new Date().getTime(),
            data: {action: 'delete_extra', tables: JSON.stringify(tablesToDelete)},
            dataType: 'json',
            cache: false,
            xhrFields: {
                withCredentials: true
            },
            success: function(data) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                
                if(data.code == 200) {
                    var html = '<div style="margin-top:15px;padding:15px;background:#e8f5e9;border-radius:4px;">';
                    html += '<h5 style="color:#2e7d32;margin-bottom:10px;"><i class="fas fa-check-circle"></i> 删除完成</h5>';
                    html += '<p style="color:#2e7d32;">' + data.message + '</p>';
                    
                    if(data.deleted && data.deleted.length > 0) {
                        html += '<p style="margin-top:10px;"><strong>已删除:</strong></p>';
                        html += '<ul style="margin:0;padding-left:20px;">';
                        data.deleted.forEach(function(item) {
                            html += '<li>' + item + '</li>';
                        });
                        html += '</ul>';
                    }
                    
                    if(data.errors && data.errors.length > 0) {
                        html += '<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;">';
                        html += '<p style="color:#c62828;"><strong>错误:</strong></p>';
                        html += '<ul style="margin:0;padding-left:20px;color:#c62828;">';
                        data.errors.forEach(function(error) {
                            html += '<li>' + error + '</li>';
                        });
                        html += '</ul></div>';
                    }
                    
                    html += '</div>';
                    $('#dbCheckContent').append(html);
                    $('#deleteExtraBtn').hide();
                    
                    if(data.deleted.length === tablesToDelete.length) {
                        window.extraTables = [];
                    }
                } else {
                    $('#dbCheckContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;color:#c62828;"><i class="fas fa-exclamation-circle"></i> 删除失败: ' + data.message + '</div>');
                }
            },
            error: function(xhr, status, error) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                var errorMsg = '请求失败: ' + status;
                if (xhr.responseText) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        errorMsg += '<br>详细信息: ' + (resp.message || resp.debug ? JSON.stringify(resp.debug || resp.message) : xhr.responseText.substring(0, 200));
                    } catch(e) {
                        errorMsg += '<br>响应: ' + xhr.responseText.substring(0, 200);
                    }
                }
                if (xhr.status) {
                    errorMsg += '<br>HTTP状态: ' + xhr.status;
                }
                if (error) {
                    errorMsg += '<br>错误: ' + error;
                }
                $('#dbCheckContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;color:#c62828;"><i class="fas fa-exclamation-circle"></i> ' + errorMsg + '</div>');
            }
        });
    }
    
    // 心跳机制 - 每5秒发送一次心跳维持在线状态
    function sendHeartbeat() {
        $.ajax({
            type: 'POST',
            url: 'heartbeat.php',
            dataType: 'json',
            success: function(data) {
                // 心跳请求完成
            },
            error: function() {
                // 心跳请求失败
            }
        });
    }
    
    // 页面加载后立即发送一次心跳
    sendHeartbeat();
    
    // 每 5 秒发送一次心跳
    setInterval(sendHeartbeat, 5000);
    
    // 清理旧文件功能
    function cleanOldFiles(btn) {
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.addClass('btn-loading').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 扫描中...');

        // 创建结果显示区域
        var resultDiv = $('<div id="cleanFilesResult" style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e8eaed;"></div>');
        resultDiv.html('<h4 style="margin-bottom: 15px; color: #333;"><i class="fas fa-search"></i> 扫描非项目文件</h4><div id="cleanFilesContent"><div style="text-align:center;padding:20px;"><i class="fas fa-spinner fa-spin"></i> 正在扫描文件...</div></div>');

        // 如果已存在则移除旧的结果
        $('#cleanFilesResult').remove();
        $('.form-group').first().after(resultDiv);

        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {egn: 'clean_old_files'},
            dataType: 'json',
            cache: false,
            success: function(data) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);

                if(data.code == 1) {
                    var html = '<div style="margin-bottom:15px;">';
                    html += '<p><strong>扫描路径:</strong> ' + data.scanned_path + '</p>';
                    html += '<p><strong>排除路径:</strong> ' + (data.excluded_paths ? data.excluded_paths.join(', ') : '无') + '</p>';
                    html += '<p><strong>项目文件数:</strong> ' + data.project_files_count + '</p>';
                    html += '<p><strong>发现的非项目文件/文件夹:</strong> <span style="color:#c62828;">' + data.found_items.length + '</span></p>';
                    html += '</div>';

                    if(data.found_items.length > 0) {
                        html += '<div style="background:#fff3e0;padding:10px;border-radius:4px;margin-bottom:10px;">';
                        html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">';
                        html += '<h5 style="color:#e65100;margin:0;"><i class="fas fa-exclamation-circle"></i> 选择要删除的文件/文件夹</h5>';
                        html += '<label style="cursor:pointer;font-size:12px;color:#666;"><input type="checkbox" id="selectAllFiles" checked> 全选/取消全选</label>';
                        html += '</div>';
                        html += '<div style="max-height:300px;overflow-y:auto;background:#fff;padding:10px;border-radius:4px;border:1px solid #ffe0b2;">';
                        html += '<div id="filesList">';
                        data.found_items.forEach(function(item, index) {
                            html += '<label style="display:block;padding:5px 0;cursor:pointer;font-size:12px;color:#e65100;">';
                            html += '<input type="checkbox" class="file-checkbox" value="' + item + '" checked style="margin-right:8px;"> ';
                            html += item;
                            html += '</label>';
                        });
                        html += '</div></div></div>';

                        html += '<div style="background:#ffebee;padding:10px;border-radius:4px;margin-bottom:15px;">';
                        html += '<p style="color:#c62828;margin:0;"><i class="fas fa-exclamation-triangle"></i> <strong>警告：</strong>此操作不可恢复！请勾选需要删除的文件后确认。</p>';
                        html += '</div>';

                        html += '<div style="display:flex;gap:10px;flex-wrap:wrap;">';
                        html += '<button class="btn btn-danger" onclick="confirmDeleteOldFiles(this)"><i class="fas fa-trash-alt"></i> 删除选中文件</button>';
                        html += '<button class="btn btn-secondary" onclick="$(\'#cleanFilesResult\').remove()"><i class="fas fa-times"></i> 取消</button>';
                        html += '</div>';

                        // 保存所有待删除列表
                        window.allFilesToDelete = data.found_items;
                    } else {
                        html += '<div style="background:#e8f5e9;padding:10px;border-radius:4px;">';
                        html += '<p style="color:#2e7d32;margin:0;"><i class="fas fa-check-circle"></i> 没有发现非项目文件，系统很干净！</p>';
                        html += '</div>';
                    }

                    $('#cleanFilesContent').html(html);

                    // 绑定全选/取消全选事件
                    $('#selectAllFiles').on('change', function() {
                        $('.file-checkbox').prop('checked', $(this).is(':checked'));
                    });
                } else {
                    $('#cleanFilesContent').html('<div style="color:#c62828;"><i class="fas fa-exclamation-circle"></i> 扫描失败: ' + (data.msg || data.message || '未知错误') + '</div>');
                }
            },
            error: function(xhr, status, error) {
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                var errorMsg = '请求失败: ' + status;
                if (xhr.responseText) {
                    errorMsg += '<br>详细信息: ' + xhr.responseText.substring(0, 200);
                }
                $('#cleanFilesContent').html('<div style="color:#c62828;"><i class="fas fa-exclamation-circle"></i> ' + errorMsg + '</div>');
            }
        });
    }

    // 确认删除旧文件
    function confirmDeleteOldFiles(btn) {
        // 获取选中的文件
        var selectedFiles = [];
        $('.file-checkbox:checked').each(function() {
            selectedFiles.push($(this).val());
        });

        if(selectedFiles.length === 0) {
            alert('请选择要删除的文件');
            return;
        }

        if(!confirm('确定要删除选中的文件/文件夹吗？\n\n删除数量: ' + selectedFiles.length + '个\n\n此操作不可恢复！')) {
            return;
        }

        var $btn = $(btn);
        $btn.addClass('btn-loading').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 删除中...');

        $('#cleanFilesContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;"><i class="fas fa-spinner fa-spin"></i> 正在删除文件...</div>');

        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: {egn: 'confirm_delete_files', files: JSON.stringify(selectedFiles)},
            dataType: 'json',
            cache: false,
            success: function(data) {
                $btn.removeClass('btn-loading').prop('disabled', false).html('<i class="fas fa-trash-alt"></i> 删除选中文件');
                
                if(data.code == 1) {
                    var html = '<div style="margin-top:15px;padding:15px;background:#e8f5e9;border-radius:4px;">';
                    html += '<h5 style="color:#2e7d32;margin-bottom:10px;"><i class="fas fa-check-circle"></i> 删除完成</h5>';
                    html += '<p style="color:#2e7d32;">' + data.message + '</p>';
                    
                    if(data.deleted && data.deleted.length > 0) {
                        html += '<p style="margin-top:10px;"><strong>已删除:</strong></p>';
                        html += '<ul style="margin:0;padding-left:20px;font-size:12px;max-height:200px;overflow-y:auto;">';
                        data.deleted.forEach(function(item) {
                            html += '<li>' + item + '</li>';
                        });
                        html += '</ul>';
                    }
                    
                    if(data.failed && data.failed.length > 0) {
                        html += '<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;">';
                        html += '<p style="color:#c62828;"><strong>删除失败:</strong></p>';
                        html += '<ul style="margin:0;padding-left:20px;color:#c62828;font-size:12px;">';
                        data.failed.forEach(function(item) {
                            html += '<li>' + item.path + ': ' + item.error + '</li>';
                        });
                        html += '</ul></div>';
                    }
                    
                    html += '</div>';
                    $('#cleanFilesContent').append(html);
                    $btn.hide();
                } else {
                    $('#cleanFilesContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;color:#c62828;"><i class="fas fa-exclamation-circle"></i> 删除失败: ' + data.message + '</div>');
                }
            },
            error: function(xhr, status, error) {
                $btn.removeClass('btn-loading').prop('disabled', false).html('<i class="fas fa-trash"></i> 确认删除');
                var errorMsg = '请求失败: ' + status;
                if (xhr.responseText) {
                    errorMsg += '<br>详细信息: ' + xhr.responseText.substring(0, 200);
                }
                $('#cleanFilesContent').append('<div style="margin-top:10px;padding:10px;background:#ffebee;border-radius:4px;color:#c62828;"><i class="fas fa-exclamation-circle"></i> ' + errorMsg + '</div>');
            }
        });
    }
    </script>
    <!-- 页面生成时间：<?php echo time(); ?> -->
</body>
</html>
