<?php
ob_start();
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'] ?? '未知';

// 统计数据
$stats = [
    'total' => count($updates),
    'latest' => $updates[0]['version'] ?? $sys_version,
];

// 处理删除更新
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>
            <img src="https://api.iconify.design/mdi:cloud-download.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            在线更新管理
        </h2>
        <div class="version-info">
            <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
            当前版本：<span>v<?php echo htmlspecialchars($sys_version); ?></span>
        </div>
    </div>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $success; ?>
        </div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="alert alert-error">
            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <!-- 统计卡片 -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:package-variant.svg?color=%23667eea" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['total']; ?></span>
                <span class="stat-label">历史版本数</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:tag.svg?color=%2310b981" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value">v<?php echo htmlspecialchars($stats['latest']); ?></span>
                <span class="stat-label">最新版本</span>
            </div>
        </div>
    </div>
    
    <!-- 系统环境信息 -->
    <div class="env-info">
        <div class="env-item">
            <img src="https://api.iconify.design/mdi:language-php.svg?color=%23777bb4" width="18" height="18" alt="">
            <span>PHP <?php echo $php_version; ?></span>
        </div>
        <div class="env-item">
            <img src="https://api.iconify.design/mdi:database.svg?color=%23f59e0b" width="18" height="18" alt="">
            <span>MySQL <?php echo $mysql_version; ?></span>
        </div>
        <div class="env-item">
            <img src="https://api.iconify.design/mdi:server.svg?color=%236b7280" width="18" height="18" alt="">
            <span><?php echo $server_software; ?></span>
        </div>
    </div>
    
    <!-- 发布新版本 -->
    <div class="section-box">
        <div class="section-header">
            <h3>
                <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                发布新版本
            </h3>
        </div>
        <div class="form-card">
            <form method="POST" enctype="multipart/form-data" id="publishForm">
                <input type="hidden" name="action" value="publish">
                <div class="form-row">
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            版本号 <span class="required">*</span>
                        </label>
                        <input type="text" name="version" required placeholder="例如：1.0.1">
                    </div>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        更新说明
                    </label>
                    <textarea name="release_notes" rows="4" placeholder="描述本次更新的内容..."></textarea>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:file-upload.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        更新包文件 <span class="required">*</span>
                    </label>
                    <div class="file-input-wrapper">
                        <input type="file" name="package" required accept=".zip,.rar,.tar.gz" id="packageInput">
                        <label for="packageInput" class="file-input-label">
                            <img src="https://api.iconify.design/mdi:folder-open.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            选择文件
                        </label>
                        <span class="file-name" id="fileNameDisplay">未选择文件</span>
                    </div>
                    <small>支持ZIP、RAR等压缩包格式</small>
                </div>
                <button type="submit" class="btn btn-primary" id="publishBtn">
                    <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                    发布更新
                </button>
            </form>
        </div>
    </div>
    
    <!-- 历史版本列表 -->
    <div class="section-box">
        <div class="section-header">
            <h3>
                <img src="https://api.iconify.design/mdi:history.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                历史版本
            </h3>
        </div>
        <?php if (empty($updates)): ?>
            <div class="empty-state">
                <img src="https://api.iconify.design/mdi:package-variant-closed.svg?color=%239ca3af" width="48" height="48" alt="">
                <p>暂无历史版本</p>
            </div>
        <?php else: ?>
            <div class="table-wrapper">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>版本</th>
                            <th>更新说明</th>
                            <th>发布时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($updates as $update): ?>
                            <tr>
                                <td>
                                    <div class="version-cell">
                                        <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="14" height="14" alt="">
                                        <strong>v<?php echo htmlspecialchars($update['version']); ?></strong>
                                    </div>
                                </td>
                                <td class="release-notes"><?php echo nl2br(htmlspecialchars($update['release_notes'])); ?></td>
                                <td>
                                    <div class="date-cell">
                                        <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="14" height="14" alt="">
                                        <?php echo $update['created_at']; ?>
                                    </div>
                                </td>
                                <td class="action-buttons">
                                    <a href="<?php echo $update['package_url']; ?>" class="action-btn" download title="下载">
                                        <img src="https://api.iconify.design/mdi:download.svg?color=%23667eea" width="16" height="16" alt="">
                                    </a>
                                    <a href="?page=updates&delete=<?php echo $update['id']; ?>" class="action-btn delete-btn" onclick="return confirm('确定删除此版本吗？')" title="删除">
                                        <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.updates-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 12px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.version-info {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    background: var(--bg-secondary);
    border-radius: 30px;
    font-size: 14px;
    color: var(--text-secondary);
}
.version-info span {
    font-weight: 600;
    color: var(--primary-color);
    margin-left: 4px;
}

