<?php
// admin/log_viewer.php

// Sitzung starten und Authentifizierung prüfen
session_start();
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../auth/AuthController.php';

// Authentifizierung absichern
$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

// Datenbankverbindung holen
$db = Database::getInstance();

// Filter aus GET-Parametern verarbeiten
$levelFilter = $_GET['level'] ?? '';
$searchFilter = $_GET['search'] ?? '';

// Basis-SQL-Anweisung vorbereiten
$sql = "SELECT * FROM system_logs WHERE 1=1";
$params = [];

// Log-Level-Filter anwenden
if ($levelFilter !== '') {
    $sql .= " AND log_level = :level";
    $params[':level'] = strtoupper($levelFilter);
}

// Nachrichtensuche anwenden
if ($searchFilter !== '') {
    $sql .= " AND message LIKE :search";
    $params[':search'] = '%' . $searchFilter . '%';
}

$sql .= " ORDER BY created_at DESC LIMIT 500";

try {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    ErrorLogger::logSqlSuccess("System-Logs geladen | table: system_logs | context: " . json_encode(['level' => $levelFilter, 'search' => $searchFilter, 'limit' => 500], JSON_UNESCAPED_UNICODE));
    $logs = $stmt->fetchAll();
} catch (PDOException $e) {
    ErrorLogger::logSqlError("Fehler beim Laden der System-Logs | table: system_logs | error: " . $e->getMessage());
    ErrorLogger::log("Fehler beim Laden der System-Logs: " . $e->getMessage(), 'ERROR');
    $logs = [];
}

// Seitentitel für Template setzen (optional)
$pageTitle = 'System-Log';

// Inhaltsblock starten (für Template)
ob_start();
?>

<!-- Eigentliche Log-Ansicht -->
<div class="container mt-4">
    <h1 class="mb-4">System-Log</h1>

    <!-- Filterformular -->
    <form method="get" class="row g-3 mb-4">
        <div class="col-md-3">
            <select name="level" class="form-select">
                <option value="">Alle Level</option>
                <?php
                $levels = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'];
                foreach ($levels as $lvl) {
                    $selected = ($lvl === strtoupper($levelFilter)) ? 'selected' : '';
                    echo "<option value=\"$lvl\" $selected>$lvl</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-6">
            <input type="text" name="search" class="form-control" placeholder="Nachricht durchsuchen" value="<?= htmlspecialchars($searchFilter) ?>">
        </div>
        <div class="col-md-3">
            <button type="submit" class="btn btn-primary w-100">Filtern</button>
        </div>
    </form>

    <!-- Logausgabe -->
    <style>
        .log-DEBUG { color: gray; }
        .log-INFO  { color: blue; }
        .log-WARN  { color: orange; }
        .log-ERROR { color: red; font-weight: bold; }
        .log-FATAL { color: white; background-color: darkred; font-weight: bold; padding: 4px; }
        .log-entry { border-bottom: 1px solid #ddd; padding: 6px 0; }
    </style>

    <div class="log-list">
        <?php if (count($logs) === 0): ?>
            <div class="alert alert-info">Keine Einträge gefunden.</div>
        <?php else: ?>
            <?php foreach ($logs as $log): ?>
                <div class="log-entry log-<?= htmlspecialchars($log['log_level']) ?>">
                    <strong>[<?= $log['created_at'] ?>] <?= htmlspecialchars($log['log_level']) ?>:</strong><br>
                    <span><?= nl2br(htmlspecialchars($log['message'])) ?></span>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<?php
// Template einbinden
$pageContent = ob_get_clean();
include_once __DIR__ . '/template.php';
