<?php
ob_start();
/**
 * 管理员专用 - 系统更新
 * 访问路径: /admin.php?page=update
 */
if (!defined('IN_ADMIN')) {
    define('IN_ADMIN', true);
}
require_once __DIR__ . '/../../config.php';

// 权限检查：仅管理员可访问
if (!isAdmin()) {
    redirect(SITE_URL . 'admin.php');
}

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

$message = '';
$error = '';
$current_version = '';

// 获取请求动作
$action = $_GET['action'] ?? '';

try {
    $client = new LicenseClient();
    $current_version = $client->getCurrentVersion();
} catch (Exception $e) {
    $error = $e->getMessage();
}

// AJAX 处理
if ($action === 'check') {
    header('Content-Type: application/json');
    try {
        $client = new LicenseClient();
        $result = $client->checkUpdate();
        echo json_encode($result);
    } catch (Exception $e) {
        echo json_encode(['has_update' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    set_time_limit(300);
    
    $to_version = $_POST['version'] ?? '';
    $download_url = $_POST['download_url'] ?? '';
    
    try {
        $client = new LicenseClient();
        $from_version = $client->getCurrentVersion();
        
        // 1. 下载更新包
        $temp_file = sys_get_temp_dir() . '/update_' . uniqid() . '.zip';
        if (!$client->downloadUpdate($download_url, $temp_file)) {
            throw new Exception('下载更新包失败，请检查网络或下载地址');
        }
        
        // 2. 解压并覆盖文件
        $zip = new ZipArchive();
        if ($zip->open($temp_file) !== true) {
            throw new Exception('无法打开更新包，文件可能已损坏');
        }
        
        $root_path = realpath(__DIR__ . '/../../');
        if (!$zip->extractTo($root_path)) {
            $zip->close();
            throw new Exception('解压失败，请检查目录写入权限');
        }
        $zip->close();
        unlink($temp_file);
        
        // 3. 执行数据库迁移
        $sql_file = $root_path . '/update.sql';
        if (file_exists($sql_file)) {
            $db = Database::getInstance();
            $sql = file_get_contents($sql_file);
            $db->query($sql);
            unlink($sql_file);
        }
        
        // 4. 更新版本号
        $version_file = $root_path . '/version.php';
        $version_content = "<?php\nreturn ['version' => '{$to_version}', 'updated_at' => '" . date('Y-m-d H:i:s') . "'];\n";
        file_put_contents($version_file, $version_content);
        
        // 5. 上报主站
        $client->reportUpdate($from_version, $to_version, 'success');
        
        echo json_encode(['success' => true, 'message' => '系统更新成功！']);
    } catch (Exception $e) {
        if (isset($client) && isset($from_version) && isset($to_version)) {
            try { $client->reportUpdate($from_version, $to_version, 'failed'); } catch (Exception $ignored) {}
        }
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}
?>

<div class="update-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>

    <?php if ($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="">
            <?= htmlspecialchars($error) ?>
        </div>
    <?php else: ?>
        <!-- 当前版本卡片 -->
        <div class="version-card">
            <div class="version-icon">
                <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="32" height="32" alt="">
            </div>
            <div class="version-content">
                <span class="version-label">当前版本</span>
                <span class="version-value"><?= htmlspecialchars($current_version) ?></span>
            </div>
        </div>
        
        <!-- 更新操作卡片 -->
        <div class="update-card">
            <div id="updateStatus">
                <button class="btn btn-primary" id="checkUpdateBtn" onclick="checkUpdate()">
                    <img src="https://api.iconify.design/mdi:refresh.svg?color=white" width="18" height="18" style="margin-right: 8px;" alt="">
                    <span id="checkBtnText">检查更新</span>
                    <span class="loading-spinner d-none" id="checkSpinner"></span>
                </button>
            </div>
            
            <!-- 发现新版本 -->
            <div id="updateInfo" style="display:none;" class="update-info">
                <div class="update-info-header">
                    <img src="https://api.iconify.design/mdi:cloud-download.svg?color=%23667eea" width="24" height="24" alt="">
                    <h3>发现新版本</h3>
                </div>
                <div class="update-info-body">
                    <div class="new-version">
                        <img src="https://api.iconify.design/mdi:tag.svg?color=%2310b981" width="18" height="18" alt="">
                        <span>版本 <strong id="newVersion"></strong></span>
                    </div>
                    <div class="update-title">
                        <img src="https://api.iconify.design/mdi:format-title.svg?color=%236b7280" width="16" height="16" alt="">
                        <span id="updateTitle"></span>
                    </div>
                    <div class="update-desc">
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%236b7280" width="16" height="16" alt="">
                        <span>更新说明</span>
                    </div>
                    <pre id="updateDesc"></pre>
                    <div class="force-badge" id="forceBadge" style="display:none;">
                        <img src="https://api.iconify.design/mdi:alert.svg?color=%23f59e0b" width="16" height="16" alt="">
                        强制更新
                    </div>
                </div>
                <div class="update-info-footer">
                    <button class="btn btn-success" id="startUpdateBtn" onclick="startUpdate()">
                        <img src="https://api.iconify.design/mdi:cloud-download.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                        立即更新
                    </button>
                    <button class="btn btn-secondary" id="cancelUpdateBtn" onclick="hideUpdateInfo()">
                        <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="18" height="18" style="margin-right: 6px;" alt="">
                        取消
                    </button>
                </div>
                <div class="update-progress" id="updateProgress" style="display:none;">
                    <span class="loading-spinner"></span>
                    <span>正在更新，请稍候...</span>
                </div>
            </div>
            
            <!-- 已是最新版本 -->
            <div id="latestInfo" style="display:none;" class="latest-info">
                <div class="latest-icon">
                    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="48" height="48" alt="">
                </div>
                <h3>当前已是最新版本</h3>
                <p>您的系统版本为 <strong id="currentVersionDisplay"><?php echo htmlspecialchars($current_version); ?></strong>，无需更新。</p>
                <button class="btn btn-secondary" onclick="hideLatestInfo()">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 6px;" alt="">
                    关闭
                </button>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --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;
}

.update-container {
    max-width: 600px;
    margin: 0 auto;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 28px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

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

/* 当前版本卡片 */
.version-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 24px 28px;
    margin-bottom: 24px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 20px;
    box-shadow: var(--shadow-sm);
}
.version-icon {
    width: 64px;
    height: 64px;
    border-radius: var(--radius-md);
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
}
.version-content {
    display: flex;
    flex-direction: column;
}
.version-label {
    font-size: 14px;
    color: var(--text-muted);
    margin-bottom: 6px;
}
.version-value {
    font-size: 32px;
    font-weight: 700;
    color: var(--primary-color);
    line-height: 1.2;
}

/* 更新卡片 */
.update-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 28px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}

/* 按钮 */
.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);
}
.btn-success {
    background: var(--success-color);
    color: white;
    box-shadow: 0 2px 4px rgba(16, 185, 129, 0.2);
}
.btn-success:hover {
    background: #059669;
    transform: translateY(-1px);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}
.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

/* 更新信息区域 */
.update-info {
    margin-top: 24px;
}
.update-info-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}
.update-info-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.update-info-body {
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    padding: 20px;
    margin-bottom: 20px;
}
.new-version {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color);
}
.new-version strong {
    color: var(--success-color);
}
.update-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-weight: 500;
    color: var(--text-primary);
}
.update-desc {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
    font-size: 14px;
    color: var(--text-secondary);
}
.update-info-body pre {
    background: var(--bg-primary);
    padding: 16px;
    border-radius: var(--radius-sm);
    font-size: 14px;
    line-height: 1.6;
    color: var(--text-secondary);
    white-space: pre-wrap;
    word-break: break-word;
    border: 1px solid var(--border-color);
    margin: 0;
}
.force-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    margin-top: 16px;
    padding: 6px 14px;
    background: #fef3c7;
    color: #92400e;
    border-radius: 30px;
    font-size: 13px;
    font-weight: 500;
}
.update-info-footer {
    display: flex;
    gap: 12px;
}
.update-progress {
    margin-top: 20px;
    padding: 16px;
    background: var(--bg-secondary);
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    color: var(--text-secondary);
}

