prepare("SELECT m.*, i.invoice_number FROM mahnungen m JOIN invoices i ON i.id = m.invoice_id WHERE m.id = :id"); $stmt->execute([':id' => $id]); $row = $stmt->fetch(PDO::FETCH_ASSOC); if (!$row) { header('Location: ' . url_for('invoices.php')); exit; } // PDF vorhanden? if (empty($row['pdf_path'])) { archive_mahnung_pdf($id); // Neu laden $stmt->execute([':id' => $id]); $row = $stmt->fetch(PDO::FETCH_ASSOC); } $fullPath = __DIR__ . '/' . ($row['pdf_path'] ?? ''); if (!file_exists($fullPath)) { http_response_code(404); echo 'PDF nicht gefunden.'; exit; } $safe_name = 'MAHNUNG-' . preg_replace('/[^A-Za-z0-9\-]/', '_', $row['invoice_number']) . '-L' . $row['level'] . '.pdf'; header('Content-Type: application/pdf'); header('Content-Disposition: inline; filename="' . $safe_name . '"'); header('Content-Length: ' . filesize($fullPath)); readfile($fullPath); exit;