<?php
$pageTitle = 'System Health & Logs';
include_once 'includes/header.php';

// --- Admin Check ---
if (!in_array($_SESSION['admin_user_role'] ?? '', ['super_admin', 'admin'])) {
    header('Location: dashboard.php');
    exit();
}

// Attempt to find the error log
$logFile = ini_get('error_log');
if (!$logFile || !file_exists($logFile)) {
    // Common XAMPP fallback
    $fallback = 'C:\xampp\php\logs\php_error_log';
    if (file_exists($fallback)) {
        $logFile = $fallback;
    }
}

$logContents = '';
$maxLines = 100;

// Handle Clear Log Action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clear_log'])) {
    if ($logFile && file_exists($logFile) && is_writable($logFile)) {
        file_put_contents($logFile, ''); // Empty the file
        $_SESSION['flash_message'] = "Error log cleared successfully.";
        header("Location: system_health.php");
        exit();
    } else {
        $_SESSION['flash_error'] = "Cannot clear log. File not found or not writable.";
    }
}

// Read Log File
if ($logFile && file_exists($logFile)) {
    $fp = fopen($logFile, "r");
    if ($fp) {
        $lines = [];
        // If file is large (>2MB), jump to near the end to avoid memory issues
        $fsize = filesize($logFile);
        if ($fsize > 2 * 1024 * 1024) {
            fseek($fp, -2 * 1024 * 1024, SEEK_END);
            fgets($fp); // Discard partial line
        }
        
        while (!feof($fp)) {
            $line = fgets($fp);
            if ($line !== false) {
                $lines[] = $line;
            }
        }
        fclose($fp);
        
        // Get last N lines and reverse them (newest first)
        $lines = array_slice($lines, -$maxLines);
        $lines = array_reverse($lines);
        $logContents = implode("", $lines);
    }
} else {
    $logContents = "Log file not found or not readable.\nConfigured path: " . ini_get('error_log');
}

include_once 'includes/sidebar.php';
?>

<h1>System Health</h1>

<?php if (isset($_SESSION['flash_message'])): ?>
    <div class="message success"><?php echo $_SESSION['flash_message']; unset($_SESSION['flash_message']); ?></div>
<?php endif; ?>
<?php if (isset($_SESSION['flash_error'])): ?>
    <div class="message error"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></div>
<?php endif; ?>

<div class="dashboard-section">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
        <div>
            <h2 class="dashboard-title" style="margin: 0;">PHP Error Log</h2>
            <small style="color: #666;">Path: <?php echo htmlspecialchars($logFile); ?></small>
        </div>
        <form method="POST" onsubmit="return confirm('Are you sure you want to clear the error log?');">
            <button type="submit" name="clear_log" class="btn-sm btn-danger">Clear Log</button>
        </form>
    </div>

    <div class="log-viewer" style="background: #1e1e1e; color: #f1f1f1; padding: 15px; border-radius: 5px; height: 500px; overflow-y: auto; font-family: 'Consolas', monospace; font-size: 0.85rem; white-space: pre-wrap; border: 1px solid #333;">
        <?php echo empty(trim($logContents)) ? '<span style="color: #777;">[Log is empty]</span>' : htmlspecialchars($logContents); ?>
    </div>
</div>

<?php include_once 'includes/footer.php'; ?>