<!-- 
    Optimized Update Notification Banner
    File: includes/update_notification.php
    
    OPTIMIZED VERSION - Uses cached results, won't slow down page loads
    Safe to include in dashboard.php or admin_settings.php
    
    Usage: <?php include 'includes/update_notification.php'; ?>
-->

<?php
// Check if we should show the notification (only check once per session)
$showUpdateNotification = false;
$updateData = null;

// Only check if we haven't checked in this session yet
if (!isset($_SESSION['update_checked_at']) || (time() - $_SESSION['update_checked_at']) > 3600) {
    // Check if cached result exists and is less than 6 hours old
    $cacheFile = __DIR__ . '/../cache/update_check.json';
    $checkNow = false;
    
    if (file_exists($cacheFile)) {
        $cacheData = json_decode(file_get_contents($cacheFile), true);
        $cacheAge = time() - strtotime($cacheData['checked_at'] ?? '2000-01-01');
        
        // Use cached data if less than 6 hours old
        if ($cacheAge < 21600) {
            $updateData = $cacheData['response'] ?? null;
        } else {
            $checkNow = true;
        }
    } else {
        $checkNow = true;
    }
    
    // Mark as checked in session (won't check again this session)
    $_SESSION['update_checked_at'] = time();
    
    if ($checkNow) {
        // We'll check asynchronously via JavaScript instead of blocking PHP
        $showUpdateNotification = false; // Will be handled by JS
    } elseif ($updateData && isset($updateData['update_available']) && $updateData['update_available']) {
        $showUpdateNotification = true;
    }
} else {
    // Already checked this session, load from cache if available
    $cacheFile = __DIR__ . '/../cache/update_check.json';
    if (file_exists($cacheFile)) {
        $cacheData = json_decode(file_get_contents($cacheFile), true);
        $updateData = $cacheData['response'] ?? null;
        if ($updateData && isset($updateData['update_available']) && $updateData['update_available']) {
            $showUpdateNotification = true;
        }
    }
}
?>

<div id="updateNotificationContainer">
    <?php if ($showUpdateNotification && $updateData): ?>
        <!-- Show notification immediately from cache -->
        <script>
            // Render notification with cached data
            const cachedUpdateData = <?= json_encode($updateData) ?>;
            showUpdateNotification(cachedUpdateData);
        </script>
    <?php endif; ?>
</div>

<style>
.update-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    max-width: 450px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
    padding: 24px;
    z-index: 10000;
    animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
    from {
        transform: translateX(500px);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

.update-notification.hidden {
    display: none;
}

.update-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
}

.update-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
}

.update-icon.security {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
}

.update-icon.normal {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: white;
}

.update-icon.feature {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
}

.update-title {
    flex: 1;
}

.update-title h3 {
    font-size: 18px;
    font-weight: 700;
    color: #1f2937;
    margin: 0 0 4px 0;
}

.update-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}

.update-badge.security {
    background: #fee2e2;
    color: #991b1b;
}

.update-badge.major {
    background: #dbeafe;
    color: #1e40af;
}

.update-badge.minor {
    background: #d1fae5;
    color: #065f46;
}

.update-badge.patch {
    background: #f3f4f6;
    color: #374151;
}

.update-close {
    background: none;
    border: none;
    color: #9ca3af;
    cursor: pointer;
    padding: 4px;
    font-size: 20px;
}

.update-close:hover {
    color: #4b5563;
}

.update-body {
    margin-bottom: 20px;
}

.update-version {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
    padding: 12px;
    background: #f9fafb;
    border-radius: 8px;
}

.update-version-label {
    font-size: 12px;
    color: #6b7280;
    font-weight: 500;
}

.update-version-number {
    font-size: 16px;
    font-weight: 700;
    color: #1f2937;
}

.update-arrow {
    color: #9ca3af;
    font-size: 18px;
}

.update-changelog {
    font-size: 14px;
    color: #4b5563;
    line-height: 1.6;
    max-height: 200px;
    overflow-y: auto;
}

.update-changelog h4 {
    font-size: 12px;
    font-weight: 600;
    color: #1f2937;
    margin: 12px 0 6px 0;
}

.update-changelog ul {
    margin: 0;
    padding-left: 20px;
}

.update-changelog li {
    margin: 4px 0;
}

.update-actions {
    display: flex;
    gap: 12px;
}

.update-btn {
    flex: 1;
    padding: 12px 20px;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.update-btn-primary {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: white;
}

.update-btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 16px rgba(37, 99, 235, 0.3);
}

.update-btn-primary:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

.update-btn-secondary {
    background: #f3f4f6;
    color: #4b5563;
}

.update-btn-secondary:hover {
    background: #e5e7eb;
}

.update-progress {
    margin-top: 16px;
    padding: 12px;
    background: #f0f9ff;
    border-radius: 8px;
    display: none;
}

.update-progress.visible {
    display: block;
}

