<?php
/**
 * System Health & Monitoring - System Admin only
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/system-ops-helpers.php';

requireAuth();
requireSystemAdmin();

$pageTitle = 'System Health';
$currentPage = 'system';

// Get system metrics
$metrics = [];

// 1. Server Information
$metrics['server'] = [
    'php_version' => PHP_VERSION,
    'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
    'server_name' => $_SERVER['SERVER_NAME'] ?? 'Unknown',
    'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown',
    'max_execution_time' => ini_get('max_execution_time'),
    'memory_limit' => ini_get('memory_limit'),
    'upload_max_filesize' => ini_get('upload_max_filesize'),
    'post_max_size' => ini_get('post_max_size'),
];

// 2. Memory Usage
$metrics['memory'] = [
    'used' => memory_get_usage(true),
    'peak' => memory_get_peak_usage(true),
    'limit' => ini_get('memory_limit'),
];

// Convert memory limit to bytes
function parseSize($size) {
    $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
    $size = preg_replace('/[^0-9\.]/', '', $size);
    if ($unit) {
        return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
    }
    return round($size);
}

$memoryLimitBytes = parseSize($metrics['memory']['limit']);
$metrics['memory']['percent'] = $memoryLimitBytes > 0 ? round(($metrics['memory']['used'] / $memoryLimitBytes) * 100, 1) : 0;

// 3. Disk Space
$diskFree = disk_free_space(__DIR__ . '/../../');
$diskTotal = disk_total_space(__DIR__ . '/../../');
$diskUsed = $diskTotal - $diskFree;
$diskPercent = $diskTotal > 0 ? round(($diskUsed / $diskTotal) * 100, 1) : 0;

$metrics['disk'] = [
    'free' => $diskFree,
    'total' => $diskTotal,
    'used' => $diskUsed,
    'percent' => $diskPercent,
];

// 4. MySQL Status
$mysqlStatus = [];
try {
    // Version
    $stmt = $pdo->query('SELECT VERSION() as version');
    $mysqlStatus['version'] = $stmt->fetchColumn();
    
    // Status variables
    $statusVars = [
        'Connections' => 'Connections',
        'Max_used_connections' => 'Max Used Connections',
        'Threads_connected' => 'Threads Connected',
        'Threads_running' => 'Threads Running',
        'Uptime' => 'Uptime',
        'Questions' => 'Total Queries',
        'Slow_queries' => 'Slow Queries',
        'Open_tables' => 'Open Tables',
        'Table_locks_waited' => 'Table Locks Waited',
    ];
    
    $stmt = $pdo->query('SHOW STATUS');
    $status = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $status[$row['Variable_name']] = $row['Value'];
    }
    
    foreach ($statusVars as $key => $label) {
        $mysqlStatus[strtolower($key)] = [
            'label' => $label,
            'value' => $status[$key] ?? 0,
        ];
    }
    
    // Calculate query per second (approximate)
    $uptime = (int)($status['Uptime'] ?? 1);
    $questions = (int)($status['Questions'] ?? 0);
    $mysqlStatus['queries_per_second'] = $uptime > 0 ? round($questions / $uptime, 2) : 0;
    
    // Connection usage percentage
    $maxConnections = (int)($status['Max_connections'] ?? 151);
    $threadsConnected = (int)($status['Threads_connected'] ?? 0);
    $mysqlStatus['connection_usage_percent'] = $maxConnections > 0 ? round(($threadsConnected / $maxConnections) * 100, 1) : 0;
    $mysqlStatus['max_connections'] = $maxConnections;
    
} catch (PDOException $e) {
    $mysqlStatus['error'] = $e->getMessage();
}

// 5. Active Sessions
$activeSessions = [];
try {
    $sessionDir = session_save_path() ?: sys_get_temp_dir();
    if (is_dir($sessionDir)) {
        $files = glob($sessionDir . '/sess_*');
        $activeSessions['count'] = count($files);
        $activeSessions['dir'] = $sessionDir;
        
        // Get session details (limited to last 10)
        $sessions = [];
        foreach (array_slice($files, -10) as $file) {
            $sessions[] = [
                'file' => basename($file),
                'modified' => filemtime($file),
                'size' => filesize($file),
            ];
        }
        usort($sessions, function($a, $b) {
            return $b['modified'] - $a['modified'];
        });
        $activeSessions['recent'] = array_slice($sessions, 0, 10);
    }
} catch (Exception $e) {
    $activeSessions['error'] = $e->getMessage();
}

// 6. PHP Error Log Location
$errorLog = ini_get('error_log');
if (!$errorLog || $errorLog === 'syslog') {
    $errorLog = 'syslog (system log)';
}

// 7. Load Average (Unix/Linux)
$loadAverage = null;
if (function_exists('sys_getloadavg')) {
    $load = sys_getloadavg();
    if ($load !== false) {
        $loadAverage = [
            '1min' => round($load[0], 2),
            '5min' => round($load[1], 2),
            '15min' => round($load[2], 2),
        ];
    }
}

// 8. PHP Extensions
$requiredExtensions = ['pdo', 'pdo_mysql', 'mbstring', 'json', 'curl', 'openssl'];
$extensions = [];
foreach ($requiredExtensions as $ext) {
    $extensions[$ext] = extension_loaded($ext);
}

$projectRoot = realpath(__DIR__ . '/../..') ?: (__DIR__ . '/../..');
$uploadsSummary = nazareth_uploads_storage_summary($projectRoot);
$backupFresh = nazareth_backup_freshness_summary(__DIR__ . '/../../backups');
$httpsOn = nazareth_request_uses_https();
$sessionCookieParams = function_exists('session_get_cookie_params') ? session_get_cookie_params() : [];

require_once __DIR__ . '/../../includes/system-header.php';
?>

<div class="header">
    <h1>System Health & Monitoring</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/system" class="link-muted">← Dashboard</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<!-- System Status Overview -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
    <div class="card" style="background: <?= $diskPercent > 80 ? '#fef2f2' : ($diskPercent > 60 ? '#fef3c7' : '#f0fdf4') ?>; border: 1px solid <?= $diskPercent > 80 ? '#fecaca' : ($diskPercent > 60 ? '#fde68a' : '#86efac') ?>;">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem;">
            <div style="font-size: 0.875rem; color: #64748b; font-weight: 500;">Disk Usage</div>
            <?php if ($diskPercent > 80): ?>
            <span style="color: #ef4444; font-size: 0.75rem;">⚠️ Critical</span>
            <?php elseif ($diskPercent > 60): ?>
            <span style="color: #f59e0b; font-size: 0.75rem;">⚠️ Warning</span>
            <?php else: ?>
            <span style="color: #10b981; font-size: 0.75rem;">✓ OK</span>
            <?php endif; ?>
        </div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b; margin-bottom: 0.5rem;"><?= $diskPercent ?>%</div>
        <div style="height: 6px; background: #e2e8f0; border-radius: 3px; overflow: hidden;">
            <div style="height: 100%; width: <?= $diskPercent ?>%; background: <?= $diskPercent > 80 ? '#ef4444' : ($diskPercent > 60 ? '#f59e0b' : '#10b981') ?>;"></div>
        </div>
        <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.5rem;">
            <?= number_format($diskUsed / 1024 / 1024 / 1024, 2) ?> GB / <?= number_format($diskTotal / 1024 / 1024 / 1024, 2) ?> GB
        </div>
    </div>

    <div class="card" style="background: <?= $metrics['memory']['percent'] > 80 ? '#fef2f2' : ($metrics['memory']['percent'] > 60 ? '#fef3c7' : '#f0fdf4') ?>; border: 1px solid <?= $metrics['memory']['percent'] > 80 ? '#fecaca' : ($metrics['memory']['percent'] > 60 ? '#fde68a' : '#86efac') ?>;">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem;">
            <div style="font-size: 0.875rem; color: #64748b; font-weight: 500;">Memory Usage</div>
            <?php if ($metrics['memory']['percent'] > 80): ?>
            <span style="color: #ef4444; font-size: 0.75rem;">⚠️ High</span>
            <?php elseif ($metrics['memory']['percent'] > 60): ?>
            <span style="color: #f59e0b; font-size: 0.75rem;">⚠️ Moderate</span>
            <?php else: ?>
            <span style="color: #10b981; font-size: 0.75rem;">✓ OK</span>
            <?php endif; ?>
        </div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b; margin-bottom: 0.5rem;"><?= $metrics['memory']['percent'] ?>%</div>
        <div style="height: 6px; background: #e2e8f0; border-radius: 3px; overflow: hidden;">
            <div style="height: 100%; width: <?= $metrics['memory']['percent'] ?>%; background: <?= $metrics['memory']['percent'] > 80 ? '#ef4444' : ($metrics['memory']['percent'] > 60 ? '#f59e0b' : '#10b981') ?>;"></div>
        </div>
        <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.5rem;">
            <?= number_format($metrics['memory']['used'] / 1024 / 1024, 2) ?> MB / <?= $metrics['memory']['limit'] ?>
        </div>
    </div>

    <?php if (isset($mysqlStatus['connection_usage_percent'])): ?>
    <div class="card" style="background: <?= $mysqlStatus['connection_usage_percent'] > 80 ? '#fef2f2' : ($mysqlStatus['connection_usage_percent'] > 60 ? '#fef3c7' : '#f0fdf4') ?>; border: 1px solid <?= $mysqlStatus['connection_usage_percent'] > 80 ? '#fecaca' : ($mysqlStatus['connection_usage_percent'] > 60 ? '#fde68a' : '#86efac') ?>;">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem;">
            <div style="font-size: 0.875rem; color: #64748b; font-weight: 500;">MySQL Connections</div>
            <?php if ($mysqlStatus['connection_usage_percent'] > 80): ?>
            <span style="color: #ef4444; font-size: 0.75rem;">⚠️ High</span>
            <?php elseif ($mysqlStatus['connection_usage_percent'] > 60): ?>
            <span style="color: #f59e0b; font-size: 0.75rem;">⚠️ Moderate</span>
            <?php else: ?>
            <span style="color: #10b981; font-size: 0.75rem;">✓ OK</span>
            <?php endif; ?>
        </div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b; margin-bottom: 0.5rem;"><?= $mysqlStatus['connection_usage_percent'] ?>%</div>
        <div style="height: 6px; background: #e2e8f0; border-radius: 3px; overflow: hidden;">
            <div style="height: 100%; width: <?= $mysqlStatus['connection_usage_percent'] ?>%; background: <?= $mysqlStatus['connection_usage_percent'] > 80 ? '#ef4444' : ($mysqlStatus['connection_usage_percent'] > 60 ? '#f59e0b' : '#10b981') ?>;"></div>
        </div>
        <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.5rem;">
            <?= $mysqlStatus['threads_connected']['value'] ?? 0 ?> / <?= $mysqlStatus['max_connections'] ?? '?' ?> connections
        </div>
    </div>
    <?php endif; ?>

    <?php if ($loadAverage): ?>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; font-weight: 500; margin-bottom: 0.5rem;">System Load</div>
        <div style="font-size: 1.25rem; font-weight: 600; color: #1e293b;">
            <?= $loadAverage['1min'] ?> / <?= $loadAverage['5min'] ?> / <?= $loadAverage['15min'] ?>
        </div>
        <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.25rem;">1min / 5min / 15min</div>
    </div>
    <?php endif; ?>

    <div class="card" style="background: #fffbeb; border: 1px solid #fde68a;">
        <div style="font-size: 0.875rem; color: #92400e; font-weight: 500; margin-bottom: 0.5rem;">Upload storage</div>
        <div style="font-size: 1.5rem; font-weight: 600; color: #1e293b;"><?= number_format($uploadsSummary['total_bytes'] / 1024 / 1024, 2) ?> MB</div>
        <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.35rem;">Member photos under <code>public/uploads/</code></div>
    </div>

    <?php
    $bf = $backupFresh;
    $bfCardBg = '#f0fdf4';
    $bfCardBorder = '#86efac';
    $bfTitle = 'Backups';
    if ($bf['level'] === 'critical') {
        $bfCardBg = '#fff1f2';
        $bfCardBorder = '#fecdd3';
        $bfTitle = 'Backups — stale';
    } elseif ($bf['level'] === 'warn') {
        $bfCardBg = '#fff7ed';
        $bfCardBorder = '#fed7aa';
        $bfTitle = 'Backups — review';
    } elseif ($bf['level'] === 'none') {
        $bfCardBg = '#f8fafc';
        $bfCardBorder = '#e2e8f0';
        $bfTitle = 'Backups — none';
    }
    ?>
    <div class="card" style="background: <?= $bfCardBg ?>; border: 1px solid <?= $bfCardBorder ?>;">
        <div style="font-size: 0.875rem; color: #64748b; font-weight: 500; margin-bottom: 0.5rem;"><?= htmlspecialchars($bfTitle) ?></div>
        <?php if ($bf['latest_mtime'] && $bf['latest_name']): ?>
        <div style="font-size: 1.1rem; font-weight: 600; color: #1e293b;"><?= htmlspecialchars($bf['latest_name']) ?></div>
        <div style="font-size: 0.8125rem; color: #64748b; margin-top: 0.35rem;">
            <?= date('Y-m-d H:i:s', $bf['latest_mtime']) ?>
            (<?= $bf['age_seconds'] !== null ? (int) floor($bf['age_seconds'] / 86400) : '—' ?> days ago)
        </div>
        <div style="font-size: 0.75rem; margin-top: 0.5rem;">
            <?php if ($bf['level'] === 'ok'): ?><span style="color: #15803d;">Latest .sql under 7 days old.</span>
            <?php elseif ($bf['level'] === 'warn'): ?><span style="color: #c2410c;">Latest backup is over 7 days old.</span>
            <?php else: ?><span style="color: #b91c1c;">Latest backup is over 30 days old.</span>
            <?php endif; ?>
            <a href="<?= BASE_PATH ?>/system/backup" style="margin-left: 0.35rem;">Open backup tool →</a>
        </div>
        <?php else: ?>
        <p style="margin: 0; color: #64748b; font-size: 0.875rem;">No <code>*.sql</code> files in <code>backups/</code>. Create one from the backup page.</p>
        <p style="margin: 0.5rem 0 0;"><a href="<?= BASE_PATH ?>/system/backup">Backup &amp; restore →</a></p>
        <?php endif; ?>
    </div>
</div>

<!-- Server Information -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Server Information</h2>
    <div class="table-wrap">
        <table>
            <tbody>
                <tr>
                    <td style="width: 40%; color: #64748b;">PHP Version</td>
                    <td style="font-weight: 500;"><?= htmlspecialchars($metrics['server']['php_version']) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Server Software</td>
                    <td><?= htmlspecialchars($metrics['server']['server_software']) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Server Name</td>
                    <td><?= htmlspecialchars($metrics['server']['server_name']) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Document Root</td>
                    <td style="font-size: 0.875rem; font-family: monospace;"><?= htmlspecialchars($metrics['server']['document_root']) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Max Execution Time</td>
                    <td><?= htmlspecialchars($metrics['server']['max_execution_time']) ?> seconds</td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Memory Limit</td>
                    <td><?= htmlspecialchars($metrics['server']['memory_limit']) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Upload Max Filesize</td>
                    <td><?= htmlspecialchars($metrics['server']['upload_max_filesize']) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Post Max Size</td>
                    <td><?= htmlspecialchars($metrics['server']['post_max_size']) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">PHP Error Log</td>
                    <td style="font-size: 0.875rem; font-family: monospace;"><?= htmlspecialchars($errorLog) ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- Application storage & backups (detail) -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Application storage &amp; backups</h2>
    <div class="table-wrap">
        <table>
            <tbody>
                <tr>
                    <td style="width: 40%; color: #64748b;">Uploads (total)</td>
                    <td style="font-weight: 500;"><?= number_format($uploadsSummary['total_bytes'] / 1024 / 1024, 2) ?> MB</td>
                </tr>
                <tr>
                    <td style="color: #64748b;">… member photos</td>
                    <td><?= number_format($uploadsSummary['members_bytes'] / 1024 / 1024, 2) ?> MB <span style="color: #94a3b8; font-size: 0.8125rem;">(<?= htmlspecialchars($uploadsSummary['members_path']) ?>)</span></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">SQL backups on disk</td>
                    <td><?= (int) $backupFresh['file_count'] ?> file(s)</td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Freshness rule</td>
                    <td style="font-size: 0.875rem;">Warning if newest <code>backups/*.sql</code> is older than <strong>7 days</strong>; critical styling after <strong>30 days</strong>.</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- HTTPS & sessions -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">HTTPS &amp; login sessions</h2>
    <p class="text-muted" style="margin-bottom: 1rem; font-size: 0.9375rem;">
        The app sets the session cookie with <strong>HttpOnly</strong>, <strong>SameSite=Lax</strong>, and <strong>Secure</strong> when this request is over HTTPS
        (see <code>includes/session-bootstrap.php</code>). Use HTTPS in production so cookies are not sent in clear text.
        Session lifetime is <strong>0</strong> (browser session): closing the browser or PWA often requires signing in again; behaviour varies by device.
    </p>
    <div class="table-wrap">
        <table>
            <tbody>
                <tr>
                    <td style="width: 40%; color: #64748b;">This page load</td>
                    <td><?= $httpsOn ? '<span style="color: #15803d;">HTTPS (or forwarded proto)</span>' : '<span style="color: #b45309;">Not detected as HTTPS</span> — fine for local dev; use TLS in production.' ?></td>
                </tr>
                <?php if (!empty($sessionCookieParams)): ?>
                <tr>
                    <td style="color: #64748b;">Cookie path</td>
                    <td style="font-family: monospace; font-size: 0.875rem;"><?= htmlspecialchars((string) ($sessionCookieParams['path'] ?? '')) ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Cookie lifetime (seconds)</td>
                    <td><?= htmlspecialchars((string) ($sessionCookieParams['lifetime'] ?? '')) ?> <span style="color: #94a3b8;">(0 = until browser session ends)</span></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">Secure flag</td>
                    <td><?= !empty($sessionCookieParams['secure']) ? 'Yes' : 'No' ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">HttpOnly</td>
                    <td><?= !empty($sessionCookieParams['httponly']) ? 'Yes' : 'No' ?></td>
                </tr>
                <tr>
                    <td style="color: #64748b;">SameSite</td>
                    <td><?= htmlspecialchars((string) ($sessionCookieParams['samesite'] ?? '—')) ?></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- MySQL Status -->
<?php if (!isset($mysqlStatus['error'])): ?>
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">MySQL Status</h2>
    <div class="table-wrap">
        <table>
            <tbody>
                <tr>
                    <td style="width: 40%; color: #64748b;">Version</td>
                    <td style="font-weight: 500;"><?= htmlspecialchars($mysqlStatus['version']) ?></td>
                </tr>
                <?php foreach ($mysqlStatus as $key => $value): ?>
                    <?php if (is_array($value) && isset($value['label'])): ?>
                    <tr>
                        <td style="color: #64748b;"><?= htmlspecialchars($value['label']) ?></td>
                        <td><?= number_format($value['value']) ?></td>
                    </tr>
                    <?php endif; ?>
                <?php endforeach; ?>
                <?php if (isset($mysqlStatus['queries_per_second'])): ?>
                <tr>
                    <td style="color: #64748b;">Queries Per Second</td>
                    <td><?= number_format($mysqlStatus['queries_per_second'], 2) ?></td>
                </tr>
                <?php endif; ?>
                <?php if (isset($mysqlStatus['slow_queries']['value']) && $mysqlStatus['slow_queries']['value'] > 0): ?>
                <tr style="background: #fef2f2;">
                    <td style="color: #991b1b; font-weight: 500;">⚠️ Slow Queries</td>
                    <td style="color: #991b1b; font-weight: 500;"><?= number_format($mysqlStatus['slow_queries']['value']) ?></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- PHP Extensions -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">PHP Extensions</h2>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Extension</th>
                    <th style="text-align: center;">Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($extensions as $ext => $loaded): ?>
                <tr>
                    <td><?= htmlspecialchars($ext) ?></td>
                    <td style="text-align: center;">
                        <?php if ($loaded): ?>
                        <span style="color: #10b981; font-weight: 500;">✓ Loaded</span>
                        <?php else: ?>
                        <span style="color: #ef4444; font-weight: 500;">✗ Missing</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Active Sessions -->
<?php if (isset($activeSessions['count'])): ?>
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Active Sessions</h2>
    <p class="text-muted" style="margin-bottom: 1rem;">
        Total active sessions: <strong><?= $activeSessions['count'] ?></strong>
        <?php if (isset($activeSessions['dir'])): ?>
        <br><span style="font-size: 0.875rem; font-family: monospace; color: #64748b;"><?= htmlspecialchars($activeSessions['dir']) ?></span>
        <?php endif; ?>
    </p>
    <?php if (!empty($activeSessions['recent'])): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Session ID</th>
                    <th style="text-align: right;">Size</th>
                    <th>Last Activity</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($activeSessions['recent'] as $session): ?>
                <tr>
                    <td style="font-family: monospace; font-size: 0.875rem;"><?= htmlspecialchars($session['file']) ?></td>
                    <td style="text-align: right; color: #64748b;"><?= number_format($session['size']) ?> bytes</td>
                    <td style="color: #64748b;"><?= date('Y-m-d H:i:s', $session['modified']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- PHP Error Log Viewer -->
<?php
$errorLogPath = ini_get('error_log');
$errorLogContent = '';
$errorLogLines = 0;

if ($errorLogPath && $errorLogPath !== 'syslog' && file_exists($errorLogPath) && is_readable($errorLogPath)) {
    $lines = file($errorLogPath);
    if ($lines) {
        $errorLogLines = count($lines);
        // Get last 100 lines
        $errorLogContent = implode('', array_slice($lines, -100));
    }
}
?>

<?php if ($errorLogContent): ?>
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">PHP Error Log (Last 100 lines)</h2>
    <p class="text-muted" style="margin-bottom: 1rem;">
        Log file: <code style="font-size: 0.875rem;"><?= htmlspecialchars($errorLogPath) ?></code>
        <br>Total lines: <?= number_format($errorLogLines) ?>
    </p>
    <pre style="background: #1e293b; color: #e2e8f0; padding: 1.5rem; border-radius: 6px; overflow-x: auto; font-size: 0.8125rem; line-height: 1.6; max-height: 400px; overflow-y: auto; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;"><?= htmlspecialchars($errorLogContent) ?></pre>
</div>
<?php elseif ($errorLogPath && $errorLogPath !== 'syslog'): ?>
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">PHP Error Log</h2>
    <p class="text-muted">Error log file not found or not readable: <code><?= htmlspecialchars($errorLogPath) ?></code></p>
</div>
<?php endif; ?>

<script>
// Auto-refresh every 30 seconds
setTimeout(function() {
    window.location.reload();
}, 30000);
</script>

<?php require_once __DIR__ . '/../../includes/system-footer.php'; ?>
