<?php
$title = '在线更新';
include __DIR__ . '/head.php';

$auth_config = include ROOT . 'includes/Auth.php';
$current_version = $auth_config['app_version'] ?? '1.0';
$app_name = $auth_config['app_name'] ?? '小韭菜';
$app_author = $auth_config['app_author'] ?? 'QingJiu';
$app_qq = $auth_config['app_qq'] ?? '';
?>
<div class="p-4 md:p-3">
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <h2 class="text-xl font-semibold text-gray-800 mb-6">系统信息</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="flex items-center py-3 border-b border-gray-100">
                <span class="text-gray-500 w-24">程序名称</span>
                <span class="text-gray-800 font-medium"><?php echo $app_name; ?></span>
            </div>
            <div class="flex items-center py-3 border-b border-gray-100">
                <span class="text-gray-500 w-24">当前版本</span>
                <span class="text-gray-800 font-medium">V <?php echo $current_version; ?></span>
            </div>
        </div>
        
        <div class="mt-6 flex flex-wrap gap-2">
          <button id="check_update" class="inline-flex items-center justify-center h-9 px-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors w-[110px] text-sm">
              <i class="fas fa-sync-alt mr-1"></i>检测更新
          </button>
          <button id="check_auth" class="inline-flex items-center justify-center h-9 px-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors w-[110px] text-sm">
              <i class="fas fa-shield-alt mr-1"></i>检测授权
          </button>
          <button id="renew_auth" class="inline-flex items-center justify-center h-9 px-3 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors w-[110px] text-sm">
              <i class="fas fa-key mr-1"></i>续费授权
          </button>
          <button id="check_schema" class="inline-flex items-center justify-center h-9 px-3 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600 transition-colors w-[110px] text-sm">
              <i class="fas fa-database mr-1"></i>校验数据
          </button>
      </div>
    </div>
    
    <div id="result" class="hidden bg-white rounded-xl shadow-sm p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">检测结果</h3>
        <div id="result_content"></div>
    </div>

    <div id="version_log" class="hidden bg-white rounded-xl shadow-sm p-6 mt-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">更新日志</h3>
        <div id="version_log_content" class="space-y-4 max-h-96 overflow-y-auto"></div>
    </div>

    <div id="update_panel" class="hidden bg-white rounded-xl shadow-sm p-6 mt-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">更新提示</h3>
        <div id="update_content"></div>
        <div id="update_progress" class="hidden mt-4">
            <div class="flex items-center mb-2">
                <span id="progress_status"></span>
                <span id="progress_text" class="text-sm text-gray-600"></span>
            </div>
            <div class="bg-gray-200 rounded-full h-3 overflow-hidden">
                <div id="progress_bar" class="bg-gradient-to-r from-blue-500 to-indigo-500 h-3 rounded-full transition-all duration-500" style="width: 0%"></div>
            </div>
            <div class="flex justify-between text-xs text-gray-400 mt-1">
                <span>0%</span>
                <span>下载</span>
                <span>解压</span>
                <span>安装</span>
                <span>100%</span>
            </div>
        </div>
    </div>

    <div id="schema_modal" class="fixed inset-0 z-50 hidden">
        <div class="fixed inset-0 bg-black/50 transition-opacity" onclick="closeSchemaModal()"></div>
        <div class="fixed inset-0 flex items-center justify-center p-4">
            <div class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col relative transform transition-all">
                <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100">
                    <h3 class="text-lg font-semibold text-gray-800">数据库校验</h3>
                    <button onclick="closeSchemaModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="px-5 py-4 overflow-y-auto">
                    <div id="schema_content"></div>
                </div>
                <div class="px-5 py-3 border-t border-gray-100 text-right">
                    <button onclick="closeSchemaModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">
                        关闭
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div id="plugin_download" class="bg-white rounded-xl shadow-sm p-6 mt-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">插件下载</h3>
        <div class="p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <p class="text-gray-700 mb-2"><i class="fas fa-plug mr-2 text-blue-500"></i>插件下载地址：</p>
            <p class="text-gray-800 font-medium mb-2 break-all">
                <a href="https://wwayq.lanzouq.com/b0fq85wtg" target="_blank" class="text-blue-600 hover:text-blue-700 underline">https://wwayq.lanzouq.com/b0fq85wtg</a>
            </p>
            <p class="text-gray-700">密码：<span class="font-medium text-gray-800">1uul</span></p>
            <p class="text-gray-500 text-sm mt-2">（目前只支持 dulu）</p>
        </div>
    </div>

    <!-- 右侧悬浮按钮 -->
    <div class="fixed right-4 bottom-20 flex flex-col gap-2 z-40">
        <button onclick="scrollToSection('plugin_download')" class="w-10 h-10 bg-blue-500 hover:bg-blue-600 text-white rounded-full shadow-lg flex items-center justify-center transition-all hover:scale-110" title="插件下载">
            <i class="fas fa-download"></i>
        </button>
        <button onclick="scrollToSection('version_log')" class="w-10 h-10 bg-green-500 hover:bg-green-600 text-white rounded-full shadow-lg flex items-center justify-center transition-all hover:scale-110" title="更新日志">
            <i class="fas fa-history"></i>
        </button>
    </div>
    
    <!-- 续费授权弹窗 -->
    <div id="renew_modal" class="fixed inset-0 z-50 hidden">
        <div class="fixed inset-0 bg-black/50 transition-opacity" onclick="closeRenewModal()"></div>
        <div class="fixed inset-0 flex items-center justify-center p-4">
            <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col relative transform transition-all">
                <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100">
                    <h3 class="text-lg font-semibold text-gray-800">续费授权</h3>
                    <button onclick="closeRenewModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="px-5 py-4 overflow-y-auto">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">授权QQ</label>
                            <input type="text" id="renew_qq" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入授权QQ">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">授权卡密</label>
                            <input type="text" id="renew_key" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入授权卡密">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">授权域名</label>
                            <input type="text" id="renew_url" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入授权域名" value="<?php echo $_SERVER['HTTP_HOST']; ?>">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">授权邮箱</label>
                            <input type="email" id="renew_email" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入授权邮箱">
                            <button type="button" onclick="useQQEmail()" class="w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm mt-2">
                                使用QQ邮箱
                            </button>
                        </div>
                    </div>
                </div>
                <div class="px-5 py-3 border-t border-gray-100 flex gap-2">
                    <button onclick="closeRenewModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">
                        取消
                    </button>
                    <button onclick="submitRenewAuth()" id="submit_renew" class="flex-1 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg font-medium transition-colors">
                        提交
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(function() {
    setTimeout(checkUpdate, 100);
});

