<?php
ob_start();
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/header.php';
check_permission('admin');

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json; charset=utf-8');
    
    $action = $_POST['action'];
    
    if ($action === 'check_update') {
        $current_version = defined('CMS_VERSION') ? CMS_VERSION : '1.0.0';
        $api_url = defined('UPDATE_API') ? UPDATE_API . '?current_version=' . $current_version : '';
        
        if (empty($api_url)) {
            echo json_encode(['success' => false, 'message' => '未配置更新服务器地址']);
            exit;
        }
        
        $response = @file_get_contents($api_url);
        
        if ($response === false) {
            echo json_encode([
                'success' => false,
                'message' => '无法连接更新服务器，请检查网络连接'
            ]);
            exit;
        }
        
        $data = json_decode($response, true);
        
        if (!$data) {
            echo json_encode([
                'success' => false,
                'message' => '更新服务器返回数据格式错误'
            ]);
            exit;
        }
        
        echo json_encode([
            'success' => true,
            'data' => $data
        ]);
        exit;
    }
    
    if ($action === 'download_update') {
        $download_url = $_POST['download_url'] ?? '';
        $version = $_POST['version'] ?? '';
        
        if (empty($download_url) || empty($version)) {
            echo json_encode(['success' => false, 'message' => '参数错误']);
            exit;
        }
        
        $temp_dir = __DIR__ . '/../temp/update_' . $version;
        if (!is_dir($temp_dir)) {
            @mkdir($temp_dir, 0755, true);
        }
        
        $update_package = $temp_dir . '/update.zip';
        $package_content = @file_get_contents($download_url);
        
        if ($package_content === false) {
            echo json_encode(['success' => false, 'message' => '下载更新包失败']);
            exit;
        }
        
        @file_put_contents($update_package, $package_content);
        
        // 解压更新包
        if (class_exists('ZipArchive')) {
            $zip = new ZipArchive;
            if ($zip->open($update_package) === true) {
                $zip->extractTo($temp_dir . '/extracted');
                $zip->close();
                
                echo json_encode([
                    'success' => true,
                    'message' => '更新包下载并解压成功',
                    'temp_dir' => $temp_dir
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => '解压更新包失败']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '服务器不支持ZipArchive']);
        }
        exit;
    }
    
    if ($action === 'execute_update') {
        $temp_dir = $_POST['temp_dir'] ?? '';
        $version = $_POST['version'] ?? '';
        
        if (empty($temp_dir) || empty($version)) {
            echo json_encode(['success' => false, 'message' => '参数错误']);
            exit;
        }
        
        $extracted_dir = $temp_dir . '/extracted';
        if (!is_dir($extracted_dir)) {
            echo json_encode(['success' => false, 'message' => '更新包文件不存在']);
            exit;
        }
        
        $updated_files = 0;
        
        // 遍历解压后的文件，复制到系统目录
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($extracted_dir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );
        
        foreach ($iterator as $file) {
            $file_path = $file->getPathname();
            $relative_path = str_replace($extracted_dir . '/', '', $file_path);
            
            if (basename($file_path) === 'update.sql' || basename($file_path) === 'README.md') {
                continue;
            }
            
            $target_path = __DIR__ . '/../' . $relative_path;
            $target_dir = dirname($target_path);
            
            if (!is_dir($target_dir)) {
                @mkdir($target_dir, 0755, true);
            }
            
            if (@copy($file_path, $target_path)) {
                $updated_files++;
            }
        }
        
        // 执行数据库更新
        $update_sql = $extracted_dir . '/update.sql';
        if (file_exists($update_sql)) {
            $sql_content = file_get_contents($update_sql);
            $sql_commands = array_filter(array_map('trim', explode(';', $sql_content)));
            
            foreach ($sql_commands as $sql) {
                if (!empty($sql)) {
                    try {
                        $GLOBALS['pdo']->exec($sql);
                    } catch (Exception $e) {
                        // 忽略错误
                    }
                }
            }
        }
        
        // 更新版本号
        update_setting('cms_version', $version);
        
        // 记录日志
        add_log('update', 'system', '升级到版本 ' . $version . '，更新了 ' . $updated_files . ' 个文件');
        
        // 清理临时文件
        array_map('unlink', glob($temp_dir . '/*'));
        @rmdir($temp_dir);
        
        echo json_encode([
            'success' => true,
            'message' => '升级成功！更新了 ' . $updated_files . ' 个文件。',
            'version' => $version
        ]);
        exit;
    }
}

