<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-6-10
 */

if (!defined('ROOT_PATH')) define('ROOT_PATH', dirname(__DIR__, 2) . '/');
if (!defined('LICENSE_CENTER_URL')) define('LICENSE_CENTER_URL', 'http://yutou.wtbidc.cn/license-center');

require_once ROOT_PATH . 'core/lib/license.php';
$license = new \Core\Lib\License();
$licenseInfo = $license->getStatus();
$currentVersion = '1.0.0';
$apiBase = LICENSE_CENTER_URL;
$msg = '';
$msgType = '';

$ch = curl_init($apiBase . '/api.php?action=check_update');
curl_setopt_array($ch, [
    CURLOPT_TIMEOUT => 10,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
]);
$resp = curl_exec($ch);
curl_close($ch);

$remoteInfo = $resp ? json_decode($resp, true) : null;
$latestVersion = $remoteInfo['data']['latest_version'] ?? $currentVersion;
$changelog = $remoteInfo['data']['changelog'] ?? '';

function versionCompareSafe($v1, $v2)
{
    $a1 = explode('.', $v1);
    $a2 = explode('.', $v2);
    $max = max(count($a1), count($a2));
    for ($i = 0; $i < $max; $i++) {
        $n1 = isset($a1[$i]) ? intval($a1[$i]) : 0;
        $n2 = isset($a2[$i]) ? intval($a2[$i]) : 0;
        if ($n1 > $n2) return 1;
        if ($n1 < $n2) return -1;
    }
    return 0;
}

function copyUpgradeDir($src, $dst, $backupDir = '')
{
    $dir = opendir($src);
    while (($file = readdir($dir)) !== false) {
        if ($file === '.' || $file === '..') continue;
        $srcPath = $src . '/' . $file;
        $dstPath = $dst . '/' . $file;
        if (is_dir($srcPath)) {
            if (!is_dir($dstPath)) mkdir($dstPath, 0755, true);
            copyUpgradeDir($srcPath, $dstPath, $backupDir);
        } else {
            if ($backupDir && file_exists($dstPath)) {
                $rel = str_replace(ROOT_PATH, '', $dstPath);
                $bfile = $backupDir . '/' . $rel;
                $bdir = dirname($bfile);
                if (!is_dir($bdir)) mkdir($bdir, 0755, true);
                copy($dstPath, $bfile);
            }
            copy($srcPath, $dstPath);
        }
    }
    closedir($dir);
}

function deleteUpgradeDir($dir)
{
    if (!is_dir($dir)) return;
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        is_dir($path) ? deleteUpgradeDir($path) : @unlink($path);
    }
    @rmdir($dir);
}

function getUpgradeDirSize($dir)
{
    $size = 0;
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        $size += is_dir($path) ? getUpgradeDirSize($path) : filesize($path);
    }
    return $size;
}

$hasNew = versionCompareSafe($latestVersion, $currentVersion) > 0;
$canUpgradeOnline = $license->canOnlineUpgrade();
$levelNames = [1 => '免费版', 2 => '基础版', 3 => '专业版'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'do_upgrade') {
    if (!$canUpgradeOnline) {
        $msg = '在线升级需要基础版或专业版授权，请先到授权信息页面升级。';
        $msgType = 'error';
    } else {
        $targetVersion = trim($_POST['target_version'] ?? '');
        if ($targetVersion === '') {
            $msg = '目标版本号无效。';
            $msgType = 'error';
        } else {
            $packageUrl = $apiBase . '/api.php?action=package_download&version=' . urlencode($targetVersion);
            $tmpDir = sys_get_temp_dir();
            $zipFile = $tmpDir . '/yutou_upgrade_' . $targetVersion . '.zip';

            $ch = curl_init($packageUrl);
            curl_setopt_array($ch, [
                CURLOPT_TIMEOUT => 60,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
            ]);
            $pkgData = curl_exec($ch);
            $httpCode = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
            curl_close($ch);

            if (!$pkgData || $httpCode !== 200) {
                $msg = '下载升级包失败，请稍后重试。';
                $msgType = 'error';
            } else {
                file_put_contents($zipFile, $pkgData);
                $backupDir = ROOT_PATH . 'core/backup/' . date('YmdHis');
                if (!is_dir($backupDir)) mkdir($backupDir, 0755, true);
                file_put_contents($backupDir . '/version_backup.txt', "Backup version: {$currentVersion} -> {$targetVersion}, time: " . date('Y-m-d H:i:s'));

                $zip = new ZipArchive();
                if ($zip->open($zipFile) === true) {
                    $extractDir = $tmpDir . '/yutou_extract_' . $targetVersion;
                    if (!is_dir($extractDir)) mkdir($extractDir, 0755, true);
                    $zip->extractTo($extractDir);
                    $zip->close();

                    $srcDir = $extractDir;
                    $entries = glob($extractDir . '/*');
                    if (count($entries) === 1 && is_dir($entries[0])) {
                        $srcDir = $entries[0];
                    }

                    copyUpgradeDir($srcDir, ROOT_PATH, $backupDir);
                    @unlink($zipFile);
                    deleteUpgradeDir($extractDir);

                    $msg = "升级成功，已从 v{$currentVersion} 升级到 v{$targetVersion}，备份已保存到 core/backup/。";
                    $msgType = 'success';
                    $currentVersion = $targetVersion;
                    $hasNew = false;
                } else {
                    $msg = '解压升级包失败。';
                    $msgType = 'error';
                }
            }
        }
    }
}