// 滑动到指定区块
function scrollToSection(id) {
    var element = document.getElementById(id);
    if(element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

$('#check_update').click(function() {
    checkUpdate();
});

function checkUpdate() {
    var btn = $('#check_update');
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>检测中...');
    
    $.ajax({
        url: 'ajax.php?act=check_update',
        type: 'POST',
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-2"></i>检测更新');
            $('#result').removeClass('hidden');
            
            if(res.code === 1) {
                $('#result_content').html('<div class="p-4 bg-green-50 border border-green-200 rounded-lg">' +
                    '<p class="text-green-600 font-medium">' + res.msg + '</p>' +
                    '</div>');
                $('#update_panel').removeClass('hidden');
                $('#version_log').addClass('hidden');
                var content = (res.data.content || '暂无').replace(/\n/g, '<br>');
                var downloadUrl = res.data.download_url || '';
                var newVersion = res.data.version || '';
                $('#update_content').html(
                    '<ul class="space-y-2 text-gray-600">' +
                    '<li>程序：<b>' + (res.data.appname || '小韭菜') + '</b></li>' +
                    '<li>版本：<b>V ' + newVersion + '</b></li>' +
                    '<li>发布时间：<b>' + (res.data.date || '') + '</b></li>' +
                    '</ul>' +
                    '<button id="do_update" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors mt-4" data-download-url="' + downloadUrl + '" data-new-version="' + newVersion + '">' +
                    '<i class="fas fa-download mr-2"></i>立即更新' +
                    '</button>' +
                    '<ul class="space-y-2 text-gray-600 mt-4">' +
                    '<li>更新内容：<p class="mt-1 text-gray-800">' + content + '</p></li>' +
                    '</ul>'
                );
            } else {
                $('#update_panel').addClass('hidden');
                var tip = '';
                if(res.msg === '当前已是最新版本') {
                    tip = '<p class="text-gray-500 text-sm mt-2"><i class="fas fa-info-circle mr-1"></i>如需重新更新，请修改 <code class="bg-gray-200 px-1 rounded">includes/Auth.php</code> 第3行的版本号</p>';
                    loadVersionLog();
                } else {
                    $('#version_log').addClass('hidden');
                }
                $('#result_content').html('<div class="p-4 bg-gray-50 border border-gray-200 rounded-lg">' +
                    '<p class="text-gray-600">' + res.msg + '</p>' + tip +
                    '</div>');
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-2"></i>检测更新');
            $('#result').removeClass('hidden');
            $('#result_content').html('<div class="p-4 bg-red-50 border border-red-200 rounded-lg">' +
                '<p class="text-red-600">请求失败，请稍后重试</p>' +
                '</div>');
        }
    });
}

$('#check_auth').click(function() {
    var btn = $(this);
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>检测中...');
    
    $.ajax({
        url: 'ajax.php?act=check_auth_status',
        type: 'POST',
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-shield-alt mr-2"></i>检测授权');
            $('#result').removeClass('hidden');
            
            if(res.code === 1) {
                $('#result_content').html('<div class="p-4 bg-green-50 border border-green-200 rounded-lg">' +
                    '<p class="text-green-600 font-medium">' + res.msg + '</p>' +
                    '</div>');
            } else {
                $('#result_content').html('<div class="p-4 bg-red-50 border border-red-200 rounded-lg">' +
                    '<p class="text-red-600 font-medium">' + res.msg + '</p>' +
                    '</div>');
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-shield-alt mr-2"></i>检测授权');
            $('#result').removeClass('hidden');
            $('#result_content').html('<div class="p-4 bg-red-50 border border-red-200 rounded-lg">' +
                '<p class="text-red-600">请求失败，请稍后重试</p>' +
                '</div>');
        }
    });
});

$(document).on('click', '#do_update', function() {
    if(!confirm('确定要更新吗？更新会自动下载并覆盖文件，config.php和授权文件不会被覆盖！')) {
        return;
    }
    
    var btn = $(this);
    btn.prop('disabled', true);
    
    // 获取更新信息
    var downloadUrl = btn.data('download-url');
    var newVersion = btn.data('new-version');
    
    // 显示进度面板
    $('#update_progress').removeClass('hidden');
    $('#update_content').find('.bg-red-50').remove();
    
    // 更新进度函数
    function updateProgress(percent, text, status) {
        $('#progress_bar').css('width', percent + '%');
        $('#progress_text').text(text);
        
        // 更新状态图标
        var statusIcon = '';
        if(status === 'loading') {
            statusIcon = '<i class="fas fa-spinner fa-spin text-blue-500 mr-2"></i>';
        } else if(status === 'success') {
            statusIcon = '<i class="fas fa-check-circle text-green-500 mr-2"></i>';
        } else if(status === 'error') {
            statusIcon = '<i class="fas fa-times-circle text-red-500 mr-2"></i>';
        }
        $('#progress_status').html(statusIcon);
    }
    
    // 步骤1: 下载更新包
    updateProgress(5, '正在从服务器下载更新包...', 'loading');
    btn.html('<i class="fas fa-spinner fa-spin mr-2"></i>下载中...');
    
    $.ajax({
        url: 'ajax.php?act=download_update',
        type: 'POST',
        data: { download_url: downloadUrl, new_version: newVersion },
        dataType: 'json',
        timeout: 300000,
        success: function(res) {
            if(res.code !== 1) {
                updateProgress(0, '下载失败: ' + res.msg, 'error');
                btn.html('<i class="fas fa-download mr-2"></i>立即更新');
                btn.prop('disabled', false);
                return;
            }
            
            updateProgress(40, '下载完成 (' + Math.round(res.data.file_size / 1024) + ' KB)，正在解压...', 'success');
            btn.html('<i class="fas fa-spinner fa-spin mr-2"></i>解压中...');
            
            // 步骤2: 解压更新包
            setTimeout(function() {
                $.ajax({
                    url: 'ajax.php?act=extract_update',
                    type: 'POST',
                    dataType: 'json',
                    timeout: 60000,
                    success: function(res) {
                        if(res.code !== 1) {
                            updateProgress(40, '解压失败: ' + res.msg, 'error');
                            btn.html('<i class="fas fa-download mr-2"></i>立即更新');
                            btn.prop('disabled', false);
                            return;
                        }
                        
                        updateProgress(60, '解压完成 (' + res.data.file_count + ' 个文件)，正在安装...', 'success');
                        btn.html('<i class="fas fa-spinner fa-spin mr-2"></i>安装中...');
                        
                        // 步骤3: 安装更新
                        setTimeout(function() {
                            $.ajax({
                                url: 'ajax.php?act=install_update',
                                type: 'POST',
                                data: { new_version: newVersion },
                                dataType: 'json',
                                timeout: 120000,
                                success: function(res) {
                                    if(res.code !== 1) {
                                        updateProgress(60, '安装失败: ' + res.msg, 'error');
                                        btn.html('<i class="fas fa-download mr-2"></i>立即更新');
                                        btn.prop('disabled', false);
                                        return;
                                    }
                                    
                                    updateProgress(100, '更新完成！', 'success');
                                    btn.html('<i class="fas fa-check mr-2"></i>更新完成');
                                    
                                    var info = '<div class="p-4 bg-green-50 border border-green-200 rounded-lg mt-4">' +
                                        '<p class="text-green-600 font-medium mb-2"><i class="fas fa-check-circle mr-2"></i>更新成功！</p>' +
                                        '<p class="text-gray-600 text-sm">版本：V ' + res.data.version + '</p>' +
                                        '<p class="text-gray-600 text-sm">更新文件数：' + res.data.files_copied + ' / ' + res.data.total_files + '</p>' +
                                        '<p class="text-gray-500 text-xs mt-2">备份目录：' + res.data.backup_dir + '</p>' +
                                        '</div>';
                                    
                                    $('#update_content').html(info);
                                    
                                    setTimeout(function() {
                                        alert('更新成功！即将刷新页面...');
                                        location.reload();
                                    }, 1500);
                                },
                                error: function(xhr, status) {
                                    updateProgress(60, '安装请求失败: ' + (status === 'timeout' ? '超时' : '网络错误'), 'error');
                                    btn.html('<i class="fas fa-download mr-2"></i>立即更新');
                                    btn.prop('disabled', false);
                                }
                            });
                        }, 500);
                    },
                    error: function(xhr, status) {
                        updateProgress(40, '解压请求失败: ' + (status === 'timeout' ? '超时' : '网络错误'), 'error');
                        btn.html('<i class="fas fa-download mr-2"></i>立即更新');
                        btn.prop('disabled', false);
                    }
                });
            }, 500);
        },
        error: function(xhr, status) {
            updateProgress(0, '下载请求失败: ' + (status === 'timeout' ? '超时，文件较大请重试' : '网络错误'), 'error');
            btn.html('<i class="fas fa-download mr-2"></i>立即更新');
            btn.prop('disabled', false);
        }
    });
});

// 续费授权相关
$('#renew_auth').click(function() {
    $('#renew_modal').removeClass('hidden');
    document.body.style.overflow = 'hidden';
});

function useQQEmail() {
    var qq = $('#renew_qq').val().trim();
    if (qq) {
        $('#renew_email').val(qq + '@qq.com');
    } else {
        alert('请先输入授权QQ');
    }
}

function closeRenewModal() {
    $('#renew_modal').addClass('hidden');
    document.body.style.overflow = '';
}

// 加载更新日志
function loadVersionLog() {
    $.ajax({
        url: 'ajax.php?act=get_version_list',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if(res.code === 1 && res.data && res.data.length > 0) {
                $('#version_log').removeClass('hidden');
                res.data.sort(function(a, b) {
                    return compareVersion(b.version, a.version);
                });
                var html = '';
                res.data.forEach(function(item) {
                    html += '<div class="border-l-4 border-blue-500 pl-4 py-2">' +
                        '<div class="flex items-center gap-2 mb-1">' +
                        '<span class="font-semibold text-gray-800">V ' + item.version + '</span>' +
                        '<span class="text-sm text-gray-500">' + item.add_time + '</span>' +
                        '</div>' +
                        '<div class="text-gray-600 text-sm">' + (item.content || '暂无更新说明').replace(/\n/g, '<br>') + '</div>' +
                        '</div>';
                });
                $('#version_log_content').html(html);
            } else {
                $('#version_log').addClass('hidden');
            }
        },
        error: function() {
            $('#version_log').addClass('hidden');
        }
    });
}

// 版本号比较函数
function compareVersion(v1, v2) {
    var parts1 = v1.split('.');
    var parts2 = v2.split('.');
    var len = Math.max(parts1.length, parts2.length);
    
    for(var i = 0; i < len; i++) {
        var num1 = parseInt(parts1[i]) || 0;
        var num2 = parseInt(parts2[i]) || 0;
        if(num1 > num2) return 1;
        if(num1 < num2) return -1;
    }
    return 0;
}

function submitRenewAuth() {
    var qq = $('#renew_qq').val().trim();
    var key = $('#renew_key').val().trim();
    var url = $('#renew_url').val().trim();
    var email = $('#renew_email').val().trim();
    
    if (!qq) {
        alert('请输入授权QQ');
        return;
    }
    if (!key) {
        alert('请输入授权卡密');
        return;
    }
    if (!url) {
        alert('请输入授权域名');
        return;
    }
    
    var btn = $('#submit_renew');
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>提交中...');
    
    $.ajax({
        url: 'ajax.php?act=renew_auth',
        type: 'POST',
        data: {
            qq: qq,
            key: key,
            url: url,
            email: email
        },
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('提交');
            
            if (res.code === 1) {
                alert('授权成功！');
                closeRenewModal();
                $('#check_auth').click();
            } else {
                alert('授权失败：' + (res.msg || '未知错误'));
            }
        },
        error: function() {
            btn.prop('disabled', false).html('提交');
            alert('网络请求失败，请稍后重试');
        }
    });
}

