<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';
include 'includes/SystemUpdateManager.php';
include 'includes/ChecksumManager.php';

// Check if admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Initialize managers
$updateManager = new SystemUpdateManager($conn);
$checksumManager = new ChecksumManager();

// Get system information
$version_query = "SELECT setting_value FROM settings WHERE setting_key = 'system_version'";
$version_result = mysqli_query($conn, $version_query);
$current_version = mysqli_fetch_assoc($version_result)['setting_value'] ?? '1.0.0';

$last_check_query = "SELECT setting_value FROM settings WHERE setting_key = 'last_update_check'";
$last_check_result = mysqli_query($conn, $last_check_query);
$last_check = mysqli_fetch_assoc($last_check_result)['setting_value'] ?? 'Never';

// Create required tables if they don't exist
$tables_sql = "
CREATE TABLE IF NOT EXISTS system_updates (
    update_id INT AUTO_INCREMENT PRIMARY KEY,
    version VARCHAR(50) NOT NULL,
    description TEXT,
    update_files JSON,
    db_changes JSON,
    release_date DATE,
    installed_date TIMESTAMP NULL,
    installed_by INT,
    status ENUM('AVAILABLE','INSTALLING','INSTALLED','FAILED') DEFAULT 'AVAILABLE',
    error_message TEXT,
    checksum VARCHAR(64),
    backup_file VARCHAR(255),
    FOREIGN KEY (installed_by) REFERENCES users(user_id)
);

CREATE TABLE IF NOT EXISTS update_logs (
    log_id INT AUTO_INCREMENT PRIMARY KEY,
    update_id INT,
    log_type ENUM('INFO', 'WARNING', 'ERROR') DEFAULT 'INFO',
    message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (update_id) REFERENCES system_updates(update_id)
);
";

mysqli_multi_query($conn, $tables_sql);
while(mysqli_next_result($conn));

// Get update history
$history_sql = "SELECT u.*, us.username 
               FROM system_updates u
               LEFT JOIN users us ON u.installed_by = us.user_id
               ORDER BY u.installed_date DESC";
$history_result = $conn->query($history_sql);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'System Updates')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        /* Update System Styles */

/* Changelog styles */
.changelog {
    max-height: 200px;
    overflow-y: auto;
    white-space: pre-line;
    font-size: 0.9rem;
    padding: 0.5rem;
    background-color: #f8f9fa;
    border-radius: 0.25rem;
}

/* Update steps */
#updateSteps {
    margin-bottom: 1rem;
}

.step {
    padding: 0.5rem;
    margin-bottom: 0.5rem;
    border-radius: 0.25rem;
    background-color: #f8f9fa;
    color: #6c757d;
}

.step.current {
    background-color: #e9ecef;
    color: #000;
    font-weight: 500;
}

.step.completed {
    background-color: #d1e7dd;
    color: #0f5132;
}

/* Log entries */
.update-log {
    max-height: 300px;
    overflow-y: auto;
    padding: 1rem;
    background-color: #f8f9fa;
    border-radius: 0.25rem;
}

.log-entry {
    border-left: 3px solid #dee2e6;
    padding-left: 1rem;
    margin-bottom: 0.75rem;
}

.log-message {
    margin-top: 0.25rem;
}

.log-message.info-log {
    color: #0c5460;
}

.log-message.warning-log {
    color: #856404;
}

.log-message.error-log {
    color: #721c24;
}