$backupList = [];
$backupBaseDir = ROOT_PATH . 'core/backup/';
if (is_dir($backupBaseDir)) {
    $dirs = glob($backupBaseDir . '*', GLOB_ONLYDIR);
    foreach (array_reverse($dirs) as $dir) {
        $backupList[] = [
            'dir' => basename($dir),
            'time' => date('Y-m-d H:i:s', filemtime($dir)),
            'size' => getUpgradeDirSize($dir),
        ];
    }
}
?>
<div class="page-container fade-in">
    <div class="page-header">
        <div>
            <h2 style="font-size:16px;font-weight:600;color:var(--dark);margin:0;">
                <svg style="width:22px;height:22px;color:var(--primary);margin-right:8px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-4.5"/>
                </svg> 版本管理
            </h2>
            <p style="font-size:12px;color:var(--text-light);margin:4px 0 0 0;">查看当前版本、检查更新并执行在线升级</p>
        </div>
        <div style="display:flex;gap:10px;">
            <?php if ($canUpgradeOnline && $hasNew): ?>
            <form method="post" style="margin:0;">
                <input type="hidden" name="action" value="do_upgrade">
                <input type="hidden" name="target_version" value="<?php echo htmlspecialchars($latestVersion); ?>">
                <button type="submit" class="btn btn-primary" style="padding:10px 18px;">
                    升级到 v<?php echo htmlspecialchars($latestVersion); ?>
                </button>
            </form>
            <?php else: ?>
            <a href="/admin/main.php?act=auth" class="btn" style="padding:10px 18px;background:linear-gradient(135deg,#ea580c 0%,#dc2626 100%);color:#fff;border:none;border-radius:10px;text-decoration:none;font-weight:700;">
                <?php echo $canUpgradeOnline ? '授权信息' : '升级授权'; ?>
            </a>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($msg): ?>
    <div style="padding:14px 16px;background:<?php echo $msgType === 'success' ? '#f0fdf4' : '#fef2f2'; ?>;color:<?php echo $msgType === 'success' ? '#16a34a' : '#dc2626'; ?>;border-radius:8px;font-size:13px;margin-top:16px;border:1px solid <?php echo $msgType === 'success' ? '#bbf7d0' : '#fecaca'; ?>;">
        <?php echo nl2br(htmlspecialchars($msg)); ?>
    </div>
    <?php endif; ?>

    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-top:20px;">
        <div class="stat-card">
            <div class="stat-header">
                <span class="stat-label">当前版本</span>
                <div class="stat-icon blue">
                    <svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-4.5"/>
                    </svg>
                </div>
            </div>
            <div class="stat-value">v<?php echo htmlspecialchars($currentVersion); ?></div>
            <div class="stat-change">当前已安装版本</div>
        </div>
        <div class="stat-card">
            <div class="stat-header">
                <span class="stat-label">最新版本</span>
                <div class="stat-icon <?php echo $hasNew ? 'orange' : 'green'; ?>">
                    <svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                    </svg>
                </div>
            </div>
            <div class="stat-value" style="color:<?php echo $hasNew ? 'var(--warning)' : 'var(--success)'; ?>;">v<?php echo htmlspecialchars($latestVersion); ?></div>
            <div class="stat-change"><?php echo $hasNew ? '发现可升级版本' : '已经是最新版本'; ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-header">
                <span class="stat-label">在线升级权限</span>
                <div class="stat-icon <?php echo $canUpgradeOnline ? 'green' : 'orange'; ?>">
                    <svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                    </svg>
                </div>
            </div>
            <div class="stat-value" style="font-size:20px;"><?php echo $canUpgradeOnline ? '已授权' : '未授权'; ?></div>
            <div class="stat-change"><?php echo $canUpgradeOnline ? (($levelNames[$licenseInfo['level']] ?? '已授权') . ' 可在线升级') : '需基础版或专业版授权'; ?></div>
        </div>
    </div>

    <div style="background:#fff;border:1px solid var(--border-light);border-radius:12px;padding:24px;margin-top:20px;box-shadow:var(--shadow-xs);">
        <div style="display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;">
            <div>
                <h3 style="font-size:16px;font-weight:600;color:var(--dark);margin:0;"><?php echo $hasNew ? ('发现新版本 v' . htmlspecialchars($latestVersion)) : '版本状态正常'; ?></h3>
                <p style="font-size:12px;color:var(--text-light);margin:6px 0 0 0;">在线升级前建议先备份数据库，程序升级时会自动生成文件备份。</p>
            </div>
            <div style="display:flex;gap:10px;flex-wrap:wrap;">
                <?php if ($hasNew && $canUpgradeOnline): ?>
                <form method="post" style="margin:0;">
                    <input type="hidden" name="action" value="do_upgrade">
                    <input type="hidden" name="target_version" value="<?php echo htmlspecialchars($latestVersion); ?>">
                    <button type="submit" class="btn" style="background:linear-gradient(135deg,#16a34a,#22c55e);color:#fff;padding:10px 20px;border:none;border-radius:10px;font-weight:700;cursor:pointer;">
                        一键升级
                    </button>
                </form>
                <?php elseif (!$canUpgradeOnline): ?>
                <a href="/admin/main.php?act=auth" class="btn" style="background:linear-gradient(135deg,#ea580c 0%,#dc2626 100%);color:#fff;padding:10px 20px;border:none;border-radius:10px;text-decoration:none;font-weight:700;">
                    升级授权后使用
                </a>
                <?php else: ?>
                <button type="button" class="btn" style="background:#f8fafc;color:#475569;padding:10px 20px;border:1px solid #e2e8f0;border-radius:10px;cursor:default;">
                    当前无需升级
                </button>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($changelog !== ''): ?>
        <div style="background:#f8fafc;border:1px solid var(--border-light);border-radius:8px;padding:16px;margin-top:18px;">
            <div style="font-size:13px;font-weight:600;color:var(--dark);margin-bottom:8px;">更新说明</div>
            <div style="font-size:13px;color:var(--text);line-height:1.8;white-space:pre-wrap;"><?php echo htmlspecialchars($changelog); ?></div>
        </div>
        <?php endif; ?>

        <?php if (!$canUpgradeOnline): ?>
        <div style="padding:16px;background:#fff7ed;border:1px solid #fdba74;border-radius:10px;color:#9a3412;font-size:13px;line-height:1.8;margin-top:18px;">
            当前版本为 <strong><?php echo htmlspecialchars($levelNames[$licenseInfo['level']] ?? '免费版'); ?></strong>，在线升级功能需要基础版或专业版授权。
            <a href="/admin/main.php?act=auth" style="color:#c2410c;font-weight:700;margin-left:8px;">前往授权信息</a>
        </div>
        <?php endif; ?>
    </div>

    <div style="background:#fff;border:1px solid var(--border-light);border-radius:12px;margin-top:20px;box-shadow:var(--shadow-xs);">
        <div style="padding:16px 20px;border-bottom:1px solid var(--border-light);">
            <h3 style="font-size:14px;font-weight:600;color:var(--dark);margin:0;">升级历史</h3>
        </div>
        <div>
            <?php if (empty($backupList)): ?>
            <div style="padding:30px;text-align:center;color:var(--text-light);font-size:13px;">暂无升级备份记录</div>
            <?php else: ?>
            <table class="data-table" style="margin:0;">
                <thead>
                    <tr>
                        <th>备份时间</th>
                        <th>版本信息</th>
                        <th>备份大小</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($backupList as $backup): ?>
                    <?php $content = @file_get_contents($backupBaseDir . $backup['dir'] . '/version_backup.txt'); ?>
                    <tr>
                        <td style="font-size:13px;color:var(--text);"><?php echo htmlspecialchars($backup['time']); ?></td>
                        <td style="font-size:12px;color:var(--text-light);"><?php echo htmlspecialchars($content ? trim($content) : ('备份于 ' . $backup['time'])); ?></td>
                        <td style="font-size:12px;color:var(--text-light);"><?php echo round($backup['size'] / 1024 / 1024, 2) . ' MB'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
</div>