/* 已是最新版本 */
.latest-info {
    margin-top: 24px;
    text-align: center;
    padding: 32px 24px;
    background: var(--bg-secondary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
}
.latest-icon {
    margin-bottom: 16px;
}
.latest-info h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 8px;
}
.latest-info p {
    color: var(--text-secondary);
    margin: 0 0 20px;
}
.latest-info strong {
    color: var(--success-color);
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 18px;
    height: 18px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 0.6s linear infinite;
}
.update-progress .loading-spinner {
    border: 2px solid rgba(102, 126, 234, 0.3);
    border-top-color: var(--primary-color);
}
.d-none {
    display: none;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 768px) {
    .version-card {
        padding: 20px;
    }
    .version-value {
        font-size: 26px;
    }
    .update-info-footer {
        flex-direction: column;
    }
    .update-info-footer .btn {
        width: 100%;
    }
}
</style>

<script>
var updateData = null;

function checkUpdate() {
    const btn = document.getElementById('checkUpdateBtn');
    const btnText = document.getElementById('checkBtnText');
    const spinner = document.getElementById('checkSpinner');
    
    btn.disabled = true;
    btnText.textContent = '检查中...';
    spinner.classList.remove('d-none');
    
    fetch('/update_api/check_update.php')
        .then(res => res.json())
        .then(res => {
            document.getElementById('updateInfo').style.display = 'none';
            document.getElementById('latestInfo').style.display = 'none';
            document.getElementById('updateStatus').style.display = 'none';
            
            if (res.has_update) {
                updateData = res;
                document.getElementById('newVersion').textContent = res.version;
                document.getElementById('updateTitle').textContent = res.title || '无标题';
                document.getElementById('updateDesc').textContent = res.description || '暂无更新说明';
                
                if (res.is_force) {
                    document.getElementById('forceBadge').style.display = 'inline-flex';
                } else {
                    document.getElementById('forceBadge').style.display = 'none';
                }
                
                document.getElementById('updateInfo').style.display = 'block';
            } else {
                document.getElementById('latestInfo').style.display = 'block';
            }
        })
        .catch(() => {
            window.showToast && window.showToast('检查更新失败，请稍后重试', 'error');
            document.getElementById('updateStatus').style.display = 'block';
        })
        .finally(() => {
            btn.disabled = false;
            btnText.textContent = '检查更新';
            spinner.classList.add('d-none');
        });
}

