public static function delete_completion_by_approved_userlist(approved_userlist $userlist, int $courseid = null, int $cmid = null) {
        global $DB;
        $userids = $userlist->get_userids();

        if (empty($userids)) {
            return;
        }

        list($useridsql, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);

        if (isset($cmid)) {
            $params['coursemoduleid'] = $cmid;

            // Only delete the record for course modules completion.
            $sql = "coursemoduleid = :coursemoduleid AND userid {$useridsql}";
            $DB->delete_records_select('course_modules_completion', $sql, $params);
            return;
        }

        if (isset($courseid)) {
            $params['course'] = $courseid;

            // Find records relating to course modules.
            $sql = "SELECT cmc.id
                      FROM {course_completion_criteria} ccc
                      JOIN {course_modules_completion} cmc ON ccc.moduleinstance = cmc.coursemoduleid
                     WHERE ccc.course = :course AND cmc.userid {$useridsql}";
            $recordids = $DB->get_records_sql($sql, $params);
            $ids = array_keys($recordids);
            if (!empty($ids)) {
                list($deletesql, $deleteparams) = $DB->get_in_or_equal($ids);
                $deletesql = 'id ' . $deletesql;
                $DB->delete_records_select('course_modules_completion', $deletesql, $deleteparams);
            }

            $sql = "course = :course AND userid {$useridsql}";
            $DB->delete_records_select('course_completion_crit_compl', $sql, $params);
            $DB->delete_records_select('course_completions', $sql, $params);
        }
    }