/* Pre blocks in tables */
table pre {
    margin: 0;
    background-color: #f8f9fa;
    padding: 0.5rem;
    border-radius:
}
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'System Updates')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <!-- System Status Cards -->
                            <div class="row">
                                <!-- Current System Status -->
                                <div class="col-md-6">
                                    <div class="card border">
                                        <div class="card-header bg-soft-primary">
                                            <div class="d-flex align-items-center">
                                                <div class="flex-grow-1">
                                                    <h5 class="card-title mb-0 text-primary">Current System Status</h5>
                                                </div>
                                                <div class="flex-shrink-0">
                                                    <button type="button" class="btn btn-primary btn-sm" id="checkUpdates">
                                                        <i class="ri-refresh-line align-middle me-1"></i> Check Updates
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <table class="table table-sm table-borderless mb-0">
                                                <tr>
                                                    <th width="40%">Current Version:</th>
                                                    <td>
                                                        <span class="badge bg-primary" id="currentVersion">
                                                            <?php echo htmlspecialchars($current_version); ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th>Last Update Check:</th>
                                                    <td id="lastCheck">
                                                        <?php echo $last_check !== 'Never' ? date('Y-m-d H:i', strtotime($last_check)) : 'Never'; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th>Update Status:</th>
                                                    <td>
                                                        <span id="updateStatus" class="badge bg-success">Up to date</span>
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>

                                <!-- System Information -->
                                <div class="col-md-6">
                                    <div class="card border">
                                        <div class="card-header bg-soft-info">
                                            <h5 class="card-title mb-0 text-info">System Information</h5>
                                        </div>
                                        <div class="card-body">
                                            <table class="table table-sm table-borderless mb-0">
                                                <tr>
                                                    <th width="40%">PHP Version:</th>
                                                    <td><?php echo phpversion(); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>MySQL Version:</th>
                                                    <td><?php echo mysqli_get_server_info($conn); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Server Software:</th>
                                                    <td><?php echo $_SERVER['SERVER_SOFTWARE']; ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Update Server:</th>
                                                    <td class="text-wrap">
                                                        <?php echo $updateManager->getUpdateServer(); ?>
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Available Updates Section -->
                            <div id="updatesList" class="d-none mt-4">
                                <div class="card border">
                                    <div class="card-header bg-soft-warning">
                                        <div class="d-flex align-items-center">
                                            <div class="flex-grow-1">
                                                <h5 class="card-title mb-0 text-warning">Available Updates</h5>
                                            </div>
                                            <div class="flex-shrink-0">
                                                <span id="updateBadge" class="badge bg-warning">New Update</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div id="updateAlerts"></div>
                                        <div class="table-responsive">
                                            <table class="table table-bordered align-middle mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Version</th>
                                                        <th>Release Date</th>
                                                        <th width="40%">Changes</th>
                                                        <th>Requirements</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="updatesTableBody">
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Update History -->
                            <div class="card border mt-4">
                                <div class="card-header bg-soft-secondary">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h5 class="card-title mb-0 text-secondary">Update History</h5>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <button type="button" class="btn btn-sm btn-secondary" onclick="downloadUpdateReport()">
                                                <i class="ri-download-2-line align-middle me-1"></i>Download Report
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Version</th>
                                                    <th>Date</th>
                                                    <th>Status</th>
                                                    <th>Installed By</th>
                                                    <th>Verification</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($row = $history_result->fetch_assoc()): 
                                                    $status_class = match($row['status']) {
                                                        'INSTALLED' => 'success',
                                                        'FAILED' => 'danger',
                                                        'INSTALLING' => 'warning',
                                                        default => 'info'
                                                    };
                                                ?>
                                                <tr>
                                                    <td>
                                                        <span class="fw-medium"><?php echo htmlspecialchars($row['version']); ?></span>
                                                    </td>
                                                    <td>
                                                        <?php echo $row['installed_date'] ? date('Y-m-d H:i', strtotime($row['installed_date'])) : ''; ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $status_class; ?>">
                                                            <?php echo $row['status']; ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($row['username'] ?? 'N/A'); ?></td>
                                                    <td>
                                                        <?php if ($row['checksum']): ?>
                                                            <span class="badge bg-info" title="<?php echo $row['checksum']; ?>">
                                                                <i class="ri-checkbox-circle-line align-middle"></i> Verified
                                                            </span>
                                                        <?php else: ?>
                                                            <span class="badge bg-warning">Not Verified</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="dropdown">
                                                            <button class="btn btn-soft-secondary btn-sm dropdown" type="button" data-bs-toggle="dropdown">
                                                                <i class="ri-more-fill align-middle"></i>
                                                            </button>
                                                            <ul class="dropdown-menu dropdown-menu-end">
                                                                <li>
                                                                    <a class="dropdown-item" href="javascript:void(0);" 
                                                                       onclick="viewUpdateDetails(<?php echo $row['update_id']; ?>)">
                                                                        <i class="ri-eye-fill align-bottom me-2 text-muted"></i> View Details
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="javascript:void(0);" 
                                                                       onclick="viewUpdateLogs(<?php echo $row['update_id']; ?>)">
                                                                        <i class="ri-file-list-3-line align-bottom me-2 text-muted"></i> View Logs
                                                                    </a>
                                                                </li>
                                                                <?php if ($row['status'] === 'FAILED' && $row['backup_file']): ?>
                                                                    <li>
                                                                        <a class="dropdown-item" href="javascript:void(0);" 
                                                                           onclick="restoreBackup(<?php echo $row['update_id']; ?>)">
                                                                            <i class="ri-replay-line align-bottom me-2 text-muted"></i> Restore Backup
                                                                        </a>
                                                                    </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
