<?php
/**
 * ============================================================================
 * admin/server-status.php - Server Status & Performance Monitoring
 * Real-time server health monitoring
 * ============================================================================
 */

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

// Check permission
if (!hasAdminPermission('view_server_stats')) {
    setFlashMessage('Access denied. Server statistics viewing permission required.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [
    ['title' => 'Server Status', 'url' => '']
];

// Get current server metrics
function getCurrentServerMetrics() {
    $metrics = [];
    
    // CPU Usage (Linux)
    if (function_exists('sys_getloadavg')) {
        $load = sys_getloadavg();
        $metrics['cpu'] = [
            'load_1min' => $load[0],
            'load_5min' => $load[1],
            'load_15min' => $load[2],
            'percentage' => min(($load[0] / 4) * 100, 100) // Assuming 4 cores
        ];
    }
    
    // Memory Usage
    if (PHP_OS_FAMILY === 'Linux') {
        $free = shell_exec('free');
        $free = (string)trim($free);
        $free_arr = explode("\n", $free);
        $mem = explode(" ", $free_arr[1]);
        $mem = array_filter($mem);
        $mem = array_merge($mem);
        $metrics['memory'] = [
            'total' => round($mem[1] / 1024, 2),
            'used' => round($mem[2] / 1024, 2),
            'free' => round($mem[3] / 1024, 2),
            'percentage' => round(($mem[2] / $mem[1]) * 100, 2)
        ];
    }
    
    // Disk Usage
    $disk_total = disk_total_space('/');
    $disk_free = disk_free_space('/');
    $disk_used = $disk_total - $disk_free;
    $metrics['disk'] = [
        'total' => round($disk_total / (1024 * 1024 * 1024), 2),
        'used' => round($disk_used / (1024 * 1024 * 1024), 2),
        'free' => round($disk_free / (1024 * 1024 * 1024), 2),
        'percentage' => round(($disk_used / $disk_total) * 100, 2)
    ];
    
    return $metrics;
}

$metrics = getCurrentServerMetrics();

// Get database stats
try {
    global $db;
    
    // Database size
    $sql = "SELECT 
                SUM(data_length + index_length) / 1024 / 1024 AS size_mb,
                COUNT(*) AS table_count
            FROM information_schema.tables 
            WHERE table_schema = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([DB_NAME]);
    $db_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Active connections
    $sql = "SHOW STATUS WHERE `variable_name` = 'Threads_connected'";
    $stmt = $db->query($sql);
    $connections = $stmt->fetch(PDO::FETCH_ASSOC);
    $active_connections = $connections['Value'] ?? 0;
    
    // Recent metrics from database
    $sql = "SELECT * FROM server_metrics 
            WHERE recorded_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
            ORDER BY recorded_at DESC";
    $stmt = $db->query($sql);
    $recent_metrics = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Critical alerts
    $sql = "SELECT * FROM system_alerts 
            WHERE is_resolved = 0 
            ORDER BY severity DESC, created_at DESC
            LIMIT 10";
    $stmt = $db->query($sql);
    $alerts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('Server stats error: ' . $e->getMessage());
    $db_stats = ['size_mb' => 0, 'table_count' => 0];
    $active_connections = 0;
    $recent_metrics = [];
    $alerts = [];
}

renderAdminHeader('Server Status', $breadcrumbs);
?>

<style>
.metric-card {
    border-left: 4px solid #059669;
    transition: all 0.3s ease;
}
.metric-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.1) !important;
}
.metric-card.warning {
    border-left-color: #f59e0b;
}
.metric-card.critical {
    border-left-color: #ef4444;
}
.progress-bar {
    transition: width 0.6s ease;
}
.status-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
    animation: pulse 2s infinite;
}
.status-indicator.ok {
    background-color: #22c55e;
}
.status-indicator.warning {
    background-color: #f59e0b;
}
.status-indicator.critical {
    background-color: #ef4444;
}
@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">
            <i class="bi bi-hdd-rack me-2"></i>Server Status
        </h2>
        <p class="text-muted mb-0">Real-time server health and performance monitoring</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" onclick="refreshMetrics()">
            <i class="bi bi-arrow-clockwise me-2"></i>Refresh
        </button>
        <button class="btn btn-outline-secondary" onclick="exportReport()">
            <i class="bi bi-download me-2"></i>Export Report
        </button>
    </div>
</div>

