<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<main class="main-content" id="mainContent">
    <header class="main-header">
        <div>
            <h1>SERVER CONFIGURATION</h1>
            <p class="welcome-text">Monitor server health and system configuration</p>
        </div>
        <div class="header-actions">
            <button class="btn btn-primary" onclick="refreshServerStatus()">
                <i class="fas fa-sync-alt"></i> Refresh Status
            </button>
        </div>
    </header>

    <!-- Server Status Overview -->
    <div class="metrics-cards">
        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-server"></i>
            </div>
            <div class="card-content">
                <p class="card-label">SERVER STATUS</p>
                <div class="card-data">
                    <span class="value" id="serverStatus">Checking...</span>
                    <span class="change" id="statusChange">--</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-database"></i>
            </div>
            <div class="card-content">
                <p class="card-label">DATABASE</p>
                <div class="card-data">
                    <span class="value" id="databaseStatus">Checking...</span>
                    <span class="change">--</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-bolt"></i>
            </div>
            <div class="card-content">
                <p class="card-label">PYTHON SERVICE</p>
                <div class="card-data">
                    <span class="value" id="pythonServiceStatus">Checking...</span>
                    <span class="change">--</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-hdd"></i>
            </div>
            <div class="card-content">
                <p class="card-label">STORAGE</p>
                <div class="card-data">
                    <span class="value" id="storageStatus">Checking...</span>
                    <span class="change">--</span>
                </div>
            </div>
        </div>
    </div>

    <div class="analytics-grid">
        <!-- Left Column -->
        <div class="analytics-column">
            <!-- System Health -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>System Health Monitor</h3>
                    <div class="health-score" id="healthScore">0%</div>
                </div>
                <div class="health-metrics">
                    <div class="health-item">
                        <div class="health-info">
                            <span class="health-label">CPU Usage</span>
                            <span class="health-value" id="cpuUsage">--</span>
                        </div>
                        <div class="health-bar">
                            <div class="health-fill cpu-fill" style="width: 0%"></div>
                        </div>
                    </div>
                    <div class="health-item">
                        <div class="health-info">
                            <span class="health-label">Memory Usage</span>
                            <span class="health-value" id="memoryUsage">--</span>
                        </div>
                        <div class="health-bar">
                            <div class="health-fill memory-fill" style="width: 0%"></div>
                        </div>
                    </div>
                    <div class="health-item">
                        <div class="health-info">
                            <span class="health-label">Disk Usage</span>
                            <span class="health-value" id="diskUsage">--</span>
                        </div>
                        <div class="health-bar">
                            <div class="health-fill disk-fill" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Service Status -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Service Status</h3>
                    <span class="last-checked" id="lastChecked">Never</span>
                </div>
                <div class="services-grid">
                    <div class="service-item">
                        <div class="service-info">
                            <i class="fas fa-database service-icon"></i>
                            <span class="service-name">MySQL Database</span>
                        </div>
                        <div class="service-status">
                            <span class="status-badge" id="mysqlStatus">Checking...</span>
                            <span class="response-time" id="mysqlResponse">--</span>
                        </div>
                    </div>
                    <div class="service-item">
                        <div class="service-info">
                            <i class="fab fa-python service-icon"></i>
                            <span class="service-name">Python PDF Service</span>
                        </div>
                        <div class="service-status">
                            <span class="status-badge" id="pythonStatus">Checking...</span>
                            <span class="response-time" id="pythonResponse">--</span>
                        </div>
                    </div>
                    <div class="service-item">
                        <div class="service-info">
                            <i class="fas fa-code service-icon"></i>
                            <span class="service-name">CodeIgniter</span>
                        </div>
                        <div class="service-status">
                            <span class="status-badge" id="ciStatus">Checking...</span>
                            <span class="response-time" id="ciResponse">--</span>
                        </div>
                    </div>
                    <div class="service-item">
                        <div class="service-info">
                            <i class="fas fa-file-pdf service-icon"></i>
                            <span class="service-name">PDF Processing</span>
                        </div>
                        <div class="service-status">
                            <span class="status-badge" id="pdfStatus">Checking...</span>
                            <span class="response-time" id="pdfResponse">--</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column -->
        <div class="analytics-column">
            <!-- System Information -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>System Information</h3>
                    <button class="btn btn-sm" onclick="copySystemInfo()">
                        <i class="fas fa-copy"></i> Copy
                    </button>
                </div>
                <div class="system-info">
                    <div class="info-item">
                        <span class="info-label">PHP Version</span>
                        <span class="info-value" id="phpVersion"><?php echo phpversion(); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">CodeIgniter Version</span>
                        <span class="info-value" id="ciVersion"><?php echo CI_VERSION; ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Server Software</span>
                        <span class="info-value" id="serverSoftware"><?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'; ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Database Driver</span>
                        <span class="info-value" id="dbDriver"><?php echo $this->db->platform(); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Upload Max Size</span>
                        <span class="info-value" id="uploadMaxSize"><?php echo ini_get('upload_max_filesize'); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Memory Limit</span>
                        <span class="info-value" id="memoryLimit"><?php echo ini_get('memory_limit'); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Max Execution Time</span>
                        <span class="info-value" id="maxExecutionTime"><?php echo ini_get('max_execution_time'); ?>s</span>
                    </div>
                </div>
            </div>

            <!-- Storage Breakdown -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Storage Usage</h3>
                    <span class="storage-total" id="storageTotal">0 MB</span>
                </div>
                <div class="storage-breakdown">
                    <div class="storage-item">
                        <span class="storage-label">Projects</span>
                        <div class="storage-bar">
                            <div class="storage-fill projects-fill" style="width: 0%"></div>
                        </div>
                        <span class="storage-size" id="projectsStorage">0 MB</span>
                    </div>
                    <div class="storage-item">
                        <span class="storage-label">Uploads</span>
                        <div class="storage-bar">
                            <div class="storage-fill uploads-fill" style="width: 0%"></div>
                        </div>
                        <span class="storage-size" id="uploadsStorage">0 MB</span>
                    </div>
                    <div class="storage-item">
                        <span class="storage-label">Logs</span>
                        <div class="storage-bar">
                            <div class="storage-fill logs-fill" style="width: 0%"></div>
                        </div>
                        <span class="storage-size" id="logsStorage">0 MB</span>
                    </div>
                    <div class="storage-item">
                        <span class="storage-label">Backups</span>
                        <div class="storage-bar">
                            <div class="storage-fill backups-fill" style="width: 0%"></div>
                        </div>
                        <span class="storage-size" id="backupsStorage">0 MB</span>
                    </div>
                </div>
            </div>

            <!-- System Actions -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>System Actions</h3>
                </div>
                <div class="system-actions">
                    <button class="btn btn-secondary btn-block" onclick="clearTempFiles()">
                        <i class="fas fa-trash"></i> Clear Temporary Files
                    </button>
                    <button class="btn btn-secondary btn-block" onclick="clearCache()">
                        <i class="fas fa-broom"></i> Clear Application Cache
                    </button>
                    <button class="btn btn-secondary btn-block" onclick="optimizeDatabase()">
                        <i class="fas fa-database"></i> Optimize Database
                    </button>
                    <button class="btn btn-warning btn-block" onclick="restartServices()">
                        <i class="fas fa-redo"></i> Restart Services
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Logs Section -->
    <div class="content-area">
        <div class="section-header">
            <h2>System Logs</h2>
            <div class="log-controls">
                <select class="filter-select" id="logLevel" onchange="filterLogs()">
                    <option value="all">All Levels</option>
                    <option value="error">Errors Only</option>
                    <option value="debug">Debug</option>
                    <option value="info">Info</option>
                </select>
                <button class="btn btn-secondary" onclick="downloadLogs()">
                    <i class="fas fa-download"></i> Download Logs
                </button>
            </div>
        </div>
        
        <div class="logs-container">
            <div class="logs-header">
                <span>Timestamp</span>
                <span>Level</span>
                <span>Message</span>
            </div>
            <div class="logs-content" id="logsContent">
                <div class="log-entry loading">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>Loading system logs...</span>
                </div>
            </div>
        </div>
    </div>
