<?php
require __DIR__ . '/../config.php';
require __DIR__ . '/auth.php';

requireLogin();

//require __DIR__ . '/../config.php';

/* Zugriff absichern */
if (!defined('LogDEBUG') || LogDEBUG !== true) {
    http_response_code(403);
    exit('Access denied');
}

$logFile = defined('DEBUG_ERROR_LOG_PATH') ? DEBUG_ERROR_LOG_PATH : '/var/log/apache2/error.log';
$maxLines = 300;

/* AJAX: Log löschen */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clear']) && $_POST['clear'] === '1') {
    header('Content-Type: application/json');
    if (!file_exists($logFile)) {
        echo json_encode(['error' => 'Logfile nicht gefunden']);
        exit;
    }
    if (!is_writable($logFile)) {
        echo json_encode(['error' => 'Logfile nicht beschreibbar (Rechte)']);
        exit;
    }
    if (file_put_contents($logFile, '') === false) {
        echo json_encode(['error' => 'Löschen fehlgeschlagen']);
        exit;
    }
    echo json_encode(['ok' => true]);
    exit;
}

/* AJAX: Log-Daten liefern */
if (isset($_GET['ajax'])) {
    if (!file_exists($logFile)) {
        echo json_encode(['error' => 'Logfile nicht gefunden: ' . $logFile]);
        exit;
    }
    if (!is_readable($logFile)) {
        echo json_encode(['error' => 'Logfile nicht lesbar (Rechte): ' . $logFile]);
        exit;
    }

    $raw = @file($logFile, FILE_IGNORE_NEW_LINES);
    if ($raw === false) {
        echo json_encode(['error' => 'Logfile konnte nicht gelesen werden.']);
        exit;
    }
    $lines = array_slice($raw, -$maxLines);
    echo json_encode($lines);
    exit;
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>Error Log Viewer</title>

<style>
:root{
    --bg:#0f1115;--panel:#151922;--border:#2a2f3a;
    --text:#e6e6e6;--accent:#4da3ff;
    --error:#ff6b6b;--warn:#feca57;--info:#48dbfb;
}
*{box-sizing:border-box}
body{
    margin:0;font-family:monospace;
    background:var(--bg);color:var(--text);
    display:flex;flex-direction:column;height:100vh
}
header{
    padding:10px 14px;
    background:var(--panel);
    border-bottom:1px solid var(--border);
    display:flex;align-items:center;gap:10px
}
header h3{margin:0;flex:1}
button{
    background:#1c2130;border:1px solid var(--border);
    color:var(--text);padding:6px 10px;cursor:pointer
}
button:hover{border-color:var(--accent)}
button.danger{border-color:var(--error);color:var(--error)}
button.danger:hover{background:rgba(255,107,107,.15)}
#log{
    flex:1;
    padding:12px;
    overflow:auto;
    white-space:pre-wrap;
}
.line-error{color:var(--error)}
.line-warn{color:var(--warn)}
.line-info{color:var(--info)}
footer{
    padding:6px 12px;
    font-size:12px;
    opacity:.6;
    border-top:1px solid var(--border)
}
</style>
</head>

<body>

<header>
    <h3>Apache Error Log</h3>
    <button onclick="toggleLive()" id="liveBtn">Live: AUS</button>
    <button onclick="loadLog()">Reload</button>
    <button onclick="clearLog()" id="clearBtn" class="danger">Log löschen</button>
</header>

<div id="log">Lade Log…</div>

<footer>
    Datei: <?= htmlspecialchars($logFile) ?> · max <?= $maxLines ?> Zeilen
</footer>

<script>
let live = false;
let timer = null;

function toggleLive(){
    live = !live;
    document.getElementById('liveBtn').innerText = live ? 'Live: AN' : 'Live: AUS';

    if (live) {
        loadLog();
        timer = setInterval(loadLog, 2000);
    } else {
        clearInterval(timer);
    }
}

function loadLog(){
    fetch('errorlog.php?ajax=1')
        .then(r => r.json())
        .then(data => {
            const log = document.getElementById('log');
            log.innerHTML = '';

            if (data && data.error) {
                log.textContent = data.error;
                log.className = 'line-error';
                return;
            }
            if (!Array.isArray(data)) {
                log.textContent = 'Ungültige Antwort vom Server.';
                return;
            }

            data.forEach(l => {
                const div = document.createElement('div');
                div.textContent = l;

                const low = l.toLowerCase();
                if (low.includes('error')) div.className = 'line-error';
                else if (low.includes('warn')) div.className = 'line-warn';
                else if (low.includes('notice') || low.includes('info')) div.className = 'line-info';

                log.appendChild(div);
            });

            log.scrollTop = log.scrollHeight;
        })
        .catch(err => {
            document.getElementById('log').textContent = 'Fehler beim Laden: ' + err.message;
        });
}

function clearLog(){
    if (!confirm('Error-Log wirklich leeren? Dies kann nicht rückgängig gemacht werden.')) return;
    const btn = document.getElementById('clearBtn');
    btn.disabled = true;
    const form = new FormData();
    form.append('clear', '1');
    fetch('errorlog.php', { method: 'POST', body: form })
        .then(r => r.json())
        .then(data => {
            if (data && data.error) {
                document.getElementById('log').textContent = 'Fehler: ' + data.error;
                document.getElementById('log').className = 'line-error';
            } else if (data && data.ok) {
                document.getElementById('log').textContent = '(Log geleert)';
                loadLog();
            }
        })
        .catch(err => {
            document.getElementById('log').textContent = 'Fehler beim Löschen: ' + err.message;
        })
        .finally(() => { btn.disabled = false; });
}

/* Initial */
loadLog();
</script>

</body>
</html>
