<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/updater.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

if (!is_super_admin()) {
    http_response_code(403);
    exit('仅超级管理员可执行系统升级。');
}

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

$action = isset($_POST['action']) ? trim((string)$_POST['action']) : '';
$checkError = '';
$checkResult = null;
$upgradeLog = array();
$upgradeError = '';
$upgradeSuccess = false;

// 进入升级页面时强制刷新版本缓存
$_cacheRefreshResult = null;
try {
    $_cacheRefreshResult = update_refresh_version_cache(0);
} catch (Exception $e) {}
$_cacheHasNew = update_has_cached_new_version();

// 检查更新
if ($action === 'check') {
    try {
        $checkResult = update_check_remote_version();
        update_write_version_cache($checkResult);
    } catch (Exception $e) {
        $checkError = $e->getMessage();
    }
}

// 执行升级
if ($action === 'upgrade') {
    try {
        $remoteInfo = update_check_remote_version();
        if (!update_has_new_version($remoteInfo['version'])) {
            $upgradeError = '当前已是最新版本，无需升级。';
        } else {
            $upgradeLog = update_perform_upgrade($remoteInfo);
            update_cleanup_old_backups(5);
            @unlink(update_version_cache_file());
            $upgradeSuccess = true;
        }
    } catch (Exception $e) {
        $upgradeError = $e->getMessage();
    }
}

// 获取迁移记录
$migrations = array();
try {
    if (db_is_ready()) {
        $migrations = list_applied_migrations();
    }
} catch (Exception $e) {}

$backups = update_list_backups();

