<?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;
}

$logDir = defined('WECKER_LOG_DIR') ? WECKER_LOG_DIR : '/var/www/wecker/logs';
$maxLines = (int) ($_GET['max'] ?? $_POST['max'] ?? 300);
$maxLines = max(10, min(2000, $maxLines));

/**
 * Nur Dateinamen aus dem Log-Verzeichnis (kein Path-Traversal).
 */
function get_log_path(string $logDir, string $name): ?string {
    $name = basename($name);
    if ($name === '' || preg_match('/[^a-zA-Z0-9_.-]/', $name)) {
        return null;
    }
    $path = $logDir . '/' . $name;
    $real = realpath($path);
    $dirReal = realpath($logDir);
    if ($real === false || $dirReal === false || strpos($real, $dirReal) !== 0) {
        return null;
    }
    return $path;
}

/**
 * Liste der Log-Dateien im Verzeichnis (.log oder typische Namen).
 */
function list_log_files(string $logDir): array {
    if (!is_dir($logDir)) {
        return [];
    }
    $files = [];
    foreach (scandir($logDir) as $f) {
        if ($f === '.' || $f === '..') continue;
        $path = $logDir . '/' . $f;
        if (is_file($path) && (substr($f, -4) === '.log' || preg_match('/^[a-z_]+\.log$/i', $f))) {
            $files[] = $f;
        }
    }
    sort($files);
    return $files;
}

/* API: Liste der verfügbaren Logs */
if (isset($_GET['list'])) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => true, 'files' => list_log_files($logDir)]);
    exit;
}

/* Datei aus Request (GET oder POST) */
$fileName = $_GET['file'] ?? $_POST['file'] ?? 'error.log';
$logFile = get_log_path($logDir, $fileName);
if ($logFile === null) {
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(400);
    echo json_encode(['error' => 'Ungültige Log-Datei']);
    exit;
}

/* POST: Log leeren */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'clear') {
    header('Content-Type: application/json; charset=utf-8');
    if (!is_writable($logFile)) {
        echo json_encode(['ok' => false, 'error' => 'Datei nicht beschreibbar']);
        exit;
    }
    if (file_put_contents($logFile, '') === false) {
        echo json_encode(['ok' => false, 'error' => 'Löschen fehlgeschlagen']);
        exit;
    }
    echo json_encode(['ok' => true]);
    exit;
}

/* GET: Log-Zeilen liefern */
if (!is_readable($logFile)) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'Logfile nicht lesbar']);
    exit;
}

$lines = array_slice(
    file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
    -$maxLines
);

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => true, 'lines' => $lines, 'file' => basename($logFile)]);