<!-- System Health Summary -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm metric-card <?php echo ($metrics['cpu']['percentage'] ?? 0) > 80 ? 'critical' : (($metrics['cpu']['percentage'] ?? 0) > 60 ? 'warning' : ''); ?>">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">CPU Usage</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo number_format($metrics['cpu']['percentage'] ?? 0, 1); ?>%</h3>
                    </div>
                    <div class="text-primary" style="font-size: 2rem;">
                        <i class="bi bi-cpu"></i>
                    </div>
                </div>
                <div class="progress" style="height: 6px;">
                    <div class="progress-bar <?php echo ($metrics['cpu']['percentage'] ?? 0) > 80 ? 'bg-danger' : (($metrics['cpu']['percentage'] ?? 0) > 60 ? 'bg-warning' : 'bg-success'); ?>" 
                         style="width: <?php echo $metrics['cpu']['percentage'] ?? 0; ?>%"></div>
                </div>
                <small class="text-muted mt-1 d-block">
                    Load: <?php echo number_format($metrics['cpu']['load_1min'] ?? 0, 2); ?>, 
                    <?php echo number_format($metrics['cpu']['load_5min'] ?? 0, 2); ?>, 
                    <?php echo number_format($metrics['cpu']['load_15min'] ?? 0, 2); ?>
                </small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm metric-card <?php echo ($metrics['memory']['percentage'] ?? 0) > 90 ? 'critical' : (($metrics['memory']['percentage'] ?? 0) > 75 ? 'warning' : ''); ?>">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">Memory</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo number_format($metrics['memory']['percentage'] ?? 0, 1); ?>%</h3>
                    </div>
                    <div class="text-info" style="font-size: 2rem;">
                        <i class="bi bi-memory"></i>
                    </div>
                </div>
                <div class="progress" style="height: 6px;">
                    <div class="progress-bar <?php echo ($metrics['memory']['percentage'] ?? 0) > 90 ? 'bg-danger' : (($metrics['memory']['percentage'] ?? 0) > 75 ? 'bg-warning' : 'bg-info'); ?>" 
                         style="width: <?php echo $metrics['memory']['percentage'] ?? 0; ?>%"></div>
                </div>
                <small class="text-muted mt-1 d-block">
                    <?php echo number_format($metrics['memory']['used'] ?? 0, 0); ?> MB / 
                    <?php echo number_format($metrics['memory']['total'] ?? 0, 0); ?> MB
                </small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm metric-card <?php echo ($metrics['disk']['percentage'] ?? 0) > 90 ? 'critical' : (($metrics['disk']['percentage'] ?? 0) > 80 ? 'warning' : ''); ?>">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">Disk Usage</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo number_format($metrics['disk']['percentage'] ?? 0, 1); ?>%</h3>
                    </div>
                    <div class="text-warning" style="font-size: 2rem;">
                        <i class="bi bi-hdd"></i>
                    </div>
                </div>
                <div class="progress" style="height: 6px;">
                    <div class="progress-bar <?php echo ($metrics['disk']['percentage'] ?? 0) > 90 ? 'bg-danger' : (($metrics['disk']['percentage'] ?? 0) > 80 ? 'bg-warning' : 'bg-success'); ?>" 
                         style="width: <?php echo $metrics['disk']['percentage'] ?? 0; ?>%"></div>
                </div>
                <small class="text-muted mt-1 d-block">
                    <?php echo number_format($metrics['disk']['used'] ?? 0, 1); ?> GB / 
                    <?php echo number_format($metrics['disk']['total'] ?? 0, 1); ?> GB
                </small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm metric-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">Database</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo number_format($db_stats['size_mb'] ?? 0, 1); ?> MB</h3>
                    </div>
                    <div class="text-success" style="font-size: 2rem;">
                        <i class="bi bi-database"></i>
                    </div>
                </div>
                <div class="d-flex justify-content-between align-items-center mt-3">
                    <small class="text-muted"><?php echo $db_stats['table_count'] ?? 0; ?> Tables</small>
                    <small class="text-muted"><?php echo $active_connections; ?> Connections</small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Active Alerts -->
<?php if (count($alerts) > 0): ?>
<div class="alert alert-danger border-0 shadow-sm mb-4">
    <div class="d-flex align-items-center mb-2">
        <i class="bi bi-exclamation-triangle-fill me-2 fs-4"></i>
        <h5 class="mb-0">Active System Alerts (<?php echo count($alerts); ?>)</h5>
    </div>
    <div class="list-group list-group-flush mt-3">
        <?php foreach (array_slice($alerts, 0, 5) as $alert): ?>
        <div class="list-group-item bg-transparent border-0 px-0">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <span class="badge bg-<?php echo $alert['severity'] === 'critical' ? 'danger' : ($alert['severity'] === 'warning' ? 'warning' : 'info'); ?> me-2">
                        <?php echo strtoupper($alert['severity']); ?>
                    </span>
                    <strong><?php echo htmlspecialchars($alert['title']); ?></strong>
                    <p class="mb-0 text-muted small"><?php echo htmlspecialchars($alert['message']); ?></p>
                </div>
                <small class="text-muted"><?php echo timeAgo($alert['created_at']); ?></small>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <a href="<?php echo APP_URL; ?>/admin/system-alerts.php" class="btn btn-sm btn-outline-danger mt-2">
        View All Alerts <i class="bi bi-arrow-right"></i>
    </a>