/* 提示消息 */
.alert {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    border-radius: var(--radius-md);
    margin-bottom: 24px;
    font-size: 14px;
}
.alert-success {
    background: #d1fae5;
    color: #065f46;
    border: 1px solid #a7f3d0;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

/* 统计卡片 */
.stats-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 20px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 18px 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 14px;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
}
.stat-content {
    display: flex;
    flex-direction: column;
}
.stat-value {
    font-size: 24px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 2px;
}

/* 环境信息 */
.env-info {
    display: flex;
    gap: 20px;
    margin-bottom: 24px;
    padding: 12px 16px;
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    border: 1px solid var(--border-color);
    flex-wrap: wrap;
}
.env-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: var(--text-secondary);
}

/* 区块 */
.section-box {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    overflow: hidden;
    margin-bottom: 24px;
    box-shadow: var(--shadow-sm);
}
.section-header {
    padding: 18px 24px;
    border-bottom: 1px solid var(--border-color);
    background: var(--bg-secondary);
}
.section-header h3 {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

/* 表单卡片 */
.form-card {
    padding: 24px;
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
    color: var(--text-primary);
}
.required {
    color: var(--danger-color);
    margin-left: 2px;
}
.form-group input[type="text"],
.form-group textarea {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    color: var(--text-primary);
    transition: all 0.2s;
}
.form-group input:focus,
.form-group textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group textarea {
    resize: vertical;
    font-family: inherit;
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}

/* 文件上传 */
.file-input-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 8px;
}
.file-input-wrapper input[type="file"] {
    display: none;
}
.file-input-label {
    display: inline-flex;
    align-items: center;
    padding: 10px 18px;
    background: var(--bg-secondary);
    border: 1.5px dashed var(--border-color);
    border-radius: var(--radius-md);
    cursor: pointer;
    font-size: 14px;
    color: var(--text-primary);
    transition: all 0.2s;
    white-space: nowrap;
}
.file-input-label:hover {
    border-color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.file-name {
    font-size: 13px;
    color: var(--text-muted);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 12px 24px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

/* 表格 */
.table-wrapper {
    padding: 0;
}
.data-table {
    width: 100%;
    border-collapse: collapse;
}
.data-table th {
    padding: 14px 20px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px 20px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr {
    transition: background 0.2s;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 单元格样式 */
.version-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}
.release-notes {
    max-width: 350px;
    line-height: 1.5;
    color: var(--text-secondary);
}
.date-cell {
    display: flex;
    align-items: center;
    gap: 6px;
    color: var(--text-secondary);
    white-space: nowrap;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 8px;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    transition: all 0.2s;
    text-decoration: none;
}
.action-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    background: #fef2f2;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 12px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 14px;
    margin: 0;
}

/* 响应式 */
@media (max-width: 768px) {
    .stats-row {
        grid-template-columns: 1fr;
    }
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .file-input-wrapper {
        flex-direction: column;
        align-items: flex-start;
    }
    .file-name {
        width: 100%;
    }
    .data-table th,
    .data-table td {
        padding: 12px 14px;
    }
}
</style>

<script>
// 文件选择显示文件名
document.getElementById('packageInput')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        document.getElementById('fileNameDisplay').textContent = file.name;
    } else {
        document.getElementById('fileNameDisplay').textContent = '未选择文件';
    }
});

// 表单提交
document.getElementById('publishForm')?.addEventListener('submit', function(e) {
    const version = this.querySelector('input[name="version"]').value.trim();
    const file = this.querySelector('input[name="package"]').files[0];
    
    if (!version) {
        e.preventDefault();
        window.showToast && window.showToast('请输入版本号', 'error');
        return;
    }
    if (!file) {
        e.preventDefault();
        window.showToast && window.showToast('请选择更新包文件', 'error');
        return;
    }
});
</script>