function startUpdate() {
    if (!updateData) {
        window.showToast && window.showToast('请先检查更新', 'error');
        return;
    }
    
    if (!confirm('确定要更新到版本 ' + updateData.version + ' 吗？')) return;
    
    const startBtn = document.getElementById('startUpdateBtn');
    const cancelBtn = document.getElementById('cancelUpdateBtn');
    const progress = document.getElementById('updateProgress');
    
    startBtn.disabled = true;
    cancelBtn.disabled = true;
    progress.style.display = 'flex';
    
    fetch('/update_api/do_update.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            version: updateData.version,
            download_url: updateData.download_url
        })
    })
    .then(res => res.json())
    .then(res => {
        if (res.success) {
            window.showToast && window.showToast(res.message, 'success');
            setTimeout(() => location.reload(), 2000);
        } else {
            window.showToast && window.showToast('更新失败：' + res.message, 'error');
            startBtn.disabled = false;
            cancelBtn.disabled = false;
            progress.style.display = 'none';
        }
    })
    .catch(() => {
        window.showToast && window.showToast('更新请求失败，请检查网络', 'error');
        startBtn.disabled = false;
        cancelBtn.disabled = false;
        progress.style.display = 'none';
    });
}

function hideUpdateInfo() {
    document.getElementById('updateInfo').style.display = 'none';
    document.getElementById('updateStatus').style.display = 'block';
    updateData = null;
}

function hideLatestInfo() {
    document.getElementById('latestInfo').style.display = 'none';
    document.getElementById('updateStatus').style.display = 'block';
}
</script>