logCsrfFailure($_SESSION['user']['user_id'] ?? null, 'delete_attachment'); ResponseHelper::forbidden('Invalid CSRF token'); } // Get attachment ID $attachmentId = $input['attachment_id'] ?? null; if (!$attachmentId || !is_numeric($attachmentId)) { ResponseHelper::error('Valid attachment ID is required'); } $attachmentId = (int)$attachmentId; try { $attachmentModel = new AttachmentModel(); // Get attachment details $attachment = $attachmentModel->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 $auditLog = new AuditLogModel(); $auditLog->log( $_SESSION['user']['user_id'], 'attachment_delete', 'ticket_attachments', $attachmentId, json_encode([ 'ticket_id' => $attachment['ticket_id'], 'filename' => $attachment['original_filename'], 'size' => $attachment['file_size'] ]), null ); ResponseHelper::success([], 'Attachment deleted successfully'); } catch (Exception $e) { ResponseHelper::serverError('Failed to delete attachment'); }