<!-- Update Details Modal -->
<div class="modal fade" id="updateDetailsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="updateDetailsContent">
                    <!-- Content will be loaded dynamically -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Update Logs Modal -->
<div class="modal fade" id="updateLogsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Logs</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="update-log custom-scroll" id="updateLogsContent">
                    <!-- Logs will be loaded dynamically -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="downloadUpdateLog()">
                    <i class="ri-download-2-line align-middle me-1"></i>
                    Download Logs
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Update Confirmation Modal -->
<div class="modal fade" id="updateConfirmationModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Install Update</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning mb-3">
                    <i class="ri-alert-line me-2"></i>
                    Please ensure you have backed up your system before proceeding.
                </div>
                
                <h6 class="fw-medium mb-2">Pre-update Checklist:</h6>
                <ul class="update-checklist">
                    <li>Back up the database</li>
                    <li>Back up custom files and configurations</li>
                    <li>Enable maintenance mode</li>
                    <li>Inform users about the update</li>
                </ul>

                <div class="form-check">
                    <input type="checkbox" class="form-check-input" id="confirmBackup" required>
                    <label class="form-check-label" for="confirmBackup">
                        I confirm that I have completed the above checklist
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="startUpdateBtn" disabled>
                    <i class="ri-download-cloud-2-line align-middle me-1"></i>
                    Start Update
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Update Progress Modal -->
<div class="modal fade" id="updateProgressModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Installing Update</h5>
            </div>
            <div class="modal-body">
                <div id="updateSteps">
                    <div class="step current">
                        <i class="ri-download-cloud-line me-1"></i> Downloading update package...
                    </div>
                    <div class="step">
                        <i class="ri-shield-check-line me-1"></i> Verifying package...
                    </div>
                    <div class="step">
                        <i class="ri-database-2-line me-1"></i> Creating backup...
                    </div>
                    <div class="step">
                        <i class="ri-install-line me-1"></i> Installing update...
                    </div>
                </div>
                
                <div class="progress mt-4">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                         role="progressbar" style="width: 0%"></div>
                </div>
                
                <div id="currentAction" class="small text-muted mt-2 text-center"></div>
            </div>
        </div>
    </div>
</div>

<!-- Restore Backup Confirmation Modal -->
<div class="modal fade" id="restoreBackupModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Restore Backup</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="ri-alert-line me-2"></i>
                    <strong>Warning:</strong> Restoring from backup will revert all changes made during the update.
                    This action cannot be undone.
                </div>
                
                <p>Are you sure you want to restore the system to its previous state?</p>
                
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" id="confirmRestore" required>
                    <label class="form-check-label" for="confirmRestore">
                        I understand that this will revert all changes
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="startRestoreBtn" disabled>
                    <i class="ri-replay-line align-middle me-1"></i>
                    Restore System
                </button>
            </div>
        </div>
    </div>
