<?php
// admin/tools/pdf_stats.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;
}

$db = Database::getInstance();
$title = "📊 PDF Download-Statistik";
$info = '';
$error = '';

ob_start();

try {
    // Gesamtstatistik je PDF
    $stmt = $db->query("SELECT d.id, d.title, COUNT(s.id) AS download_count FROM pdf_downloads d LEFT JOIN pdf_download_stats s ON d.id = s.pdf_id GROUP BY d.id ORDER BY download_count DESC");
    $pdfs = $stmt->fetchAll();
    ErrorLogger::logSqlSuccess("PDF-Gesamtstatistik geladen | table: pdf_downloads/pdf_download_stats | context: " . json_encode(["group_by" => "d.id"], JSON_UNESCAPED_UNICODE));

    // Letzte 20 Einzel-Downloads
    $stmt = $db->query("SELECT s.downloaded_at, s.recipient_id, s.ip_address, d.title FROM pdf_download_stats s JOIN pdf_downloads d ON s.pdf_id = d.id ORDER BY s.downloaded_at DESC LIMIT 20");
    $downloads = $stmt->fetchAll();
    ErrorLogger::logSqlSuccess("Letzte PDF-Downloads geladen | table: pdf_download_stats | context: " . json_encode(["limit" => 20], JSON_UNESCAPED_UNICODE));

    ErrorLogger::log("PDF-Download-Statistik abgerufen", 'INFO');
} catch (Exception $e) {
    ErrorLogger::logSqlError("Fehler beim Laden der PDF-Statistik | table: pdf_downloads/pdf_download_stats | error: " . $e->getMessage());
    $error = 'Fehler beim Laden der Statistik: ' . $e->getMessage();
    ErrorLogger::log("Fehler beim Abrufen der PDF-Statistik: {$e->getMessage()}", 'ERROR');
}
?>

<div class="page-header h2">📊 PDF-Download Statistik</div>

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

<h4>Gesamtübersicht</h4>
<table class="table table-striped">
  <thead>
    <tr>
      <th>PDF-ID</th>
      <th>Titel</th>
      <th>Downloads</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($pdfs as $row): ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td><?= htmlspecialchars($row['title']) ?></td>
        <td><?= $row['download_count'] ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<hr>

<h4>Letzte 20 Downloads</h4>
<table class="table table-striped">
  <thead>
    <tr>
      <th>Zeitpunkt</th>
      <th>PDF-Titel</th>
      <th>Empfänger-ID</th>
      <th>IP-Adresse</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($downloads as $log): ?>
      <tr>
        <td><?= $log['downloaded_at'] ?></td>
        <td><?= htmlspecialchars($log['title']) ?></td>
        <td><?= $log['recipient_id'] ?></td>
        <td><?= $log['ip_address'] ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<script>
// Meldungen automatisch ausblenden
  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';

