getAttachment($attachmentId); if (!$attachment) { ResponseHelper::notFound('Attachment not found'); } // Check permission $isAdmin = $_SESSION['user']['is_admin'] ?? false; if (!$attachmentModel->canUserDelete($attachmentId, $_SESSION['user']['user_id'], $isAdmin)) { ResponseHelper::forbidden('You do not have permission to delete this attachment'); } // Delete the file $uploadDir = $GLOBALS['config']['UPLOAD_DIR'] ?? dirname(__DIR__) . '/uploads'; $filePath = $uploadDir . '/' . $attachment['ticket_id'] . '/' . $attachment['filename']; if (file_exists($filePath)) { if (!unlink($filePath)) { ResponseHelper::serverError('Failed to delete file'); } } // Delete from database if (!$attachmentModel->deleteAttachment($attachmentId)) { ResponseHelper::serverError('Failed to delete attachment record'); } // Log the deletion $conn = new mysqli( $GLOBALS['config']['DB_HOST'], $GLOBALS['config']['DB_USER'], $GLOBALS['config']['DB_PASS'], $GLOBALS['config']['DB_NAME'] ); if (!$conn->connect_error) { $auditLog = new AuditLogModel($conn); $auditLog->log( $_SESSION['user']['user_id'], 'attachment_delete', 'ticket_attachments', (string)$attachmentId, [ 'ticket_id' => $attachment['ticket_id'], 'filename' => $attachment['original_filename'], 'size' => $attachment['file_size'] ] ); $conn->close(); } ResponseHelper::success([], 'Attachment deleted successfully'); } catch (Exception $e) { ResponseHelper::serverError('Failed to delete attachment'); }