public static function delete_template($id, $deleteplans = true) {
        global $DB;
        static::require_enabled();
        $template = new template($id);

        // First we do a permissions check.
        if (!$template->can_manage()) {
            throw new required_capability_exception($template->get_context(), 'moodle/competency:templatemanage',
                'nopermissions', '');
        }

        $transaction = $DB->start_delegated_transaction();
        $success = true;

        // Check if there are cohorts associated.
        $templatecohorts = template_cohort::get_relations_by_templateid($template->get('id'));
        foreach ($templatecohorts as $templatecohort) {
            $success = $templatecohort->delete();
            if (!$success) {
                break;
            }
        }

        // Still OK, delete or unlink the plans from the template.
        if ($success) {
            $plans = plan::get_records(array('templateid' => $template->get('id')));
            foreach ($plans as $plan) {
                $success = $deleteplans ? self::delete_plan($plan->get('id')) : self::unlink_plan_from_template($plan);
                if (!$success) {
                    break;
                }
            }
        }

        // Still OK, delete the template comptencies.
        if ($success) {
            $success = template_competency::delete_by_templateid($template->get('id'));
        }

        // OK - all set.
        if ($success) {
            // Create a template deleted event.
            $event = \core\event\competency_template_deleted::create_from_template($template);

            $success = $template->delete();
        }

        if ($success) {
            // Trigger a template deleted event.
            $event->trigger();

            // Commit the transaction.
            $transaction->allow_commit();
        } else {
            $transaction->rollback(new moodle_exception('Error while deleting the template.'));
        }

        return $success;
    }