</div>
    <!-- Scripts -->
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        // Global configuration
    const updateConfig = {
        updateServer: document.querySelector('meta[name="update-server"]')?.content || '',
        currentVersion: document.querySelector('meta[name="current-version"]')?.content || '1.0.0'
    };
    
    // Main initialization
    document.addEventListener('DOMContentLoaded', function() {
        initializeUpdateSystem();
    });
    
    function initializeUpdateSystem() {
        // Element references
        const elements = {
            checkUpdatesBtn: document.getElementById('checkUpdates'),
            updatesList: document.getElementById('updatesList'),
            updatesTableBody: document.getElementById('updatesTableBody'),
            updateStatus: document.getElementById('updateStatus'),
            lastCheck: document.getElementById('lastCheck'),
            currentVersion: document.getElementById('currentVersion')
        };
    
        // Event listeners
        elements.checkUpdatesBtn.addEventListener('click', () => checkForUpdates(elements));
    }
    
    async function checkForUpdates(elements) {
        try {
            showLoading('Checking for Updates', 'Please wait while we check for system updates...');
    
            const response = await fetch('check_updates.php');
            const data = await response.json();
    
            Swal.close();
    
            if (data.error) {
                throw new Error(data.error);
            }
    
            // Update last check time
            elements.lastCheck.textContent = new Date().toLocaleString();
    
            if (data.updates && data.updates.length > 0) {
                showAvailableUpdates(data.updates, elements);
            } else {
                showSuccess('System Up to Date', 'Your system is running the latest version.');
                updateSystemStatus(elements, 'success', 'Up to date');
                elements.updatesList.classList.add('d-none');
            }
        } catch (error) {
            showError('Update Check Failed', error.message);
        }
    }
    
    function showAvailableUpdates(updates, elements) {
        elements.updatesTableBody.innerHTML = '';
        updateSystemStatus(elements, 'warning', 'Update Available');
    
        updates.forEach(update => {
            const row = createUpdateRow(update);
            elements.updatesTableBody.appendChild(row);
        });
    
        elements.updatesList.classList.remove('d-none');
    }
    
    function createUpdateRow(update) {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <span class="fw-medium">${update.version}</span>
                ${update.min_version ? `<br><small class="text-muted">Requires ${update.min_version}+</small>` : ''}
            </td>
            <td>${update.release_date}</td>
            <td>
                <div class="changelog">${update.changelog}</div>
            </td>
            <td>
                <div class="small">
                    <i class="ri-information-line text-info me-1"></i>
                    ${update.requirements || 'No special requirements'}
                </div>
                <div class="small mt-1">
                    <i class="ri-file-zip-line text-muted me-1"></i>
                    ${update.package_size || 'Unknown size'}
                </div>
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-primary" 
                        onclick="installUpdate('${update.version}')">
                    <i class="ri-download-cloud-2-line align-middle me-1"></i>
                    Install Update
                </button>
            </td>
        `;
        return row;
    }
    
    async function installUpdate(version) {
        const result = await Swal.fire({
            title: 'Install Update',
            html: createUpdateConfirmationHtml(),
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Install Update',
            cancelButtonText: 'Cancel',
            allowOutsideClick: false,
            preConfirm: () => {
                if (!document.getElementById('confirmBackup').checked) {
                    Swal.showValidationMessage('Please confirm you have backed up the system');
                    return false;
                }
                return true;
            }
        });
    
        if (result.isConfirmed) {
            performUpdate(version);
        }
    }
    
    async function performUpdate(version) {
        try {
            showUpdateProgress();
    
            const response = await fetch('install_update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ version: version })
            });
    
            const data = await response.json();
    
            if (data.error) {
                throw new Error(data.error);
            }
    
            await Swal.fire({
                icon: 'success',
                title: 'Update Complete',
                text: 'The system has been updated successfully. The page will now refresh.',
                allowOutsideClick: false,
                confirmButtonText: 'Refresh Now'
            });
    
            window.location.reload();
        } catch (error) {
            showError('Update Failed', error.message);
        }
    }
    
    async function viewUpdateDetails(updateId) {
        try {
            const response = await fetch(`get_update_details.php?id=${updateId}`);
            const data = await response.json();
    
            if (data.error) throw new Error(data.error);
    
            const modalContent = document.getElementById('updateDetailsContent');
            modalContent.innerHTML = createUpdateDetailsHtml(data);
    
            new bootstrap.Modal(document.getElementById('updateDetailsModal')).show();
        } catch (error) {
            showError('Error', error.message);
        }
    }
    
    async function viewUpdateLogs(updateId) {
        try {
            const response = await fetch(`get_update_logs.php?id=${updateId}`);
            const data = await response.json();
    
            if (data.error) throw new Error(data.error);
    
            const logsContent = document.getElementById('updateLogsContent');
            logsContent.innerHTML = createUpdateLogsHtml(data.logs);
    
            new bootstrap.Modal(document.getElementById('updateLogsModal')).show();
        } catch (error) {
            showError('Error', error.message);
        }
    }
    
    async function restoreBackup(updateId) {
        const result = await Swal.fire({
            title: 'Restore Backup',
            text: 'Are you sure you want to restore the system from backup? This will revert all changes made during the update.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, Restore',
            cancelButtonText: 'Cancel',
            allowOutsideClick: false
        });
    
        if (result.isConfirmed) {
            try {
                showLoading('Restoring Backup', 'Please wait while we restore the system...');
    
                const response = await fetch('restore_backup.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ update_id: updateId })
                });
    
                const data = await response.json();
    
                if (data.error) throw new Error(data.error);
    
                await Swal.fire({
                    icon: 'success',
                    title: 'Restore Complete',
                    text: 'The system has been restored successfully. The page will now refresh.',
                    allowOutsideClick: false,
                    confirmButtonText: 'Refresh Now'
                });
    
                window.location.reload();
            } catch (error) {
                showError('Restore Failed', error.message);
            }
        }
    }
    
    function downloadUpdateReport() {
        window.location.href = 'download_update_report.php';
    }
    
    // UI Helper Functions
    function updateSystemStatus(elements, type, message) {
        elements.updateStatus.className = `badge bg-${type}`;
        elements.updateStatus.textContent = message;
    }
    
    function showLoading(title, text) {
        Swal.fire({
            title: title,
            text: text,
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
    }
    
    function showSuccess(title, text) {
        Swal.fire({
            icon: 'success',
            title: title,
            text: text
        });
    }
    
    function showError(title, text) {
        Swal.fire({
            icon: 'error',
            title: title,
            text: text
        });
    }
    
    // HTML Template Functions
    function createUpdateConfirmationHtml() {
        return `
            <div class="text-start">
                <p>Before proceeding with the update:</p>
                <ul>
                    <li>Ensure you have backed up your database</li>
                    <li>Put the system in maintenance mode</li>
                    <li>Inform users about the update</li>
                </ul>
                <div class="form-check mt-3">
                    <input class="form-check-input" type="checkbox" id="confirmBackup">
                    <label class="form-check-label" for="confirmBackup">
                        I confirm that I have backed up the system
                    </label>
                </div>
            </div>
        `;
    }
    
    function showUpdateProgress() {
        Swal.fire({
            title: 'Installing Update',
            html: `
                <div class="text-start">
                    <div id="updateSteps">
                        <div class="step current">
                            <i class="ri-download-cloud-line me-1"></i> Downloading update package...
                        </div>
                        <div class="step">
                            <i class="ri-shield-check-line me-1"></i> Verifying package...
                        </div>
                        <div class="step">
                            <i class="ri-database-2-line me-1"></i> Creating backup...
                        </div>
                        <div class="step">
                            <i class="ri-install-line me-1"></i> Installing update...
                        </div>
                    </div>
                    <div class="progress mt-3">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" 
                             role="progressbar" style="width: 0%"></div>
                    </div>
                    <div id="currentAction" class="small text-muted mt-2"></div>
                </div>
            `,
            allowOutsideClick: false,
            showConfirmButton: false
        });
    }
    
    function createUpdateDetailsHtml(data) {
        return `
            <table class="table table-bordered">
                <tr>
                    <th width="30%">Version</th>
                    <td>${data.version}</td>
                </tr>
                <tr>
                    <th>Status</th>
                    <td>
                        <span class="badge bg-${data.status === 'INSTALLED' ? 'success' : 'danger'}">
                            ${data.status}
                        </span>
                    </td>
                </tr>
                <tr>
                    <th>Installation Date</th>
                    <td>${data.installed_date}</td>
                </tr>
                <tr>
                    <th>Installed By</th>
                    <td>${data.installed_by}</td>
                </tr>
                <tr>
                    <th>Changes</th>
                    <td>
                        <pre class="mb-0" style="max-height: 200px; overflow-y: auto;">
                            ${data.description}
                        </pre>
                    </td>
                </tr>
                ${data.error_message ? `
                    <tr>
                        <th>Error Details</th>
                        <td>
                            <pre class="text-danger mb-0">${data.error_message}</pre>
                        </td>
                    </tr>
                ` : ''}
                ${createFileChangesHtml(data)}
            </table>
        `;
    }
    
    function createFileChangesHtml(data) {
        let html = '';
        if (data.update_files) {
            html += `
                <tr>
                    <th>Updated Files</th>
                    <td>
                        <pre class="mb-0" style="max-height: 150px; overflow-y: auto;">
                            ${JSON.parse(data.update_files).join('\n')}
                        </pre>
                    </td>
                </tr>
            `;
        }
        if (data.db_changes) {
            html += `
                <tr>
                    <th>Database Changes</th>
                    <td>
                        <pre class="mb-0" style="max-height: 150px; overflow-y: auto;">
                            ${JSON.stringify(JSON.parse(data.db_changes), null, 2)}
                        </pre>
                    </td>
                </tr>
            `;
        }
        return html;
    }
    
    function createUpdateLogsHtml(logs) {
        return logs.map(log => `
            <div class="log-entry mb-2">
                <small class="text-muted">${log.created_at}</small>
                <div class="log-message ${log.log_type.toLowerCase()}-log">
                    <i class="ri-information-line me-1"></i>
                    ${log.message}
                </div>
            </div>
        `).join('');
    }
    </script>
</body>
</html>