public static function delete_rule($ruleid, $coursecontext = null) {
        global $DB;

        subscription_manager::remove_all_subscriptions_for_rule($ruleid, $coursecontext);

        // Retrieve the rule from the DB before we delete it, so we have a record when we trigger a rule deleted event.
        $rule = $DB->get_record('tool_monitor_rules', array('id' => $ruleid));

        $success = $DB->delete_records('tool_monitor_rules', array('id' => $ruleid));

        // If successful trigger a rule deleted event.
        if ($success) {
            // It is possible that we are deleting rules associated with a deleted course, so we should be
            // passing the context as the second parameter.
            if (!is_null($coursecontext)) {
                $context = $coursecontext;
                $courseid = $rule->courseid;
            } else if (!empty($rule->courseid) && ($context = \context_course::instance($rule->courseid,
                    IGNORE_MISSING))) {
                $courseid = $rule->courseid;
            } else {
                $courseid = 0;
                $context = \context_system::instance();
            }

            $params = array(
                'objectid' => $rule->id,
                'courseid' => $courseid,
                'context' => $context
            );
            $event = \tool_monitor\event\rule_deleted::create($params);
            $event->add_record_snapshot('tool_monitor_rules', $rule);
            $event->trigger();
        }

        return $success;
    }