<?php
// Permission checking is now handled by the permission system in auto-prepend.php

$message = '';
$message_type = '';

// Check if this is a versioned installation
$is_versioned = file_exists('/etc/whp-version') || file_exists('/root/whp/VERSION');
$current_version = '';

if ($is_versioned) {
    if (file_exists('/etc/whp-version')) {
        $current_version = trim(file_get_contents('/etc/whp-version'));
    } elseif (file_exists('/root/whp/VERSION')) {
        $current_version = trim(file_get_contents('/root/whp/VERSION'));
    }
}

// Release server configuration
$release_server = 'https://whp-releases.cloud-hosting.io';
?>

<?php if (!empty($message)): ?>
<div class="row">
    <div class="col-sm-12">
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <?php echo htmlspecialchars($message); ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Version Status Banner -->
<div class="row mb-4">
    <div class="col-12">
        <div class="alert alert-success">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-0">
                        <i class="fa fa-check-circle"></i> 
                        WHP Release System
                    </h6>
                    <small class="text-muted">
                        Current Version: <strong><?php echo htmlspecialchars($current_version); ?></strong> | 
                        Update Server: <?php echo htmlspecialchars($release_server); ?>
                    </small>
                </div>
                <button type="button" class="btn btn-sm btn-outline-success" id="check-release-btn" onclick="checkForUpdates()">
                    <i class="fa fa-refresh"></i> Check Updates
                </button>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <!-- WHP Release Update Panel -->
    <div class="col-md-6">
        <div class="card h-100 border-success">
            <div class="card-header bg-success text-white">
                <h5 class="card-title mb-0">
                    <i class="fa fa-cube"></i> WHP Release Update
                </h5>
            </div>
            <div class="card-body">
                <p class="text-muted">Download and install the latest WHP release from the official server.</p>
                <div id="update-info" class="mb-3" style="display: none;">
                    <div class="alert alert-info" id="update-available-info"></div>
                </div>
                <div class="mb-3">
                    <button type="button" class="btn btn-success" id="release-update-btn" onclick="startReleaseUpdate()">
                        <i class="fa fa-download"></i> Update WHP
                    </button>
                    <button type="button" class="btn btn-outline-primary" id="release-status-btn" onclick="checkForUpdates()">
                        <i class="fa fa-info-circle"></i> Check Updates
                    </button>
                </div>
                <div class="mb-3">
                    <button type="button" class="btn btn-sm btn-secondary" onclick="showReleaseInfo()">
                        <i class="fa fa-question-circle"></i> About Release System
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- System Package Update Panel -->
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-cube"></i> System Package Update
                </h5>
            </div>
            <div class="card-body">
                <p class="text-muted">Update system packages using yum/dnf package manager.</p>
                <div class="mb-3">
                    <button type="button" class="btn btn-warning" id="package-update-btn" onclick="startPackageUpdate()">
                        <i class="fa fa-refresh"></i> Update Packages
                    </button>
                    <button type="button" class="btn btn-secondary" id="package-check-btn" onclick="checkPackageUpdates()">
                        <i class="fa fa-search"></i> Check Updates
                    </button>
                </div>
                <div id="package-status" class="alert alert-info" style="display: none;">
                    <strong>Available Updates:</strong>
                    <div id="package-status-content"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Output Console -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">
                        <i class="fa fa-terminal"></i> Update Output
                    </h5>
                    <div>
                        <button type="button" class="btn btn-sm btn-secondary" onclick="clearOutput()">
                            <i class="fa fa-eraser"></i> Clear
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <textarea id="update-output" class="form-control" rows="20" readonly style="font-family: monospace; background-color: #2d3748; color: #e2e8f0; border: 1px solid #4a5568;" placeholder="Update output will appear here..."></textarea>
                <div class="progress" id="update-progress" style="display: none; margin-top: 10px;">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
                        <span class="visually-hidden">Update in progress...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let updateInProgress = false;
let currentUpdateType = '';

function appendOutput(message) {
    const output = document.getElementById('update-output');
    const timestamp = new Date().toLocaleTimeString();
    output.value += `[${timestamp}] ${message}\n`;
    output.scrollTop = output.scrollHeight;
}

