<?php
declare(strict_types=1);

if (!defined('APP_DEBUG') || APP_DEBUG !== true) {
    http_response_code(404);
    exit;
}

// debug files are stored in project root /debug (one level above /public)
$base = dirname(__DIR__, 2) . '/debug';
$files = [];
if (is_dir($base)) {
    foreach (scandir($base) as $f) {
        if ($f === '.' || $f === '..') continue;
        $path = $base . '/' . $f;
        if (is_file($path)) {
            $files[] = $f;
        }
    }
}

$selected = isset($_GET['file']) ? basename((string)$_GET['file']) : '';
$content = '';
if ($selected && in_array($selected, $files, true)) {
    $content = @file_get_contents($base . '/' . $selected) ?: '';
}

// Raw delivery for AJAX view (no layout, plain text)
if (isset($_GET['raw']) && $_GET['raw'] === '1') {
    if (!$selected || !in_array($selected, $files, true)) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Log nicht gefunden.';
        exit;
    }
    header('Content-Type: text/plain; charset=utf-8');
    echo $content;
    exit;
}
?>
<main class="container" style="padding: 32px 0;">
  <div class="card" style="padding: 16px;">
    <h1>Debug-Logs</h1>
    <?php if (!$files): ?>
      <p class="muted">Keine Logs in /debug/ gefunden.</p>
    <?php else: ?>
      <form method="get" style="margin-bottom: 16px;">
        <label for="logSelect" class="label">Log-Datei auswählen</label>
        <select id="logSelect" name="file" class="select" onchange="this.form.submit()">
          <option value="">-- auswählen --</option>
          <?php foreach ($files as $f): ?>
            <option value="<?= htmlspecialchars($f, ENT_QUOTES) ?>" <?= $f === $selected ? 'selected' : '' ?>><?= htmlspecialchars($f, ENT_QUOTES) ?></option>
          <?php endforeach; ?>
        </select>
      </form>
      <?php if ($selected): ?>
        <h3><?= htmlspecialchars($selected, ENT_QUOTES) ?></h3>
        <pre style="white-space:pre-wrap; background:#f8fafc; padding:12px; border:1px solid #e5e7eb; border-radius:8px; max-height: 60vh; overflow:auto;"><?= htmlspecialchars($content, ENT_QUOTES) ?></pre>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</main>