$upgradeHistory = array();
try {
    if (db_is_ready()) {
        $upgradeHistory = list_upgrade_history();
    }
} catch (Exception $e) {}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 系统升级</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <style>
    .update-card { background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px; margin-bottom:20px; }
    .update-card h3 { font-size:16px; font-weight:700; color:#1e293b; margin:0 0 16px; display:flex; align-items:center; gap:8px; }
    .version-current { display:inline-flex; align-items:center; gap:8px; padding:10px 20px; background:linear-gradient(135deg,#4f46e5,#6366f1); color:#fff; border-radius:12px; font-size:18px; font-weight:800; }
    .version-badge { padding:4px 12px; border-radius:8px; font-size:13px; font-weight:700; }
    .badge-new { background:#dcfce7; color:#15803d; }
    .badge-latest { background:#dbeafe; color:#1d4ed8; }
    .info-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(200px,1fr)); gap:14px; margin:16px 0; }
    .info-item { padding:14px; background:#f8fafc; border-radius:12px; }
    .info-item label { display:block; font-size:12px; color:#94a3b8; margin-bottom:4px; }
    .info-item span { font-size:14px; color:#1e293b; font-weight:600; }
    .changelog { background:#f8fafc; border-radius:12px; padding:16px; margin:16px 0; font-size:13px; color:#475569; line-height:1.8; white-space:pre-wrap; }
    .btn-check { padding:10px 24px; background:#4f46e5; color:#fff; border:none; border-radius:10px; font-size:14px; font-weight:600; cursor:pointer; transition:all .15s; }
    .btn-check:hover { background:#4338ca; transform:translateY(-1px); }
    .btn-upgrade { padding:12px 32px; background:linear-gradient(135deg,#16a34a,#15803d); color:#fff; border:none; border-radius:12px; font-size:15px; font-weight:700; cursor:pointer; transition:all .15s; box-shadow:0 4px 16px rgba(22,163,74,.25); }
    .btn-upgrade:hover { transform:translateY(-2px); box-shadow:0 8px 24px rgba(22,163,74,.35); }
    .btn-upgrade:disabled { opacity:.5; cursor:not-allowed; transform:none; }
    .upgrade-log { background:#0f172a; border-radius:12px; padding:20px; margin:16px 0; font-family:'Cascadia Code','Fira Code',monospace; font-size:13px; color:#94a3b8; line-height:1.8; max-height:400px; overflow-y:auto; }
    .upgrade-log .log-ok { color:#4ade80; }
    .upgrade-log .log-info { color:#60a5fa; }
    .alert-error { padding:14px 18px; background:#fef2f2; border:1px solid #fecaca; border-radius:12px; color:#dc2626; font-size:13px; margin-bottom:16px; }
    .alert-success { padding:14px 18px; background:#f0fdf4; border:1px solid #bbf7d0; border-radius:12px; color:#15803d; font-size:13px; margin-bottom:16px; }
    .mini-table { width:100%; border-collapse:collapse; font-size:13px; }
    .mini-table th { background:#f8fafc; color:#64748b; font-weight:600; padding:8px 12px; text-align:left; border-bottom:2px solid #e2e8f0; }
    .mini-table td { padding:8px 12px; border-bottom:1px solid #f1f5f9; color:#334155; }
    .env-tag { display:inline-block; padding:2px 8px; border-radius:6px; font-size:11px; font-weight:600; }
    .env-ok { background:#dcfce7; color:#15803d; }
    .env-warn { background:#fef9c3; color:#a16207; }
    .env-err { background:#fef2f2; color:#dc2626; }
    .section-cols { display:grid; grid-template-columns:1fr 1fr; gap:20px; }
    @media(max-width:900px) { .section-cols { grid-template-columns:1fr; } }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('system_update', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>系统升级</h1><p>检查并安装最新版本，升级前自动备份当前文件</p></div>
            </header>

            <?php if ($upgradeSuccess): ?>
                <div class="alert-success">
                    <strong>🎉 升级成功！</strong> 系统已升级到最新版本。页面将自动刷新以加载新版代码。
                </div>
                <script>setTimeout(function(){ location.href = '/admin/system-update/index.php'; }, 3000);</script>
            <?php endif; ?>
            <?php if ($upgradeError !== ''): ?>
                <div class="alert-error"><strong>升级失败：</strong><?php echo e($upgradeError); ?></div>
            <?php endif; ?>
            <?php if ($checkError !== ''): ?>
                <div class="alert-error"><strong>检查失败：</strong><?php echo e($checkError); ?></div>
            <?php endif; ?>

            <!-- 当前版本 -->
            <div class="update-card">
                <h3>📦 当前版本</h3>
                <div style="display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
                    <div class="version-current">v<?php echo e(APP_VERSION); ?></div>
                    <form method="post" style="margin:0;">
                        <input type="hidden" name="action" value="check">
                        <button type="submit" class="btn-check">检查更新</button>
                    </form>
                </div>
            </div>

            <?php if ($checkResult === null && $_cacheHasNew && $_cacheRefreshResult && !empty($_cacheRefreshResult['version'])): ?>
            <div class="update-card" style="border:1px solid #bbf7d0;background:linear-gradient(135deg,#f0fdf4,#ecfdf5);">
                <h3 style="color:#15803d;">🎉 发现新版本 v<?php echo e($_cacheRefreshResult['version']); ?></h3>
                <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin:14px 0;">
                    <div><small style="color:#64748b;">当前版本</small><br><strong>v<?php echo e(APP_VERSION); ?></strong></div>
                    <div><small style="color:#64748b;">最新版本</small><br><strong style="color:#15803d;">v<?php echo e($_cacheRefreshResult['version']); ?></strong></div>
                    <div><small style="color:#64748b;">发布日期</small><br><strong><?php echo e(!empty($_cacheRefreshResult['release_date']) ? $_cacheRefreshResult['release_date'] : '-'); ?></strong></div>
                </div>
                <?php if (!empty($_cacheRefreshResult['changelog'])): ?>
                <div style="margin:10px 0;font-size:13px;color:#475569;line-height:1.8;">
                    <strong>更新日志：</strong>
                    <div style="margin-top:6px;padding:12px 16px;background:#fff;border-radius:8px;border:1px solid #dcfce7;white-space:pre-line;"><?php echo e($_cacheRefreshResult['changelog']); ?></div>
                </div>
                <?php endif; ?>
                <?php
                    $upgradePath = update_get_upgrade_path($_cacheRefreshResult);
                    if (count($upgradePath) > 1):
                ?>
                <div style="margin:10px 0;padding:12px 16px;background:#fff;border-radius:8px;border:1px solid #dcfce7;font-size:13px;color:#475569;line-height:1.8;">
                    <strong>跨版本升级路径（<?php echo count($upgradePath); ?> 步）：</strong>
                    v<?php echo e(APP_VERSION); ?><?php foreach ($upgradePath as $pv): ?> → v<?php echo e($pv['version']); ?><?php endforeach; ?>
                    <br><span style="color:#94a3b8;">系统将逐版本下载并应用更新包，确保不遗漏任何文件和数据库迁移。</span>
                </div>
                <?php endif; ?>
                <form method="post" style="margin-top:14px;">
                    <input type="hidden" name="action" value="upgrade">
                    <button type="submit" class="btn-upgrade" onclick="return confirm('升级前将自动备份当前文件，确定升级到 v<?php echo e($_cacheRefreshResult['version']); ?>？<?php echo count($upgradePath) > 1 ? '\\n\\n将逐步升级 ' . count($upgradePath) . ' 个版本，过程可能需要几分钟。' : ''; ?>');">🚀 立即升级到 v<?php echo e($_cacheRefreshResult['version']); ?></button>
                </form>
            </div>
            <?php endif; ?>

            <?php if (!empty($upgradeLog)): ?>
            <div class="update-card">
                <h3>📋 升级日志</h3>
                <div class="upgrade-log">
                    <?php foreach ($upgradeLog as $line): ?>
                        <?php
                            $cls = 'log-info';
                            if (strpos($line, '完成') !== false || strpos($line, '成功') !== false) $cls = 'log-ok';
                        ?>
                        <div class="<?php echo $cls; ?>">[<?php echo date('H:i:s'); ?>] <?php echo e($line); ?></div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($checkResult !== null): ?>
            <div class="update-card">
                <h3>🔍 检查结果</h3>
                <?php if (update_has_new_version($checkResult['version'])): ?>
                    <div style="margin-bottom:16px;">
                        <span class="version-badge badge-new">🆕 发现新版本 v<?php echo e($checkResult['version']); ?></span>
                    </div>
                    <div class="info-grid">
                        <div class="info-item">
                            <label>当前版本</label>
                            <span>v<?php echo e(APP_VERSION); ?></span>
                        </div>
                        <div class="info-item">
                            <label>最新版本</label>
                            <span>v<?php echo e($checkResult['version']); ?></span>
                        </div>
                        <div class="info-item">
                            <label>发布日期</label>
                            <span><?php echo e(isset($checkResult['release_date']) ? $checkResult['release_date'] : '-'); ?></span>
                        </div>
                        <div class="info-item">
                            <label>PHP 要求</label>
                            <span>
                                <?php $minPhp = isset($checkResult['min_php']) ? $checkResult['min_php'] : '7.4'; ?>
                                >= <?php echo e($minPhp); ?>
                                <?php if (version_compare(PHP_VERSION, $minPhp, '>=')): ?>
                                    <span class="env-tag env-ok">✓ 当前 <?php echo PHP_VERSION; ?></span>
                                <?php else: ?>
                                    <span class="env-tag env-err">✗ 当前 <?php echo PHP_VERSION; ?></span>
                                <?php endif; ?>
                            </span>
                        </div>
                    </div>
                    <?php if (!empty($checkResult['changelog'])): ?>
                        <strong style="font-size:13px;color:#64748b;">更新日志：</strong>
                        <div class="changelog"><?php echo e($checkResult['changelog']); ?></div>
                    <?php endif; ?>
                    <form method="post" style="margin-top:20px;" onsubmit="return confirm('确定要升级到 v<?php echo e($checkResult['version']); ?>？升级前会自动备份当前文件。');">
                        <input type="hidden" name="action" value="upgrade">
                        <button type="submit" class="btn-upgrade" id="btnUpgrade">🚀 立即升级到 v<?php echo e($checkResult['version']); ?></button>
                    </form>
                <?php else: ?>
                    <div style="padding:20px;text-align:center;">
                        <span class="version-badge badge-latest">✓ 已是最新版本</span>
                        <p style="margin:12px 0 0;color:#64748b;font-size:14px;">当前版本 v<?php echo e(APP_VERSION); ?> 已是最新，无需升级。</p>
                    </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- 环境与迁移 -->
            <div class="section-cols">
                <div class="update-card">
                    <h3>🖥 环境信息</h3>
                    <table class="mini-table">
                        <tr><td>PHP 版本</td><td><span class="env-tag env-ok"><?php echo PHP_VERSION; ?></span></td></tr>
                        <tr><td>操作系统</td><td><?php echo PHP_OS; ?></td></tr>
                        <tr><td>ZipArchive</td><td><span class="env-tag <?php echo class_exists('ZipArchive') ? 'env-ok' : 'env-err'; ?>"><?php echo class_exists('ZipArchive') ? '已安装' : '未安装'; ?></span></td></tr>
                        <tr><td>allow_url_fopen</td><td><span class="env-tag <?php echo ini_get('allow_url_fopen') ? 'env-ok' : 'env-err'; ?>"><?php echo ini_get('allow_url_fopen') ? '已开启' : '未开启'; ?></span></td></tr>
                        <tr><td>runtime 可写</td><td><span class="env-tag <?php echo is_writable(__DIR__ . '/runtime') ? 'env-ok' : 'env-err'; ?>"><?php echo is_writable(__DIR__ . '/runtime') ? '是' : '否'; ?></span></td></tr>
                        <tr><td>项目根可写</td><td><span class="env-tag <?php echo is_writable(__DIR__) ? 'env-ok' : 'env-warn'; ?>"><?php echo is_writable(__DIR__) ? '是' : '否'; ?></span></td></tr>
                    </table>
                </div>

                <div class="update-card">
                    <h3>🗄 数据库迁移记录</h3>
                    <?php if (empty($migrations)): ?>
                        <p style="color:#94a3b8;font-size:13px;">暂无迁移记录。首次升级时将自动记录。</p>
                    <?php else: ?>
                        <table class="mini-table">
                            <thead><tr><th>迁移文件</th><th>执行时间</th></tr></thead>
                            <tbody>
                            <?php foreach ($migrations as $m): ?>
                                <tr><td><?php echo e($m['migration']); ?></td><td><?php echo e($m['applied_at']); ?></td></tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>

            <div class="update-card">
                <h3>📋 升级记录</h3>
                <?php if (empty($upgradeHistory)): ?>
                    <p style="color:#94a3b8;font-size:13px;">暂无升级记录。首次升级后将自动记录。</p>
                <?php else: ?>
                    <table class="mini-table">
                        <thead><tr><th style="width:140px;">发布时间</th><th style="width:120px;">版本号</th><th>更新内容</th></tr></thead>
                        <tbody>
                        <?php foreach ($upgradeHistory as $h): ?>
                            <tr>
                                <td><?php echo e(!empty($h['release_date']) ? $h['release_date'] : substr($h['upgraded_at'], 0, 10)); ?></td>
                                <td><span class="version-badge badge-new">v<?php echo e($h['version']); ?></span></td>
                                <td style="font-size:13px;color:#475569;white-space:pre-wrap;line-height:1.6;"><?php echo e(!empty($h['changelog']) ? $h['changelog'] : '-'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>

            <?php if (!empty($backups)): ?>
            <div class="update-card">
                <h3>💾 升级备份</h3>
                <p style="color:#64748b;font-size:13px;margin:0 0 12px;">升级前自动备份的文件保存在 <code>runtime/update-backup/</code>，保留最近 5 次。</p>
                <table class="mini-table">
                    <thead><tr><th>备份时间</th><th>目录</th></tr></thead>
                    <tbody>
                    <?php foreach ($backups as $b): ?>
                        <tr><td><?php echo e(substr($b,0,4).'-'.substr($b,4,2).'-'.substr($b,6,2).' '.substr($b,9,2).':'.substr($b,11,2).':'.substr($b,13,2)); ?></td><td><code>runtime/update-backup/<?php echo e($b); ?></code></td></tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>

        </div>
    </main>
</div>
</body>
</html>