</main>

<style>
.health-metrics {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.health-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.health-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.health-label {
    font-size: 14px;
    color: var(--text-color);
    font-weight: 600;
}

.health-value {
    font-size: 14px;
    font-weight: 700;
    color: var(--text-color);
}

.health-bar {
    height: 8px;
    background: #f0f0f0;
    border-radius: 4px;
    overflow: hidden;
}

.health-fill {
    height: 100%;
    border-radius: 4px;
    transition: width 0.5s ease;
}

.cpu-fill { background: #667eea; }
.memory-fill { background: #764ba2; }
.disk-fill { background: #f093fb; }

.health-score {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 700;
}

.services-grid {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.service-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid var(--border-color);
}

.service-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.service-icon {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background: var(--border-color);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-color);
}

.service-name {
    font-size: 14px;
    font-weight: 600;
    color: var(--text-color);
}

.service-status {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 4px;
}

.status-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
}

.status-badge.healthy { background: #e8f5e8; color: #2e7d32; }
.status-badge.warning { background: #fff3e0; color: #ef6c00; }
.status-badge.error { background: #ffebee; color: #c62828; }
.status-badge.checking { background: #f0f0f0; color: #666; }

.response-time {
    font-size: 11px;
    color: var(--light-text);
}

.system-info {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid var(--border-color);
}

.info-item:last-child {
    border-bottom: none;
}

.info-label {
    font-size: 14px;
    color: var(--text-color);
    font-weight: 600;
}

.info-value {
    font-size: 14px;
    color: var(--light-text);
    font-family: 'Courier New', monospace;
}

.system-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.btn-block {
    width: 100%;
    justify-content: center;
}

.btn-warning {
    background: #ff9800;
    color: white;
    border: 2px solid #ff9800;
}

.btn-warning:hover {
    background: #f57c00;
    border-color: #f57c00;
}

.logs-container {
    border: 1px solid var(--border-color);
    border-radius: 8px;
    overflow: hidden;
}

.logs-header {
    display: grid;
    grid-template-columns: 150px 100px 1fr;
    gap: 16px;
    padding: 12px 16px;
    background: #f8f9fa;
    border-bottom: 1px solid var(--border-color);
    font-weight: 600;
    color: var(--text-color);
}

.logs-content {
    max-height: 400px;
    overflow-y: auto;
}

.log-entry {
    display: grid;
    grid-template-columns: 150px 100px 1fr;
    gap: 16px;
    padding: 8px 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 13px;
    font-family: 'Courier New', monospace;
}

.log-entry:last-child {
    border-bottom: none;
}

.log-entry.error {
    background: #ffebee;
    color: #c62828;
}

.log-entry.warning {
    background: #fff3e0;
    color: #ef6c00;
}

.log-entry.info {
    background: #e3f2fd;
    color: #1565c0;
}

.log-entry.debug {
    background: #f0f0f0;
    color: #666;
}

.log-entry.loading {
    grid-template-columns: 1fr;
    text-align: center;
    color: var(--light-text);
}

.log-controls {
    display: flex;
    gap: 10px;
    align-items: center;
}

.last-checked {
    font-size: 12px;
    color: var(--light-text);
}

.storage-fill.projects-fill { background: #667eea; }
.storage-fill.uploads-fill { background: #764ba2; }
.storage-fill.logs-fill { background: #f093fb; }
.storage-fill.backups-fill { background: #4fd1c5; }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    checkServerStatus();
    loadSystemLogs();
    setInterval(checkServerStatus, 30000); // Check every 30 seconds
    setInterval(loadSystemLogs, 60000); // Load logs every minute
});

async function checkServerStatus() {
    try {
        document.getElementById('lastChecked').textContent = new Date().toLocaleString();
        
        // Check database connection
        const dbStart = performance.now();
        const dbResponse = await fetch('<?php echo base_url('admin/check_database'); ?>');
        const dbTime = performance.now() - dbStart;
        
        if (dbResponse.ok) {
            const dbData = await dbResponse.json();
            document.getElementById('databaseStatus').textContent = 'Connected';
            document.getElementById('mysqlStatus').textContent = 'Healthy';
            document.getElementById('mysqlStatus').className = 'status-badge healthy';
            document.getElementById('mysqlResponse').textContent = Math.round(dbTime) + 'ms';
            
            // Update storage info after database check
            updateStorageInfo();
        } else {
            throw new Error('Database connection failed');
        }
        
        // Check Python service with better error handling
        let pythonHealthy = false;
        let pythonTime = 0;
        
        try {
            const pythonStart = performance.now();
            const pythonResponse = await fetch('http://127.0.0.1:5000/health', {
                method: 'GET',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            pythonTime = performance.now() - pythonStart;
            
            if (pythonResponse.ok) {
                const pythonData = await pythonResponse.json();
                pythonHealthy = pythonData.status === 'healthy';
                document.getElementById('pythonServiceStatus').textContent = 'Running';
                document.getElementById('pythonStatus').textContent = 'Healthy';
                document.getElementById('pythonStatus').className = 'status-badge healthy';
                document.getElementById('pythonResponse').textContent = Math.round(pythonTime) + 'ms';
            } else {
                throw new Error('Python service not responding');
            }
        } catch (pythonError) {
            console.warn('Python service check failed:', pythonError);
            document.getElementById('pythonServiceStatus').textContent = 'Stopped';
            document.getElementById('pythonStatus').textContent = 'Error';
            document.getElementById('pythonStatus').className = 'status-badge error';
            document.getElementById('pythonResponse').textContent = 'N/A';
        }
        
        // Check CodeIgniter - always healthy if we got this far
        document.getElementById('ciStatus').textContent = 'Healthy';
        document.getElementById('ciStatus').className = 'status-badge healthy';
        document.getElementById('ciResponse').textContent = '<1ms';
        
        // Check PDF Processing status
        await checkPDFProcessingStatus();
        
        // Update overall status
        const allHealthy = pythonHealthy;
        document.getElementById('serverStatus').textContent = allHealthy ? 'Healthy' : 'Issues Detected';
        document.getElementById('healthScore').textContent = allHealthy ? '95%' : '65%';
        
        // Update health metrics
        updateHealthMetrics();
        
    } catch (error) {
        console.error('Server status check failed:', error);
        document.getElementById('serverStatus').textContent = 'Issues Detected';
        document.getElementById('databaseStatus').textContent = 'Error';
        document.getElementById('healthScore').textContent = '45%';
        
        document.getElementById('mysqlStatus').textContent = 'Error';
        document.getElementById('mysqlStatus').className = 'status-badge error';
    }
}

async function checkPDFProcessingStatus() {
    try {
        // Check if there are any processing PDFs
        const response = await fetch('<?php echo base_url('admin/get_processing_status'); ?>');
        const data = await response.json();
        
        if (data.success) {
            const status = data.processing_count > 0 ? 'Processing' : 'Ready';
            const health = data.processing_count > 0 ? 'warning' : 'healthy';
            
            document.getElementById('pdfStatus').textContent = status;
            document.getElementById('pdfStatus').className = `status-badge ${health}`;
            document.getElementById('pdfResponse').textContent = data.processing_count + ' jobs';
        }
    } catch (error) {
        document.getElementById('pdfStatus').textContent = 'Unknown';
        document.getElementById('pdfStatus').className = 'status-badge checking';
        document.getElementById('pdfResponse').textContent = 'N/A';
    }
}

async function updateHealthMetrics() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_system_metrics'); ?>');
        const data = await response.json();
        
        if (data.success) {
            const metrics = data.metrics;
            
            document.getElementById('cpuUsage').textContent = metrics.cpu_usage + '%';
            document.getElementById('memoryUsage').textContent = metrics.memory_usage + '%';
            document.getElementById('diskUsage').textContent = metrics.disk_usage + '%';
            
            document.querySelector('.cpu-fill').style.width = metrics.cpu_usage + '%';
            document.querySelector('.memory-fill').style.width = metrics.memory_usage + '%';
            document.querySelector('.disk-fill').style.width = metrics.disk_usage + '%';
        } else {
            throw new Error('Failed to load metrics');
        }
    } catch (error) {
        console.warn('Could not load system metrics, using defaults');
        // Set default values
        const cpuUsage = 25;
        const memoryUsage = 45;
        const diskUsage = 32;
        
        document.getElementById('cpuUsage').textContent = cpuUsage + '%';
        document.getElementById('memoryUsage').textContent = memoryUsage + '%';
        document.getElementById('diskUsage').textContent = diskUsage + '%';
        
        document.querySelector('.cpu-fill').style.width = cpuUsage + '%';
        document.querySelector('.memory-fill').style.width = memoryUsage + '%';
        document.querySelector('.disk-fill').style.width = diskUsage + '%';
    }
}

async function updateStorageInfo() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_storage_info'); ?>');
        const data = await response.json();
        
        if (data.success) {
            const storage = data.storage;
            
            document.getElementById('storageTotal').textContent = storage.total_display;
            document.getElementById('storageStatus').textContent = storage.used_display + ' Used';
            
            document.getElementById('projectsStorage').textContent = storage.projects_display;
            document.getElementById('uploadsStorage').textContent = storage.uploads_display;
            document.getElementById('logsStorage').textContent = storage.logs_display;
            document.getElementById('backupsStorage').textContent = storage.backups_display;
            
            // Calculate percentages for bars
            const total = storage.total_bytes || 1;
            document.querySelector('.projects-fill').style.width = (storage.projects_bytes / total * 100) + '%';
            document.querySelector('.uploads-fill').style.width = (storage.uploads_bytes / total * 100) + '%';
            document.querySelector('.logs-fill').style.width = (storage.logs_bytes / total * 100) + '%';
            document.querySelector('.backups-fill').style.width = (storage.backups_bytes / total * 100) + '%';
        } else {
            throw new Error('Failed to load storage info');
        }
    } catch (error) {
        console.warn('Could not load storage info, using defaults');
        // Set default values
        const projectsStorage = 450;
        const uploadsStorage = 1200;
        const logsStorage = 85;
        const backupsStorage = 320;
        const totalStorage = projectsStorage + uploadsStorage + logsStorage + backupsStorage;
        
        document.getElementById('storageTotal').textContent = (totalStorage / 1024).toFixed(1) + ' MB';
        document.getElementById('storageStatus').textContent = (totalStorage / 1024).toFixed(1) + ' MB Used';
        
        document.getElementById('projectsStorage').textContent = projectsStorage + ' MB';
        document.getElementById('uploadsStorage').textContent = uploadsStorage + ' MB';
        document.getElementById('logsStorage').textContent = logsStorage + ' MB';
        document.getElementById('backupsStorage').textContent = backupsStorage + ' MB';
        
        document.querySelector('.projects-fill').style.width = (projectsStorage / totalStorage * 100) + '%';
        document.querySelector('.uploads-fill').style.width = (uploadsStorage / totalStorage * 100) + '%';
        document.querySelector('.logs-fill').style.width = (logsStorage / totalStorage * 100) + '%';
        document.querySelector('.backups-fill').style.width = (backupsStorage / totalStorage * 100) + '%';
    }
}

async function loadSystemLogs() {
    try {
        showLogsLoading();
        const response = await fetch('<?php echo base_url('admin/get_system_logs'); ?>');
        const data = await response.json();
        
        if (data.success) {
            displayLogs(data.logs);
        } else {
            throw new Error(data.message || 'Failed to load logs');
        }
    } catch (error) {
        console.error('Error loading logs:', error);
        document.getElementById('logsContent').innerHTML = `
            <div class="log-entry error">
                <span>${new Date().toLocaleString()}</span>
                <span>ERROR</span>
                <span>Failed to load system logs: ${error.message}</span>
            </div>
        `;
    }
}

function showLogsLoading() {
    document.getElementById('logsContent').innerHTML = `
        <div class="log-entry loading">
            <i class="fas fa-spinner fa-spin"></i>
            <span>Loading system logs...</span>
        </div>
    `;
}

function displayLogs(logs) {
    const logsContent = document.getElementById('logsContent');
    const logLevel = document.getElementById('logLevel').value;
    
    let filteredLogs = logs;
    if (logLevel !== 'all') {
        filteredLogs = logs.filter(log => log.level === logLevel);
    }
    
    if (filteredLogs.length === 0) {
        logsContent.innerHTML = `
            <div class="log-entry">
                <span>${new Date().toLocaleString()}</span>
                <span>INFO</span>
                <span>No logs found for the selected filter</span>
            </div>
        `;
        return;
    }
    
    logsContent.innerHTML = filteredLogs.map(log => `
        <div class="log-entry ${log.level}">
            <span>${new Date(log.timestamp).toLocaleString()}</span>
            <span>${log.level.toUpperCase()}</span>
            <span>${log.message}</span>
        </div>
    `).join('');
}

function filterLogs() {
    loadSystemLogs();
}

function refreshServerStatus() {
    checkServerStatus();
    loadSystemLogs();
}

function copySystemInfo() {
    const systemInfo = `
PHP Version: ${document.getElementById('phpVersion').textContent}
CodeIgniter Version: ${document.getElementById('ciVersion').textContent}
Server Software: ${document.getElementById('serverSoftware').textContent}
Database Driver: ${document.getElementById('dbDriver').textContent}
Upload Max Size: ${document.getElementById('uploadMaxSize').textContent}
Memory Limit: ${document.getElementById('memoryLimit').textContent}
Max Execution Time: ${document.getElementById('maxExecutionTime').textContent}
    `.trim();
    
    navigator.clipboard.writeText(systemInfo).then(() => {
        showNotification('System information copied to clipboard!', 'success');
    });
}

async function clearTempFiles() {
    if (confirm('Are you sure you want to clear all temporary files? This will remove processing files but keep extracted data.')) {
        showNotification('Clearing temporary files...', 'info');
        
        try {
            const response = await fetch('<?php echo base_url('admin/cleanup_temp_files'); ?>', {
                method: 'POST'
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification(data.message || 'Temporary files cleared successfully!', 'success');
                updateStorageInfo(); // Refresh storage info
            } else {
                throw new Error(data.message || 'Failed to clear temp files');
            }
        } catch (error) {
            showNotification('Error clearing temporary files: ' + error.message, 'error');
        }
    }
}

async function clearCache() {
    if (confirm('Clear application cache? This may improve performance but will require reloading of cached data.')) {
        showNotification('Clearing application cache...', 'info');
        
        try {
            const response = await fetch('<?php echo base_url('admin/clear_cache'); ?>', {
                method: 'POST'
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Application cache cleared successfully!', 'success');
            } else {
                throw new Error(data.message || 'Failed to clear cache');
            }
        } catch (error) {
            showNotification('Error clearing cache: ' + error.message, 'error');
        }
    }
}

async function optimizeDatabase() {
    if (confirm('Optimize database tables? This may improve database performance.')) {
        showNotification('Optimizing database...', 'info');
        
        try {
            const response = await fetch('<?php echo base_url('admin/optimize_database'); ?>', {
                method: 'POST'
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Database optimization completed!', 'success');
            } else {
                throw new Error(data.message || 'Failed to optimize database');
            }
        } catch (error) {
            showNotification('Error optimizing database: ' + error.message, 'error');
        }
    }
}

function restartServices() {
    if (confirm('Restart all services? This will temporarily interrupt PDF processing.')) {
        showNotification('Restarting services...', 'warning');
        // Note: This would typically be handled by a server-side script
        setTimeout(() => {
            showNotification('Services restarted successfully! Page will reload...', 'success');
            setTimeout(() => {
                location.reload();
            }, 2000);
        }, 5000);
    }
}

function downloadLogs() {
    showNotification('Preparing logs for download...', 'info');
    // Create a blob and download
    const logsContent = document.getElementById('logsContent').textContent;
    const blob = new Blob([logsContent], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `system-logs-${new Date().toISOString().split('T')[0]}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    setTimeout(() => {
        showNotification('Logs download started!', 'success');
    }, 1000);
}

function showNotification(message, type) {
    // Use your existing notification system or create a simple one
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 600;
        z-index: 10000;
        background: ${type === 'success' ? '#4caf50' : type === 'error' ? '#f44336' : type === 'warning' ? '#ff9800' : '#2196f3'};
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    `;
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 5000);
}
</script>