$('#check_schema').click(function() {
    checkSchema();
});

function checkSchema() {
    var btn = $('#check_schema');
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>校验中...');
    $.ajax({
        url: 'ajax.php?act=check_schema',
        type: 'POST',
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-database mr-1"></i>校验数据');
            openSchemaModal();
            if(res.code === 1) {
                renderSchemaResult(res.data);
            } else {
                $('#schema_content').html('<div class="p-4 bg-red-50 border border-red-200 rounded-lg"><p class="text-red-600 font-medium">'+(res.msg || '校验失败')+'</p></div>');
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-database mr-1"></i>校验数据');
            openSchemaModal();
            $('#schema_content').html('<div class="p-4 bg-red-50 border border-red-200 rounded-lg"><p class="text-red-600">请求失败，请稍后重试</p></div>');
        }
    });
}

function renderSchemaResult(data) {
    console.log('Schema data:', data);
    
    // 安全获取数据，避免undefined
    var summary = data.summary || {};
    var missingTables = data.missing_tables || [];
    var extraTables = data.extra_tables || [];
    var tables = data.tables || [];
    
    var totalMissingCols = summary.missing_columns_count || 0;
    var totalExtraCols = summary.extra_columns_count || 0;
    var totalMissingTables = summary.missing_tables_count || 0;
    
    // 判断是否有问题（缺失表或缺失列才算问题）
    var hasIssue = totalMissingTables > 0 || totalMissingCols > 0;
    // 判断是否有差异（包括多余列）
    var hasDiff = hasIssue || totalExtraCols > 0 || extraTables.length > 0;
    
    var html = '';
    
    // 标题区域 - 更友好的提示
    if(!hasDiff){
        html += '<div class="p-4 bg-green-50 border border-green-200 rounded-lg mb-4">';
        html += '<p class="text-green-700 font-medium"><i class="fas fa-check-circle mr-2"></i>数据库结构完整，未发现问题</p>';
        html += '</div>';
    } else if(hasIssue) {
        html += '<div class="p-4 bg-red-50 border border-red-200 rounded-lg mb-4">';
        html += '<p class="text-red-700 font-medium"><i class="fas fa-exclamation-circle mr-2"></i>发现问题：缺表 '+totalMissingTables+' 个，缺列 '+totalMissingCols+' 个</p>';
        html += '<p class="text-red-600 text-sm mt-1">建议点击下方"一键修复"按钮进行修复</p>';
        html += '</div>';
    } else {
        html += '<div class="p-4 bg-blue-50 border border-blue-200 rounded-lg mb-4">';
        html += '<p class="text-blue-700 font-medium"><i class="fas fa-info-circle mr-2"></i>检测到结构差异（不影响使用）</p>';
        html += '<p class="text-blue-600 text-sm mt-1">你的数据库可能进行了定制化扩展，多余列表示增强功能</p>';
        html += '</div>';
    }
    
    // 缺失的表（真正的问题）
    if(missingTables.length){
        html += '<div class="mb-4">';
        html += '<div class="font-semibold text-gray-800 mb-2"><i class="fas fa-exclamation-triangle text-red-500 mr-2"></i>缺少的表（需要修复）</div>';
        html += '<div class="text-sm text-gray-700 bg-red-50 p-3 rounded-lg border border-red-200">'+missingTables.join(', ')+'</div>';
        html += '</div>';
    }
    
    // 表结构详情（可折叠）
    if(tables.length){
        html += '<div class="mb-4">';
        html += '<div class="font-semibold text-gray-800 mb-2 cursor-pointer select-none" onclick="$(\'#table_detail\').toggleClass(\'hidden\')">';
        html += '<i class="fas fa-list text-gray-500 mr-2"></i>表结构详情 <i class="fas fa-chevron-down text-xs ml-1"></i></div>';
        html += '<div id="table_detail" class="bg-gray-50 p-3 rounded-lg max-h-64 overflow-y-auto">';
        
        tables.forEach(function(t){
            var tableName = t.table || '未知表';
            var missingCols = t.missing_columns || [];
            var extraCols = t.extra_columns || [];
            
            // 只显示有差异的表
            if(missingCols.length || extraCols.length){
                html += '<div class="py-2 border-b border-gray-200 last:border-0">';
                html += '<div class="font-medium text-gray-800 mb-1">' + tableName + '</div>';
                
                if(missingCols.length){
                    html += '<div class="text-sm text-red-600 mb-1"><i class="fas fa-minus-circle mr-1"></i>缺列：' + missingCols.join(', ') + '</div>';
                }
                if(extraCols.length){
                    html += '<div class="text-sm text-blue-600"><i class="fas fa-plus-circle mr-1"></i>扩展列：' + extraCols.join(', ') + '</div>';
                }
                html += '</div>';
            }
        });
        
        html += '</div></div>';
    }
    
    // 说明提示
    html += '<div class="p-3 bg-gray-100 rounded-lg text-sm text-gray-600 mb-4">';
    html += '<p class="mb-1"><strong>说明：</strong></p>';
    html += '<ul class="list-disc list-inside space-y-1">';
    html += '<li><span class="text-red-600">缺列</span>：标准字段缺失，可能影响功能，建议修复</li>';
    html += '<li><span class="text-blue-600">扩展列</span>：你的数据库有额外字段，通常表示定制化功能，不影响使用</li>';
    html += '</ul></div>';
    
    // 修复按钮（只有真正有问题时才显示）
    if(hasIssue){
        html += '<div class="flex flex-wrap gap-2">';
        html += '<button id="fix_schema" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"><i class="fas fa-tools mr-2"></i>一键修复</button>';
        html += '<button onclick="closeSchemaModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">关闭</button>';
        html += '</div>';
    } else {
        html += '<div class="text-center">';
        html += '<button onclick="closeSchemaModal()" class="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">关闭</button>';
        html += '</div>';
    }
    
    $('#schema_content').html(html);
}

