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

try {
    $client = new LicenseClient();
    $current_version = $client->getCurrentVersion();
    $update_info = $client->checkUpdate();
    $has_update = $update_info['has_update'] ?? false;
    $latest_version = $update_info['version'] ?? $current_version;
} catch (Exception $e) {
    $error = $e->getMessage();
    $current_version = defined('SYS_VERSION') ? SYS_VERSION : '1.0.0';
    $has_update = false;
}
?>

<?php if (isset($error)): ?>
<div class="card" style="background: #fef2f2; color: #991b1b;">
    <?php echo htmlspecialchars($error); ?>
</div>
<?php endif; ?>

<div class="card" style="text-align: center;">
    <img src="https://api.iconify.design/mdi:cloud-download.svg?color=%23667eea" width="48" height="48" alt="">
    <div style="font-size: 14px; color: #999; margin-top: 8px;">当前版本</div>
    <div style="font-size: 36px; font-weight: 700; color: #667eea;">v<?php echo htmlspecialchars($current_version); ?></div>
</div>

<?php if ($has_update): ?>
<div class="card" style="background: #fef3c7; border-color: #f59e0b;">
    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
        <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23f59e0b" width="24" height="24" alt="">
        <div>
            <div style="font-weight: 600;">发现新版本</div>
            <div>v<?php echo htmlspecialchars($latest_version); ?></div>
        </div>
    </div>
    <button class="btn btn-primary btn-block" onclick="startUpdate()">
        <img src="https://api.iconify.design/mdi:cloud-download.svg?color=white" width="18" height="18" alt="">
        立即更新
    </button>
</div>
<?php else: ?>
<div class="card" style="background: #d1fae5; text-align: center;">
    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="32" height="32" alt="">
    <p style="color: #065f46;">已是最新版本</p>
</div>
<?php endif; ?>

<div class="card">
    <h3 style="margin-bottom: 12px; font-size: 15px;">系统信息</h3>
    <div style="display: flex; flex-direction: column; gap: 8px;">
        <div style="display: flex; justify-content: space-between;">
            <span style="color: #999;">PHP版本</span>
            <span><?php echo PHP_VERSION; ?></span>
        </div>
        <div style="display: flex; justify-content: space-between;">
            <span style="color: #999;">服务器</span>
            <span><?php echo $_SERVER['SERVER_SOFTWARE'] ?? '未知'; ?></span>
        </div>
    </div>
</div>

<script>
async function startUpdate() {
    if (!confirm('确定要更新系统吗？更新过程中请勿关闭页面。')) return;
    showToast('开始更新...', 'info');
    const r = await fetch('/update_api/do_update.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({version: '<?php echo $latest_version; ?>'})
    });
    const d = await r.json();
    showToast(d.message);
    if (d.success) setTimeout(() => location.reload(), 2000);
}
</script>