<?php
/**
 * 管理员专用 - 系统更新
 * 访问路径: /admin.php?page=update
 */
if (!defined('IN_ADMIN')) {
    define('IN_ADMIN', true);
}
require_once __DIR__ . '/../../config.php';

// 权限检查：仅管理员可访问
if (!isAdmin()) {
    redirect(SITE_URL . 'admin.php');
}

require_once __DIR__ . '/../../includes/LicenseClient.php';

$message = '';
$error = '';
$current_version = '';

// 获取请求动作
$action = $_GET['action'] ?? '';

try {
    $client = new LicenseClient();
    $current_version = $client->getCurrentVersion();
} catch (Exception $e) {
    $error = $e->getMessage();
}

// AJAX 处理
if ($action === 'check') {
    // ... 后续代码保持不变 ...
    header('Content-Type: application/json');
    try {
        $client = new LicenseClient();
        $result = $client->checkUpdate();
        echo json_encode($result);  // 直接输出，前端通过 res.data 或 res 接收
    } catch (Exception $e) {
        echo json_encode(['has_update' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    set_time_limit(300);
    
    $to_version = $_POST['version'] ?? '';
    $download_url = $_POST['download_url'] ?? '';
    
    try {
        $client = new LicenseClient();
        $from_version = $client->getCurrentVersion();
        
        // 1. 下载更新包
        $temp_file = sys_get_temp_dir() . '/update_' . uniqid() . '.zip';
        if (!$client->downloadUpdate($download_url, $temp_file)) {
            throw new Exception('下载更新包失败，请检查网络或下载地址');
        }
        
        // 2. 解压并覆盖文件
        $zip = new ZipArchive();
        if ($zip->open($temp_file) !== true) {
            throw new Exception('无法打开更新包，文件可能已损坏');
        }
        
        $root_path = realpath(__DIR__ . '/../../');
        if (!$zip->extractTo($root_path)) {
            $zip->close();
            throw new Exception('解压失败，请检查目录写入权限');
        }
        $zip->close();
        unlink($temp_file);
        
        // 3. 执行数据库迁移
        $sql_file = $root_path . '/update.sql';
        if (file_exists($sql_file)) {
            $db = Database::getInstance();
            $sql = file_get_contents($sql_file);
            // 注意：复杂 SQL 建议拆分执行，这里简化处理
            $db->query($sql);
            unlink($sql_file);
        }
        
        // 4. 更新版本号
        $version_file = $root_path . '/version.php';
        $version_content = "<?php\nreturn ['version' => '{$to_version}', 'updated_at' => '" . date('Y-m-d H:i:s') . "'];\n";
        file_put_contents($version_file, $version_content);
        
        // 5. 上报主站
        $client->reportUpdate($from_version, $to_version, 'success');
        
        echo json_encode(['success' => true, 'message' => '系统更新成功！']);
    } catch (Exception $e) {
        if (isset($client) && isset($from_version) && isset($to_version)) {
            try { $client->reportUpdate($from_version, $to_version, 'failed'); } catch (Exception $ignored) {}
        }
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}
?>
<style>
    .alert-success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
    border-radius: 12px;
    padding: 20px;
}
.alert-success h5 {
    color: #155724;
    margin-bottom: 12px;
}
</style>
<h2>系统更新</h2>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php else: ?>
    <div class="card mb-4">
        <div class="card-body">
            <h5 class="card-title">当前版本</h5>
            <span class="badge bg-secondary fs-5"><?= htmlspecialchars($current_version) ?></span>
        </div>
    </div>
    
    <div class="card">
        <div class="card-body">
            <div id="updateStatus">
                <button class="btn btn-primary" id="checkUpdateBtn" onclick="checkUpdate()">
                    <span class="spinner-border spinner-border-sm d-none" role="status" id="checkSpinner"></span>
                    检查更新
                </button>
            </div>
            
            <div id="updateInfo" style="display:none;" class="mt-4">
                <div class="alert alert-info">
                    <h5>发现新版本：<span id="newVersion"></span></h5>
                    <p><strong>标题：</strong><span id="updateTitle"></span></p>
                    <div><strong>更新说明：</strong></div>
                    <pre id="updateDesc" class="bg-light p-3 rounded" style="white-space: pre-wrap;"></pre>
                    <div class="mt-2">
                        <span class="badge bg-warning" id="forceBadge" style="display:none;">强制更新</span>
                    </div>
                </div>
                <button class="btn btn-success" id="startUpdateBtn" onclick="startUpdate()">立即更新</button>
                <button class="btn btn-secondary" id="cancelUpdateBtn" onclick="hideUpdateInfo()">取消</button>
                <div class="progress mt-3" id="updateProgress" style="display:none;">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" style="width:100%">正在更新，请稍候...</div>
                </div>
            </div>
            <!-- 已是最新版本提示框（新增） -->
<div id="latestInfo" style="display:none;" class="mt-4">
    <div class="alert alert-success">
        <h5>✅ 当前已是最新版本</h5>
        <p>您的系统版本为 <strong id="currentVersionDisplay"><?php echo htmlspecialchars($current_version); ?></strong>，无需更新。</p>
    </div>
    <button class="btn btn-secondary" onclick="hideLatestInfo()">关闭</button>
</div>
        </div>
    </div>
<?php endif; ?>

<script>
var updateData = null;

function checkUpdate() {
    const btn = $('#checkUpdateBtn');
    const spinner = $('#checkSpinner');
    btn.prop('disabled', true);
    spinner.removeClass('d-none');
    
    $.ajax({
        url: '/update_api/check_update.php',
        method: 'GET',
        dataType: 'json',
        success: function(res) {
            $('#updateInfo').hide();
            $('#latestInfo').hide();
            $('#updateStatus').hide();
            
            if (res.has_update) {
                updateData = res;
                $('#newVersion').text(res.version);
                $('#updateTitle').text(res.title || '无标题');
                $('#updateDesc').text(res.description || '暂无更新说明');
                
                if (res.is_force) {
                    $('#forceBadge').show();
                } else {
                    $('#forceBadge').hide();
                }
                
                $('#updateInfo').show();
            } else {
                $('#latestInfo').show();
            }
        },
        error: function() {
            alert('检查更新失败，请稍后重试');
            $('#updateStatus').show();
        },
        complete: function() {
            btn.prop('disabled', false);
            spinner.addClass('d-none');
        }
    });
}

function startUpdate() {
    if (!updateData) {
        alert('请先检查更新');
        return;
    }
    
    if (!confirm('确定要更新到版本 ' + updateData.version + ' 吗？')) return;
    
    $('#startUpdateBtn').prop('disabled', true);
    $('#cancelUpdateBtn').prop('disabled', true);
    $('#updateProgress').show();
    
    $.ajax({
        url: '/update_api/do_update.php',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            version: updateData.version,
            download_url: updateData.download_url
        }),
        dataType: 'json',
        success: function(res) {
            if (res.success) {
                alert(res.message + ' 页面即将刷新。');
                setTimeout(() => location.reload(), 2000);
            } else {
                alert('更新失败：' + res.message);
                $('#startUpdateBtn').prop('disabled', false);
                $('#cancelUpdateBtn').prop('disabled', false);
                $('#updateProgress').hide();
            }
        },
        error: function() {
            alert('更新请求失败，请检查网络');
            $('#startUpdateBtn').prop('disabled', false);
            $('#cancelUpdateBtn').prop('disabled', false);
            $('#updateProgress').hide();
        }
    });
}

function hideUpdateInfo() {
    $('#updateInfo').hide();
    $('#updateStatus').show();
    updateData = null;
}

function hideLatestInfo() {
    $('#latestInfo').hide();
    $('#updateStatus').show();
}

</script>