public function delete($archive = true) {
        global $DB;

        if ($archive) {
            $this->status = BADGE_STATUS_ARCHIVED;
            $this->save();

            // Trigger event, badge archived.
            $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
            $event = \core\event\badge_archived::create($eventparams);
            $event->trigger();
            return;
        }

        $fs = get_file_storage();

        // Remove all issued badge image files and badge awards.
        // Cannot bulk remove area files here because they are issued in user context.
        $awards = $this->get_awards();
        foreach ($awards as $award) {
            $usercontext = context_user::instance($award->userid);
            $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
        }
        $DB->delete_records('badge_issued', array('badgeid' => $this->id));

        // Remove all badge criteria.
        $criteria = $this->get_criteria();
        foreach ($criteria as $criterion) {
            $criterion->delete();
        }

        // Delete badge images.
        $badgecontext = $this->get_context();
        $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);

        // Delete endorsements, alignments and related badges.
        $DB->delete_records('badge_endorsement', array('badgeid' => $this->id));
        $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid';
        $relatedparams = array(
            'badgeid' => $this->id,
            'relatedbadgeid' => $this->id
        );
        $DB->delete_records_select('badge_related', $relatedsql, $relatedparams);
        $DB->delete_records('badge_alignment', array('badgeid' => $this->id));

        // Finally, remove badge itself.
        $DB->delete_records('badge', array('id' => $this->id));

        // Trigger event, badge deleted.
        $eventparams = array('objectid' => $this->id,
            'context' => $this->get_context(),
            'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
            );
        $event = \core\event\badge_deleted::create($eventparams);
        $event->trigger();
    }