<?php
require_once 'includes/init.php';
require_once 'includes/core/DownloadTracker.php';

$db = Database::getInstance();

$token = $_GET['token'] ?? '';
$rid = (int)($_GET['rid'] ?? 0);

$sqlPdf = "
  SELECT pt.pdf_id, pd.filename, pd.title
  FROM pdf_tokens pt
  JOIN pdf_downloads pd ON pt.pdf_id = pd.id
  WHERE pt.token = ? AND pt.valid_until > NOW()
";

function detectDownloadMimeType(string $filename): string
{
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    return match ($ext) {
        'pdf' => 'application/pdf',
        'zip' => 'application/zip',
        default => 'application/octet-stream',
    };
}

try {
    $stmt = $db->prepare($sqlPdf);
    $stmt->execute([$token]);
    $pdf = $stmt->fetch();

    ErrorLogger::logSqlSuccess('download: load token | SQL: ' . $sqlPdf . ' | params: ' . json_encode([$token], JSON_UNESCAPED_UNICODE));

    if ($pdf) {
        DownloadTracker::log($pdf['pdf_id'], $rid, $_SERVER['REMOTE_ADDR']);

        $filepath = __DIR__ . '/uploads/protected_pdfs/' . $pdf['filename'];
        if (file_exists($filepath)) {
            header('Content-Type: ' . detectDownloadMimeType($pdf['filename']));
            header('Content-Disposition: attachment; filename="' . basename($pdf['filename']) . '"');
            header('Content-Length: ' . filesize($filepath));
            readfile($filepath);
            exit;
        }
    }

    http_response_code(403);
    echo 'Download-Link ungueltig oder abgelaufen.';
} catch (Throwable $e) {
    ErrorLogger::logSqlError('download: workflow failed | SQL: ' . $sqlPdf . ' | params: ' . json_encode([$token, $rid], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    http_response_code(500);
    echo 'Interner Fehler. Bitte versuchen Sie es spaeter erneut.';
}