.update-progress-bar {
    width: 100%;
    height: 8px;
    background: #dbeafe;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 8px;
}

.update-progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #3b82f6, #2563eb);
    border-radius: 4px;
    transition: width 0.3s;
    animation: progress 1s ease-in-out infinite;
}

@keyframes progress {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(400%); }
}

.update-progress-text {
    font-size: 13px;
    color: #1e40af;
    font-weight: 500;
    text-align: center;
}

.update-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-top-color: white;
    border-radius: 50%;
    animation: spin 0.6s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<script>
// Only check for updates asynchronously if not already shown
if (!document.getElementById('updateNotificationContainer').innerHTML.trim()) {
    // Delay check by 2 seconds to not block page load
    setTimeout(checkForUpdatesAsync, 2000);
}

function checkForUpdatesAsync() {
    fetch('check_updates.php', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success && data.update_available) {
            showUpdateNotification(data);
        }
    })
    .catch(error => {
        console.log('Update check skipped:', error);
        // Silently fail - not critical
    });
}

function showUpdateNotification(updateData) {
    const container = document.getElementById('updateNotificationContainer');
    
    const iconClass = updateData.release_type === 'security' || updateData.release_type === 'hotfix' ? 'security' : 
                      updateData.release_type === 'major' ? 'normal' : 'feature';
    
    const iconName = updateData.release_type === 'security' ? 'shield-fill-exclamation' :
                     updateData.release_type === 'hotfix' ? 'tools' :
                     updateData.release_type === 'major' ? 'star-fill' :
                     updateData.release_type === 'minor' ? 'plus-circle' : 'wrench';
    
    const html = `
        <div class="update-notification" id="updateNotification">
            <div class="update-header">
                <div class="update-icon ${iconClass}">
                    <i class="bi bi-${iconName}"></i>
                </div>
                <div class="update-title">
                    <h3>Update Available</h3>
                    <span class="update-badge ${updateData.release_type}">
                        <i class="bi bi-circle-fill" style="font-size: 6px;"></i>
                        ${updateData.release_type}
                    </span>
                </div>
                <button class="update-close" onclick="closeUpdateNotification()">
                    <i class="bi bi-x"></i>
                </button>
            </div>
            
            <div class="update-body">
                <div class="update-version">
                    <div>
                        <div class="update-version-label">Current</div>
                        <div class="update-version-number">${updateData.current_version}</div>
                    </div>
                    <i class="bi bi-arrow-right update-arrow"></i>
                    <div>
                        <div class="update-version-label">New Version</div>
                        <div class="update-version-number">${updateData.latest_version}</div>
                    </div>
                </div>
                
                <div class="update-changelog">
                    <strong>${updateData.title}</strong>
                    <div style="margin-top: 8px; font-size: 13px;">
                        ${formatChangelog(updateData.changelog)}
                    </div>
                </div>
            </div>
            
            <div class="update-actions">
                <button class="update-btn update-btn-secondary" onclick="closeUpdateNotification()">
                    Later
                </button>
                <button class="update-btn update-btn-primary" onclick="startUpdate('${updateData.latest_version}', '${updateData.file_hash || ''}')" id="updateBtn">
                    <i class="bi bi-download"></i>
                    Install Update
                </button>
            </div>
            
            <div class="update-progress" id="updateProgress">
                <div class="update-progress-bar">
                    <div class="update-progress-fill"></div>
                </div>
                <div class="update-progress-text" id="updateProgressText">
                    Downloading update...
                </div>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}

function formatChangelog(changelog) {
    // Convert markdown to simple HTML
    return changelog
        .replace(/### (.+)/g, '<h4>$1</h4>')
        .replace(/- (.+)/g, '<li>$1</li>')
        .replace(/\n/g, '<br>');
}

function closeUpdateNotification() {
    const notification = document.getElementById('updateNotification');
    if (notification) {
        notification.classList.add('hidden');
    }
}

function startUpdate(version, hash) {
    const btn = document.getElementById('updateBtn');
    const progress = document.getElementById('updateProgress');
    const progressText = document.getElementById('updateProgressText');
    
    // Disable button and show progress
    btn.disabled = true;
    btn.innerHTML = '<span class="update-spinner"></span> Installing...';
    progress.classList.add('visible');
    
    // Create form data
    const formData = new FormData();
    formData.append('version', version);
    formData.append('hash', hash);
    
    // Perform update
    fetch('perform_update.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            progressText.innerHTML = '<i class="bi bi-check-circle-fill"></i> Update completed successfully!';
            setTimeout(() => {
                location.reload();
            }, 2000);
        } else {
            progressText.innerHTML = '<i class="bi bi-x-circle-fill"></i> Update failed: ' + data.message;
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-download"></i> Retry Update';
        }
    })
    .catch(error => {
        progressText.innerHTML = '<i class="bi bi-x-circle-fill"></i> Error: ' + error.message;
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-download"></i> Retry Update';
    });
}
</script>