</div>
<?php endif; ?>

<!-- Detailed Metrics -->
<div class="row">
    <!-- PHP Information -->
    <div class="col-lg-6 mb-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-info-circle me-2"></i>PHP Information
                </h5>
            </div>
            <div class="card-body">
                <table class="table table-sm">
                    <tr>
                        <td class="text-muted">PHP Version</td>
                        <td class="fw-semibold"><?php echo PHP_VERSION; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Memory Limit</td>
                        <td class="fw-semibold"><?php echo ini_get('memory_limit'); ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Max Execution Time</td>
                        <td class="fw-semibold"><?php echo ini_get('max_execution_time'); ?>s</td>
                    </tr>
                    <tr>
                        <td class="text-muted">Upload Max Filesize</td>
                        <td class="fw-semibold"><?php echo ini_get('upload_max_filesize'); ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Post Max Size</td>
                        <td class="fw-semibold"><?php echo ini_get('post_max_size'); ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Extensions Loaded</td>
                        <td class="fw-semibold"><?php echo count(get_loaded_extensions()); ?></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Server Information -->
    <div class="col-lg-6 mb-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-server me-2"></i>Server Information
                </h5>
            </div>
            <div class="card-body">
                <table class="table table-sm">
                    <tr>
                        <td class="text-muted">Server Software</td>
                        <td class="fw-semibold"><?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Operating System</td>
                        <td class="fw-semibold"><?php echo PHP_OS; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Server IP</td>
                        <td class="fw-semibold"><?php echo $_SERVER['SERVER_ADDR'] ?? 'N/A'; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Document Root</td>
                        <td class="fw-semibold small"><?php echo $_SERVER['DOCUMENT_ROOT']; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Server Time</td>
                        <td class="fw-semibold"><?php echo date('Y-m-d H:i:s'); ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Server Uptime</td>
                        <td class="fw-semibold" id="serverUptime">Calculating...</td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Performance Chart -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-graph-up me-2"></i>Performance History (Last Hour)
        </h5>
    </div>
    <div class="card-body">
        <canvas id="performanceChart" height="80"></canvas>
    </div>
</div>

<script>
// Auto-refresh every 30 seconds
setInterval(refreshMetrics, 30000);

function refreshMetrics() {
    location.reload();
}

function exportReport() {
    window.location.href = APP_URL + '/admin/export-server-report.php';
}

// Calculate and display server uptime
if (typeof sys_getloadavg === 'function') {
    // Would need actual implementation for uptime
    $('#serverUptime').text('Available');
}

// Performance Chart
<?php if (count($recent_metrics) > 0): ?>
const ctx = document.getElementById('performanceChart').getContext('2d');

// Group metrics by type and time
const metricsByTime = {};
<?php foreach ($recent_metrics as $metric): ?>
    const time_<?php echo $metric['id']; ?> = '<?php echo date('H:i', strtotime($metric['recorded_at'])); ?>';
    if (!metricsByTime[time_<?php echo $metric['id']; ?>]) {
        metricsByTime[time_<?php echo $metric['id']; ?>] = {cpu: 0, memory: 0, disk: 0};
    }
    metricsByTime[time_<?php echo $metric['id']; ?>]['<?php echo $metric['metric_type']; ?>'] = <?php echo $metric['metric_value']; ?>;
<?php endforeach; ?>

const times = Object.keys(metricsByTime).sort();
const cpuData = times.map(t => metricsByTime[t].cpu);
const memData = times.map(t => metricsByTime[t].memory);
const diskData = times.map(t => metricsByTime[t].disk);

new Chart(ctx, {
    type: 'line',
    data: {
        labels: times,
        datasets: [
            {
                label: 'CPU %',
                data: cpuData,
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4
            },
            {
                label: 'Memory %',
                data: memData,
                borderColor: 'rgb(16, 185, 129)',
                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                tension: 0.4
            },
            {
                label: 'Disk %',
                data: diskData,
                borderColor: 'rgb(245, 158, 11)',
                backgroundColor: 'rgba(245, 158, 11, 0.1)',
                tension: 0.4
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            legend: {
                display: true,
                position: 'top'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                max: 100,
                ticks: {
                    callback: function(value) {
                        return value + '%';
                    }
                }
            }
        }
    }
});
<?php endif; ?>
</script>

<?php renderAdminFooter(); ?>