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

function_admin_login_erfordern();

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

$logDir = defined('WECKER_LOG_DIR') ? WECKER_LOG_DIR : '/var/www/wecker/logs';
$maxLines = 300;
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>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;flex-wrap:wrap
}
header h3{margin:0;flex:1}
select{
    background:#1c2130;border:1px solid var(--border);
    color:var(--text);padding:6px 10px;min-width:140px
}
button{
    background:#1c2130;border:1px solid var(--border);
    color:var(--text);padding:6px 10px;cursor:pointer
}
button:hover{border-color:var(--accent)}
button.danger:hover{border-color:var(--error);color:var(--error)}
#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>Log Viewer</h3>
    <select id="logSelect" title="Log-Datei wählen" onchange="loadLog()">
        <option value="error.log">error.log</option>
    </select>
    <button onclick="toggleLive()" id="liveBtn">Live: AUS</button>
    <button onclick="loadLog()">Reload</button>
    <button type="button" class="danger" onclick="clearLog()" title="Log-Datei leeren">Löschen</button>
</header>

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

<footer>
    Verzeichnis: <?= htmlspecialchars($logDir) ?> · max <span id="maxLines"><?= $maxLines ?></span> Zeilen
</footer>

<script>
const maxLines = <?= (int) $maxLines ?>;
let live = false;
let timer = null;

function getSelectedFile() {
    return document.getElementById('logSelect').value || 'error.log';
}

function loadLogList() {
    fetch('errorlog_api.php?list=1')
        .then(r => r.json())
        .then(data => {
            const sel = document.getElementById('logSelect');
            const current = sel.value;
            const files = (data.ok && data.files && data.files.length) ? data.files : ['error.log', 'access.log'];
            sel.innerHTML = files.map(f => '<option value="' + f + '">' + f + '</option>').join('');
            if (files.includes(current)) sel.value = current;
            else sel.value = files[0];
        })
        .catch(() => {});
}

function loadLog(){
    const file = getSelectedFile();
    fetch('errorlog_api.php?file=' + encodeURIComponent(file) + '&max=' + maxLines)
        .then(r => r.json())
        .then(data => {
            const log = document.getElementById('log');
            if (data.error) {
                log.textContent = 'Fehler: ' + data.error;
                return;
            }
            log.innerHTML = '';
            const lines = data.lines || data;
            if (Array.isArray(lines)) {
                lines.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(() => { document.getElementById('log').textContent = 'Laden fehlgeschlagen.'; });
}

function toggleLive(){
    live = !live;
    document.getElementById('liveBtn').innerText = live ? 'Live: AN' : 'Live: AUS';
    if (live) {
        loadLog();
        timer = setInterval(loadLog, 2000);
    } else {
        clearInterval(timer);
    }
}

function clearLog() {
    if (!confirm('Log-Datei wirklich leeren?')) return;
    const file = getSelectedFile();
    const fd = new FormData();
    fd.set('action', 'clear');
    fd.set('file', file);
    fetch('errorlog_api.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(data => {
            if (data.ok) loadLog();
            else alert(data.error || 'Fehler');
        })
        .catch(() => alert('Fehler'));
}

loadLogList();
loadLog();
</script>

</body>
</html>
