getConnection(); $stmt = $pdo->prepare(" SELECT a.*, t.employee_id, e.auth_user_id FROM employee_training_attachments a JOIN employee_trainings t ON t.id = a.training_id JOIN employees e ON e.id = t.employee_id WHERE a.id = :id LIMIT 1 "); $stmt->execute(['id' => $id]); $att = $stmt->fetch(PDO::FETCH_ASSOC); if (!$att) { http_response_code(404); exit('Allegato non trovato.'); } /* Access: HR or owning employee */ $roleStmt = $pdo->prepare(" SELECT r.name FROM auth_users u LEFT JOIN auth_roles r ON r.id = u.role_id WHERE u.id = :id LIMIT 1 "); $roleStmt->execute(['id' => $currentUserId]); $role = (string)$roleStmt->fetchColumn(); $hrRoles = ['Admin', 'Superuser', 'employee-hr', 'manager']; $isHr = in_array($role, $hrRoles, true); if (!$isHr && (int)$att['auth_user_id'] !== $currentUserId) { http_response_code(403); exit('Accesso negato.'); } $path = __DIR__ . '/../../files/employees/' . (int)$att['employee_id'] . '/trainings/' . $att['stored_name']; if (!is_file($path)) { http_response_code(404); exit('File non trovato sul server.'); } while (ob_get_level() > 0) { ob_end_clean(); } header('Content-Type: ' . (!empty($att['mime_type']) ? $att['mime_type'] : 'application/octet-stream')); header('Content-Disposition: attachment; filename="' . rawurlencode($att['original_name']) . '"'); header('Content-Length: ' . filesize($path)); header('Cache-Control: private, max-age=0, must-revalidate'); readfile($path); exit;