prepare("SELECT * FROM documents WHERE id = ?"); $stmt->execute([$document_id]); $document = $stmt->fetch(PDO::FETCH_ASSOC); if (!$document) { header("HTTP/1.1 404 Not Found"); exit; } // Permission check $user_role = $_SESSION['user_role']; $user_id = $_SESSION['user_id']; $has_permission = false; if ($user_role === 'staff') { $has_permission = true; } elseif ($user_role === 'partner') { $stmt = $pdo->prepare("SELECT id FROM partners WHERE user_id = ?"); $stmt->execute([$user_id]); $partner_id = $stmt->fetchColumn(); if ($partner_id && $document['partner_id'] == $partner_id) { $has_permission = true; } } if (!$has_permission) { header("HTTP/1.1 403 Forbidden"); exit("You do not have permission to access this file."); } // Serve the file for download $file_path = $document['file_path']; if (file_exists($file_path)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($document['file_name']) . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file_path)); readfile($file_path); exit; } else { header("HTTP/1.1 404 Not Found"); exit("File not found on server."); }