prepare("SELECT tenant_id, original_file_path FROM invoices WHERE id = ?"); $stmt->execute([$id]); $invoice = $stmt->fetch(); if (!$invoice) outputErrorImage('Error: Invoice not found'); // Authorization if ($decoded['role'] !== 'super_admin' && $invoice['tenant_id'] !== $decoded['tenant_id']) { outputErrorImage('Error: Unauthorized'); } $filePath = $invoice['original_file_path']; if (!file_exists($filePath)) { outputErrorImage('Error: File missing on disk'); } if (!is_readable($filePath)) { outputErrorImage('Error: Permission denied'); } $mime = mime_content_type($filePath); if (!$mime) $mime = 'application/octet-stream'; header("Content-Type: $mime"); header("Content-Length: " . filesize($filePath)); header("Cache-Control: public, max-age=3600"); readfile($filePath); exit;