// 获取当前版本
$current_version = defined('CMS_VERSION') ? CMS_VERSION : '1.0.0';
$update_api = defined('UPDATE_API') ? UPDATE_API : '';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>一键升级 - 2026企业CMS</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .update-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 30px;
        }
        
        .current-version {
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .version-info h3 {
            margin-bottom: 5px;
        }
        
        .version-badge {
            padding: 8px 16px;
            background: #2c82e0;
            color: white;
            border-radius: 20px;
            font-size: 16px;
            font-weight: 500;
        }
        
        .check-result {
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }
        
        .check-result.has-update {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        
        .check-result.no-update {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            color: #495057;
        }
        
        .check-result.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .new-version {
            font-size: 24px;
            font-weight: 700;
            color: #28a745;
        }
        
        .update-notes {
            margin-top: 15px;
            padding: 15px;
            background: white;
            border-radius: 4px;
        }
        
        .update-notes h4 {
            margin-bottom: 10px;
        }
        
        .update-notes ul {
            padding-left: 20px;
        }
        
        .update-notes li {
            margin-bottom: 5px;
        }
        
        .progress-bar {
            height: 6px;
            background: #e9ecef;
            border-radius: 3px;
            margin: 20px 0;
            overflow: hidden;
            display: none;
        }
        
        .progress-bar .progress {
            height: 100%;
            background: #2c82e0;
            width: 0%;
            transition: width 0.3s;
        }
        
        .update-log {
            padding: 15px;
            background: #212529;
            color: #0f0;
            border-radius: 4px;
            font-family: monospace;
            font-size: 13px;
            max-height: 200px;
            overflow-y: auto;
            margin-top: 20px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <?php include 'sidebar.php'; ?>
        
        <main class="admin-content">
            <div class="page-header">
                <h1>一键升级</h1>
                <button class="btn btn-primary" id="checkBtn" onclick="checkUpdate()">检查更新</button>
            </div>
            
            <div class="update-container">
                <div class="current-version">
                    <div class="version-info">
                        <h3>当前版本</h3>
                        <p>2026企业CMS</p>
                    </div>
                    <div class="version-badge"><?php echo xss_clean($current_version); ?></div>
                </div>
                
                <div id="checkResult" class="check-result">
                    <!-- 检查结果会显示在这里 -->
                </div>
                
                <div class="progress-bar" id="progressBar">
                    <div class="progress" id="progress"></div>
                </div>
                
                <div class="update-log" id="updateLog"></div>
            </div>
        </main>
    </div>
    
    <script>
        let checkResult = null;
        
        function checkUpdate() {
            const btn = document.getElementById('checkBtn');
            btn.disabled = true;
            btn.textContent = '检查中...';
            
            const resultDiv = document.getElementById('checkResult');
            resultDiv.className = 'check-result';
            resultDiv.style.display = 'block';
            resultDiv.innerHTML = '<p>正在检查更新...</p>';
            
            const formData = new FormData();
            formData.append('action', 'check_update');
            
            fetch('', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    btn.disabled = false;
                    btn.textContent = '检查更新';
                    
                    if (data.success && data.data && data.data.has_update) {
                        checkResult = data.data;
                        resultDiv.className = 'check-result has-update';
                        resultDiv.innerHTML = `
                            <h3>发现新版本！</h3>
                            <p class="new-version">v${data.data.version}</p>
                            <p>发布时间：${data.data.release_date || '未知'}</p>
                            <div class="update-notes">
                                <h4>更新内容：</h4>
                                <ul>
                                    ${(data.data.notes || []).map(n => '<li>' + n + '</li>').join('')}
                                </ul>
                            </div>
                            <div style="margin-top: 20px;">
                                <button class="btn btn-primary" onclick="downloadUpdate()">立即升级</button>
                            </div>
                        `;
                    } else if (data.success) {
                        resultDiv.className = 'check-result no-update';
                        resultDiv.innerHTML = '<h3>已是最新版本</h3><p>当前没有可用的更新。</p>';
                    } else {
                        resultDiv.className = 'check-result error';
                        resultDiv.innerHTML = '<h3>检查失败</h3><p>' + (data.message || '未知错误') + '</p>';
                    }
                })
                .catch(err => {
                    btn.disabled = false;
                    btn.textContent = '检查更新';
                    resultDiv.className = 'check-result error';
                    resultDiv.innerHTML = '<h3>检查失败</h3><p>网络错误，请稍后重试。</p>';
                });
        }
        
        function downloadUpdate() {
            if (!checkResult) return;
            
            const resultDiv = document.getElementById('checkResult');
            resultDiv.innerHTML += '<p>正在下载更新包...</p>';
            
            const progressBar = document.getElementById('progressBar');
            progressBar.style.display = 'block';
            document.getElementById('progress').style.width = '30%';
            
            const formData = new FormData();
            formData.append('action', 'download_update');
            formData.append('download_url', checkResult.download_url || '');
            formData.append('version', checkResult.version || '');
            
            fetch('', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    document.getElementById('progress').style.width = '60%';
                    
                    if (data.success) {
                        resultDiv.innerHTML += '<p>✅ 更新包下载完成，正在执行升级...</p>';
                        executeUpdate(data.temp_dir, checkResult.version);
                    } else {
                        resultDiv.innerHTML += '<p style="color:#dc3545;">❌ 下载失败：' + (data.message || '') + '</p>';
                    }
                })
                .catch(err => {
                    resultDiv.innerHTML += '<p style="color:#dc3545;">❌ 下载失败，请重试。</p>';
                });
        }
        
        function executeUpdate(tempDir, version) {
            const formData = new FormData();
            formData.append('action', 'execute_update');
            formData.append('temp_dir', tempDir || '');
            formData.append('version', version || '');
            
            const logDiv = document.getElementById('updateLog');
            logDiv.style.display = 'block';
            logDiv.innerHTML = '> 开始执行升级...\n';
            
            fetch('', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    document.getElementById('progress').style.width = '100%';
                    
                    if (data.success) {
                        logDiv.innerHTML += '> 升级成功！\n> ' + (data.message || '') + '\n> 页面将在3秒后刷新...';
                        setTimeout(() => location.reload(), 3000);
                    } else {
                        logDiv.innerHTML += '> 升级失败：' + (data.message || '') + '\n';
                    }
                })
                .catch(err => {
                    logDiv.innerHTML += '> 升级失败，请重试。\n';
                });
        }
    </script>
</body>
</html>
<?php require_once __DIR__ . '/footer.php'; ?>
