<?php
// admin/tools/pdf_list.php

session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';
require_once __DIR__ . '/../../includes/core/ErrorLogger.php';

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

$config = include __DIR__ . '/../../includes/config.php';
$db = Database::getInstance();

$title = "📁 PDF-Downloads Übersicht";
$info = '';
$error = '';

ob_start();

try {
    $baseUrl = rtrim($config['app']['base_url'], '/');

    // Alle PDFs mit optional letztem Token laden
    $stmt = $db->query("SELECT d.id, d.title, d.created_at, t.token, t.valid_until
                        FROM pdf_downloads d
                        LEFT JOIN (
                            SELECT pt.*
                            FROM pdf_tokens pt
                            INNER JOIN (
                                SELECT pdf_id, MAX(created_at) AS max_created
                                FROM pdf_tokens
                                GROUP BY pdf_id
                            ) grouped_pt ON pt.pdf_id = grouped_pt.pdf_id AND pt.created_at = grouped_pt.max_created
                        ) t ON d.id = t.pdf_id
                        ORDER BY d.created_at DESC");
    
    $pdfs = $stmt->fetchAll();
    ErrorLogger::logSqlSuccess("PDF-Liste geladen | table: pdf_downloads/pdf_tokens | context: " . json_encode(["order" => "created_at DESC"], JSON_UNESCAPED_UNICODE));
    ErrorLogger::log("PDF-Download-Übersicht geladen", 'INFO');

} catch (Exception $e) {
    ErrorLogger::logSqlError("Fehler beim Laden der PDF-Liste | table: pdf_downloads/pdf_tokens | error: " . $e->getMessage());
    $error = 'Fehler beim Laden: ' . $e->getMessage();
    ErrorLogger::log("Fehler bei PDF-Download-Übersicht: {$e->getMessage()}", 'ERROR');
}
?>

<div class="page-header h2">📁 PDF-Downloads Übersicht</div>

<?php if ($error): ?>
  <div class="alert alert-danger auto-dismiss">❌ <?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Titel</th>
      <th>Erstellt</th>
      <th>Platzhalter</th>
      <th>Token</th>
      <th>Gültig bis</th>
      <th>Download-Link</th>
      <th>Aktionen</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($pdfs as $pdf): ?>
      <tr>
        <td><?= $pdf['id'] ?></td>
        <td><?= htmlspecialchars($pdf['title']) ?></td>
        <td><?= $pdf['created_at'] ?></td>
        <td><code>[download_pdf<?= $pdf['id'] ?>]</code></td>
        <td><?= $pdf['token'] ? htmlspecialchars($pdf['token']) : '–' ?></td>
        <td><?= $pdf['valid_until'] ? $pdf['valid_until'] : '–' ?></td>
        <td>
          <?php if ($pdf['token']): ?>
            <code><?= $baseUrl ?>/download.php?token=<?= htmlspecialchars($pdf['token']) ?>&amp;rid=EMPFAENGER_ID</code>
          <?php else: ?>
            –
          <?php endif; ?>
        </td>
        <td>
          <a href="pdf_edit.php?id=<?= $pdf['id'] ?>">✏️ Bearbeiten</a> |
          <a href="pdf_delete.php?id=<?= $pdf['id'] ?>" onclick="return confirm('Wirklich löschen?')">🗑️ Löschen</a>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<script>
// Automatisches Ausblenden von Hinweisen
  document.addEventListener('DOMContentLoaded', function () {
    setTimeout(() => {
      document.querySelectorAll('.auto-dismiss').forEach(el => {
        el.classList.add('fade');
        setTimeout(() => el.remove(), 1000);
      });
    }, 5000);
  });
</script>

<?php
$pageContent = ob_get_clean();
include __DIR__ . '/../template.php';
