<?php
requireAdmin();

$version = SYS_VERSION;
$updates = $db->fetchAll("SELECT * FROM updates ORDER BY id DESC");

// 处理发布更新
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'publish') {
    $new_version = trim($_POST['version'] ?? '');
    $release_notes = trim($_POST['release_notes'] ?? '');
    
    // 处理文件上传
    if (isset($_FILES['package']) && $_FILES['package']['error'] == 0) {
        $file = $_FILES['package'];
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'update_' . $new_version . '.' . $ext;
        $target = UPLOAD_DIR . 'packages/' . $filename;
        
        if (!is_dir(UPLOAD_DIR . 'packages/')) {
            mkdir(UPLOAD_DIR . 'packages/', 0755, true);
        }
        
        if (move_uploaded_file($file['tmp_name'], $target)) {
            $package_url = UPLOAD_URL . 'packages/' . $filename;
            $db->query("INSERT INTO updates (version, release_notes, package_url) VALUES ('$new_version', '$release_notes', '$package_url')");
            $success = '更新包已发布';
            $updates = $db->fetchAll("SELECT * FROM updates ORDER BY id DESC");
        } else {
            $error = '文件上传失败';
        }
    } else {
        $error = '请选择更新包文件';
    }
}
// 获取系统版本信息（从数据库读取）
$sys_version = getSiteConfig('sys_version') ?? '1.0.0';
$php_version = PHP_VERSION;
$mysql_version = $db->fetchOne("SELECT VERSION() as ver")['ver'] ?? '未知';
$server_software = $_SERVER['SERVER_SOFTWARE'] ?? '未知';

// 处理删除更新
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $db->query("DELETE FROM updates WHERE id = $id");
    redirect('?page=updates');
}
?>

<div class="updates-container">
    <div class="page-header">
        <h2>在线更新管理</h2>
        <p>当前版本：v<?php echo htmlspecialchars($sys_version); ?></p>
    </div>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <!-- 发布新版本 -->
    <div class="section-box">
        <h3>发布新版本</h3>
        <div class="form-card">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="publish">
                <div class="form-row">
                    <div class="form-group">
                        <label>版本号 *</label>
                        <input type="text" name="version" required placeholder="例如：1.0.1">
                    </div>
                </div>
                <div class="form-group">
                    <label>更新说明</label>
                    <textarea name="release_notes" rows="4" placeholder="描述本次更新的内容..."></textarea>
                </div>
                <div class="form-group">
                    <label>更新包文件 *</label>
                    <input type="file" name="package" required accept=".zip,.rar,.tar.gz">
                    <small>支持ZIP、RAR等压缩包格式</small>
                </div>
                <button type="submit" class="btn btn-primary">发布更新</button>
            </form>
        </div>
    </div>
    
    <!-- 历史版本列表 -->
    <div class="section-box">
        <h3>历史版本</h3>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>版本</th>
                        <th>更新说明</th>
                        <th>发布时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($updates)): ?>
                        <tr><td colspan="4" style="text-align: center;">暂无历史版本</td></tr>
                    <?php else: ?>
                        <?php foreach ($updates as $update): ?>
                            <tr>
                                <td><strong>v<?php echo htmlspecialchars($update['version']); ?></strong></td>
                                <td><?php echo nl2br(htmlspecialchars($update['release_notes'])); ?></td>
                                <td><?php echo $update['created_at']; ?></td>
                                <td>
                                    <a href="<?php echo $update['package_url']; ?>" class="btn-icon" download title="下载">📥</a>
                                    <a href="?page=updates&delete=<?php echo $update['id']; ?>" class="btn-icon" onclick="return confirm('确定删除此版本吗？')" title="删除">🗑️</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>