function setUpdateInProgress(inProgress, type = '') {
    updateInProgress = inProgress;
    currentUpdateType = type;
    
    // Disable/enable buttons (check if they exist first)
    const buttons = [
        'package-update-btn', 'package-check-btn', 'release-update-btn', 
        'release-status-btn', 'check-release-btn'
    ];
    
    buttons.forEach(buttonId => {
        const button = document.getElementById(buttonId);
        if (button) {
            button.disabled = inProgress;
        }
    });
    
    // Show/hide progress bar
    const progress = document.getElementById('update-progress');
    if (inProgress) {
        progress.style.display = 'block';
        appendOutput(`Starting ${type} update...`);
    } else {
        progress.style.display = 'none';
        if (type) {
            appendOutput(`${type} update completed.\n`);
        }
    }
}

function clearOutput() {
    if (!updateInProgress) {
        document.getElementById('update-output').value = '';
    }
}

// Release System Functions
function checkForUpdates() {
    if (updateInProgress) return;
    
    appendOutput('Checking for WHP updates...');
    
    const currentVersion = '<?php echo htmlspecialchars($current_version); ?>';
    const releaseServer = '<?php echo htmlspecialchars($release_server); ?>';
    
    fetch(`${releaseServer}/api/check.php?version=${currentVersion}`)
    .then(response => response.json())
    .then(data => {
        const updateInfo = document.getElementById('update-info');
        const updateAvailableInfo = document.getElementById('update-available-info');
        
        if (data.update_available) {
            if (data.update_possible) {
                updateAvailableInfo.innerHTML = `
                    <strong>Update Available!</strong><br>
                    Current: ${data.current_version}<br>
                    Latest: ${data.latest_version}<br>
                    Size: ${formatBytes(data.size)}<br>
                    <small class="text-muted">Released: ${new Date(data.release_date).toLocaleDateString()}</small>
                `;
                updateAvailableInfo.className = 'alert alert-success';
                updateInfo.style.display = 'block';
                
                appendOutput(`Update available: ${data.current_version} → ${data.latest_version}`);
            } else {
                updateAvailableInfo.innerHTML = `
                    <strong>Update Required!</strong><br>
                    ${data.error}<br>
                    <small class="text-muted">Your version (${data.current_version}) is too old. Please contact support.</small>
                `;
                updateAvailableInfo.className = 'alert alert-warning';
                updateInfo.style.display = 'block';
                
                appendOutput(`Update blocked: ${data.error}`);
            }
        } else {
            updateAvailableInfo.innerHTML = `
                <strong>Up to Date!</strong><br>
                Current version: ${data.current_version}<br>
                <small class="text-muted">You are running the latest version.</small>
            `;
            updateAvailableInfo.className = 'alert alert-info';
            updateInfo.style.display = 'block';
            
            appendOutput('No updates available. You are running the latest version.');
        }
    })
    .catch(error => {
        appendOutput(`ERROR checking for updates: ${error.message}`);
        const updateInfo = document.getElementById('update-info');
        const updateAvailableInfo = document.getElementById('update-available-info');
        updateAvailableInfo.innerHTML = `
            <strong>Update Check Failed</strong><br>
            Unable to contact update server.<br>
            <small class="text-muted">Please check your internet connection.</small>
        `;
        updateAvailableInfo.className = 'alert alert-danger';
        updateInfo.style.display = 'block';
    });
}

function startReleaseUpdate() {
    if (updateInProgress) return;
    
    if (!confirm('This will update WHP to the latest release. Continue?')) {
        return;
    }
    
    setUpdateInProgress(true, 'Release');
    
    fetch('/api/update-management.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': '<?php echo get_csrf_token(); ?>',
        },
        body: JSON.stringify({
            action: 'release_update'
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        function readStream() {
            return reader.read().then(({ done, value }) => {
                if (done) {
                    setUpdateInProgress(false, 'Release');
                    appendOutput('Release update completed. Please refresh the page.');
                    return;
                }
                
                const chunk = decoder.decode(value);
                const lines = chunk.split('\\n');
                
                lines.forEach(line => {
                    if (line.trim()) {
                        try {
                            const data = JSON.parse(line);
                            if (data.output) {
                                appendOutput(data.output);
                            }
                            if (data.error) {
                                appendOutput(`ERROR: ${data.error}`);
                            }
                            if (data.heartbeat) {
                                // Just keep connection alive, don't display heartbeat
                                console.log('Heartbeat received');
                            }
                        } catch (e) {
                            // If not JSON, treat as plain text
                            appendOutput(line);
                        }
                    }
                });
                
                return readStream();
            });
        }
        
        return readStream();
    })
    .catch(error => {
        appendOutput(`ERROR: ${error.message}`);
        setUpdateInProgress(false);
    });
}