$(document).on('click','#fix_schema',function(){
    fixSchema();
});

function fixSchema(){
    var container = $('#schema_content');
    var btns = $('#fix_schema, #clean_schema');
    btns.prop('disabled', true);
    $.ajax({
        url: 'ajax.php?act=fix_schema',
        type: 'POST',
        data: {},
        dataType: 'json',
        success: function(res){
            btns.prop('disabled', false);
            if(res.code === 1){
                container.prepend('<div class="p-3 mb-3 bg-green-50 border border-green-200 rounded-lg text-green-700">修复完成：'+(res.msg || '已执行')+'</div>');
                checkSchema();
            }else{
                container.prepend('<div class="p-3 mb-3 bg-red-50 border border-red-200 rounded-lg text-red-700">'+(res.msg || '修复失败')+'</div>');
            }
        },
        error: function(){
            btns.prop('disabled', false);
            container.prepend('<div class="p-3 mb-3 bg-red-50 border border-red-200 rounded-lg text-red-700">请求失败，请稍后重试</div>');
        }
    });
}

function openSchemaModal(){
    $('#schema_modal').removeClass('hidden');
    document.body.style.overflow = 'hidden';
}
function closeSchemaModal(){
    $('#schema_modal').addClass('hidden');
    document.body.style.overflow = '';
}
</script>
<?php include 'foot.php'; ?>