function startPackageUpdate() {
    if (updateInProgress) return;
    
    setUpdateInProgress(true, 'Package');
    
    fetch('/api/update-management.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': '<?php echo get_csrf_token(); ?>',
        },
        body: JSON.stringify({
            action: 'package_update'
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        function readStream() {
            return reader.read().then(({ done, value }) => {
                if (done) {
                    setUpdateInProgress(false, 'Package');
                    return;
                }
                
                const chunk = decoder.decode(value);
                const lines = chunk.split('\\n');
                
                lines.forEach(line => {
                    if (line.trim()) {
                        try {
                            const data = JSON.parse(line);
                            if (data.output) {
                                appendOutput(data.output);
                            }
                            if (data.error) {
                                appendOutput(`ERROR: ${data.error}`);
                            }
                            if (data.heartbeat) {
                                // Just keep connection alive, don't display heartbeat
                                console.log('Heartbeat received');
                            }
                        } catch (e) {
                            // If not JSON, treat as plain text
                            appendOutput(line);
                        }
                    }
                });
                
                return readStream();
            });
        }
        
        return readStream();
    })
    .catch(error => {
        appendOutput(`ERROR: ${error.message}`);
        setUpdateInProgress(false);
    });
}

function checkPackageUpdates() {
    if (updateInProgress) return;
    
    fetch('/api/update-management.php?action=package_check')
    .then(response => response.json())
    .then(data => {
        const statusDiv = document.getElementById('package-status');
        const contentDiv = document.getElementById('package-status-content');
        
        if (data.status === 'success') {
            contentDiv.innerHTML = `<pre>${data.data}</pre>`;
            statusDiv.style.display = 'block';
        } else {
            contentDiv.innerHTML = `Error: ${data.error || data.message || 'Unknown error'}`;
            statusDiv.className = 'alert alert-danger';
            statusDiv.style.display = 'block';
        }
    })
    .catch(error => {
        appendOutput(`ERROR checking package updates: ${error.message}`);
    });
}

function showReleaseInfo() {
    const modalHTML = `
        <div class="modal fade" id="releaseInfoModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">WHP Release System</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p><strong>What is the Release System?</strong></p>
                        <p>The WHP Release System provides:</p>
                        <ul>
                            <li><strong>Version Tracking:</strong> Know exactly which version you're running</li>
                            <li><strong>Security:</strong> Cryptographic verification of updates</li>
                            <li><strong>Reliability:</strong> Automatic backups before updates</li>
                            <li><strong>Rollback:</strong> Ability to revert problematic updates</li>
                            <li><strong>Migration Handling:</strong> Database schema updates</li>
                        </ul>
                        <p><strong>How it works:</strong></p>
                        <ol>
                            <li>Check for updates from the official release server</li>
                            <li>Download verified packages with checksums</li>
                            <li>Apply updates safely with automatic rollback on failure</li>
                        </ol>
                        <p><strong>Release Server:</strong></p>
                        <p><a href="${'<?php echo htmlspecialchars($release_server); ?>'}" target="_blank">${'<?php echo htmlspecialchars($release_server); ?>'}</a></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    const existing = document.getElementById('releaseInfoModal');
    if (existing) existing.remove();
    
    // Add modal to body
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('releaseInfoModal'));
    modal.show();
}

// Utility function to format bytes
function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

// Auto-refresh status on page load
document.addEventListener('DOMContentLoaded', function() {
    checkForUpdates();
});
</script>