<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace theme_universe\output;

use html_writer;
use stdClass;
use moodle_url;
use context_course;
use context_system;
use core_course_list_element;
use custom_menu;
use core_completion;
use action_menu_filler;
use action_menu_link_secondary;
use action_menu;
use action_link;
use core_text;
use coding_exception;
use navigation_node;
use context_header;
use pix_icon;
use renderer_base;
use theme_config;
use get_string;
use core_course_category;
use theme_universe\util\user;
use theme_universe\util\course;

/**
 * Renderers to align Moodle's HTML with that expected by Bootstrap
 *
 * @package    theme_universe
 * @copyright  2023 Marcin Czaja (https://rosea.io)
 * @license    Commercial https://themeforest.net/licenses
 */
class core_renderer extends \core_renderer {

    public function edit_button(moodle_url $url, string $method = 'post') {
        if ($this->page->theme->haseditswitch) {
            return;
        }
        $url->param('sesskey', sesskey());
        if ($this->page->user_is_editing()) {
            $url->param('edit', 'off');
            $editstring = get_string('turneditingoff');
        } else {
            $url->param('edit', 'on');
            $editstring = get_string('turneditingon');
        }
        $button = new \single_button($url, $editstring, 'post', ['class' => 'btn btn-primary']);
        return $this->render_single_button($button);
    }

    /**
     * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
     * that should be included in the <head> tag. Designed to be called in theme
     * layout.php files.
     *
     * @return string HTML fragment.
     */
    public function standard_head_html() {
        $output = parent::standard_head_html();
        global $USER;

        $googleanalyticscode = "<script
                                    async
                                    src='https://www.googletagmanager.com/gtag/js?id=GOOGLE-ANALYTICS-CODE'>
                                </script>
                                <script>
                                    window.dataLayer = window.dataLayer || [];
                                    function gtag() {
                                        dataLayer.push(arguments);
                                    }
                                    gtag('js', new Date());
                                    gtag('config', 'GOOGLE-ANALYTICS-CODE');
                                </script>";

        $theme = theme_config::load('universe');

        if (!empty($theme->settings->googleanalytics) && isloggedin()) {
            $output .= str_replace(
                "GOOGLE-ANALYTICS-CODE",
                trim($theme->settings->googleanalytics),
                $googleanalyticscode
            );
        }

        return $output;
    }

    /*
    *
    * Method to get reference to $CFG->themedir variable
    *
    */
    function theme_universe_themedir() {
        global $CFG;

        $teme_dir = '/theme';

        if (isset($CFG->themedir)) {
            $teme_dir = $CFG->themedir;
            $teme_dir = str_replace($CFG->dirroot, '', $CFG->themedir);
        }

        return $teme_dir;
    }


    /**
     *
     * Method to load theme element form 'layout/parts' folder
     *
     */
    public function theme_part($name, $vars = array()) {

        global $CFG;

        $element = $name . '.php';
        $candidate1 = $this->page->theme->dir . '/layout/parts/' . $element;

        // Require for child theme.
        if (file_exists($candidate1)) {
            $candidate = $candidate1;
        } else {
            $candidate = $CFG->dirroot . theme_universe_themedir() . '/universe/layout/parts/' . $element;
        }

        if (!is_readable($candidate)) {
            debugging("Could not include element $name.");
            return;
        }

        ob_start();
        include($candidate);
        $output = ob_get_clean();
        return $output;
    }

    /**
     * Renders the custom menu
     *
     * @param custom_menu $menu
     * @return mixed
     */
    protected function render_custom_menu(custom_menu $menu) {
        if (!$menu->has_children()) {
            return '';
        }

        $content = '';
        foreach ($menu->get_children() as $item) {
            $context = $item->export_for_template($this);
            $content .= $this->render_from_template('core/moremenu_children', $context);
        }

        return $content;
    }

    /**
     * Outputs the favicon urlbase.
     *
     * @return string an url
     */
    public function favicon() {
        global $CFG;
        $theme = theme_config::load('universe');
        $favicon = $theme->setting_file_url('favicon', 'favicon');

        if (!empty(($favicon))) {
            $urlreplace = preg_replace('|^https?://|i', '//', $CFG->wwwroot);
            $favicon = str_replace($urlreplace, '', $favicon);

            return new moodle_url($favicon);
        }

        return parent::favicon();
    }

    public function render_lang_menu() {
        $langs = get_string_manager()->get_list_of_translations();
        $haslangmenu = $this->lang_menu() != '';
        $menu = new custom_menu;

        if ($haslangmenu) {
            $strlang = get_string('language');
            $currentlang = current_language();
            if (isset($langs[$currentlang])) {
                $currentlang = $langs[$currentlang];
            } else {
                $currentlang = $strlang;
            }
            $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
            foreach ($langs as $langtype => $langname) {
                $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
            }
            foreach ($menu->get_children() as $item) {
                $context = $item->export_for_template($this);
            }

            $context->currentlangname = array_search($currentlang, $langs);

            if (isset($context)) {
                return $this->render_from_template('theme_universe/lang_menu', $context);
            }
        }
    }

    public function render_lang_menu_login() {
        $langs = get_string_manager()->get_list_of_translations();
        $haslangmenu = $this->lang_menu() != '';
        $menu = new custom_menu;

        if ($haslangmenu) {
            $strlang = get_string('language');
            $currentlang = current_language();
            if (isset($langs[$currentlang])) {
                $currentlang = $langs[$currentlang];
            } else {
                $currentlang = $strlang;
            }
            $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
            foreach ($langs as $langtype => $langname) {
                $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
            }
            foreach ($menu->get_children() as $item) {
                $context = $item->export_for_template($this);
            }

            $context->currentlangname = array_search($currentlang, $langs);

            if (isset($context)) {
                return $this->render_from_template('theme_universe/lang_menu_login', $context);
            }
        }
    }

    public static function get_course_progress_count($course, $userid = 0) {
        global $USER;

        // Make sure we continue with a valid userid.
        if (empty($userid)) {
            $userid = $USER->id;
        }

        $completion = new \completion_info($course);

        // First, let's make sure completion is enabled.
        if (!$completion->is_enabled()) {
            return null;
        }

        if (!$completion->is_tracked_user($userid)) {
            return null;
        }

        // Before we check how many modules have been completed see if the course has.
        if ($completion->is_course_complete($userid)) {
            return 100;
        }

        // Get the number of modules that support completion.
        $modules = $completion->get_activities();
        $count = count($modules);
        if (!$count) {
            return null;
        }

        // Get the number of modules that have been completed.
        $completed = 0;
        foreach ($modules as $module) {
            $data = $completion->get_data($module, true, $userid);
            $completed += $data->completionstate == COMPLETION_INCOMPLETE ? 0 : 1;
        }

        return ($completed / $count) * 100;
    }

    /**
     *
     * Outputs the course progress if course completion is on.
     *
     * @return string Markup.
     */
    protected function courseprogress($course) {
        global $USER;
        $theme = \theme_config::load('universe');

        $output = '';
        $courseformat = course_get_format($course);

        if (get_class($courseformat) != 'format_tiles') {
            $completion = new \completion_info($course);

            // Start Course progress count.
            // Make sure we continue with a valid userid.
            if (empty($userid)) {
                $userid = $USER->id;
            }
            $completion = new \completion_info($course);

            // Get the number of modules that support completion.
            $modules = $completion->get_activities();
            $count = count($modules);

            if (!$count) {
                return null;
            }

            // Get the number of modules that have been completed.
            $completed = 0;
            foreach ($modules as $module) {
                $data = $completion->get_data($module, true, $userid);
                $completed += $data->completionstate == COMPLETION_INCOMPLETE ? 0 : 1;
            }
            $progresscountc = $completed;
            $progresscounttotal = $count;
            // End progress count.

            if ($completion->is_enabled()) {
                $templatedata = new \stdClass;
                $templatedata->progress = \core_completion\progress::get_course_progress_percentage($course);
                $templatedata->progresscountc = $progresscountc;
                $templatedata->progresscounttotal = $progresscounttotal;

                if (!is_null($templatedata->progress)) {
                    $templatedata->progress = floor($templatedata->progress);
                } else {
                    $templatedata->progress = 0;
                }
                if (get_config('theme_universe', 'courseprogressbar') == 1) {
                    $progressbar = '<div class="rui-course-progresschart">' .
                        $this->render_from_template('theme_universe/progress-chart', $templatedata) .
                        '</div>';
                    if (has_capability('report/progress:view',  \context_course::instance($course->id))) {
                        $courseprogress = new \moodle_url('/report/progress/index.php');
                        $courseprogress->param('course', $course->id);
                        $courseprogress->param('sesskey', sesskey());
                        $output .= html_writer::link($courseprogress, $progressbar, array('class' => 'rui-course-progressbar border rounded px-3 pt-2 mb-3'));
                    } else {
                        $output .= $progressbar;
                    }
                }
            }
        }

        return $output;
    }


    /**
     *
     * Returns HTML to display course contacts.
     *
     */
    public function course_teachers() {
        global $CFG, $COURSE, $DB;
        $course = $DB->get_record('course', ['id' => $COURSE->id]);
        $course = new core_course_list_element($course);
        $instructors = $course->get_course_contacts();

        if (!empty($instructors)) {
            $content = html_writer::start_div('course-teachers-box');

            foreach ($instructors as $key => $instructor) {
                $name = $instructor['username'];
                $role = $instructor['rolename'];
                $roleshortname = $instructor['role']->shortname;

                if ($instructor['role']->id == '3') {
                    $url = $CFG->wwwroot . '/user/profile.php?id=' . $key;
                    $user = $instructor['user'];
                    $userutil = new user($user->id);
                    $picture = $userutil->get_user_picture();

                    $content .= "<div class='course-contact-title-item'>
                        <a href='{$url}' 'title='{$name}'
                            class='course-contact rui-user-{$roleshortname}'>";
                    $content .= "<img src='{$picture}'
                        class='course-teacher-avatar' alt='{$name}'
                        title='{$name} - {$role}' data-toggle='tooltip'/>";
                    $content .= "<div class='course-teacher-content'>
                        <span class='course-teacher-role'>{$role}</span>
                        <h4 class='course-teacher-name'>{$name}</h4></div>";
                    $content .= "</a></div>";
                }
            }

            $content .= html_writer::end_div(); // End .teachers-box.
            return $content;
        }
    }

    public function course_contacts() {
        global $CFG, $COURSE, $DB;
        $course = $DB->get_record('course', ['id' => $COURSE->id]);
        $course = new core_course_list_element($course);
        $instructors = $course->get_course_contacts();

        if (!empty($instructors)) {
            $content = '';

            foreach ($instructors as $key => $instructor) {
                $name = $instructor['username'];
                $role = $instructor['rolename'];
                $roleshortname = $instructor['role']->shortname;

                $url = $CFG->wwwroot . '/user/profile.php?id=' . $key;
                $user = $instructor['user'];
                $userutil = new user($user->id);
                $picture = $userutil->get_user_picture(384);

                $user = $DB->get_record('user', array('id' => $key));
                $desc = $user->description;

                $content .= "<div class='course-teachers-box my-0'>";
                $content .= "<div class='course-contact course-teacher-avatar mt-0'><img src='{$picture}'
                    class='course-teacher-avatar'
                    alt='{$name}, {$role}'/></div>";
                $content .= "<div class='course-contact-title-item d-block'>
                    <span class='course-teacher-role d-block'>{$role}</span>
                    <a href='{$url}' 'title='{$name}'
                        class='d-flex flex-wrap course-contact rui-user-{$roleshortname}'>
                        <h4 class='course-teacher-name mb-0'>{$name}</h4></a></div>";
                $content .= "<div class='rui-course-contact-desc'>{$desc}</div></div>";
            }

            return $content;
        }
    }

    /**
     *
     * Returns HTML to display course details.
     *
     */
    protected function course_details() {
        global $CFG, $COURSE, $DB;

        if ($this->page->theme->settings->ipcoursedates == 1) {
            $course = $DB->get_record('course', ['id' => $COURSE->id]);
            $course = new core_course_list_element($course);
            $content = '';
            $tempcourse = $DB->get_record('course_categories', ['id' => $COURSE->id]);
    
            $content .= html_writer::start_div('rui-course-details d-flex');
            $content .= html_writer::start_div('rui-custom-field-box rui-course-startdate');
            $content .= html_writer::tag('span', get_string('startdate', 'moodle'), ['class' => 'rui-custom-field-name']);
            $content .= html_writer::tag('span', userdate($course->startdate, get_string('strftimedaydate', 'core_langconfig')), ['class' => 'rui-custom-field-value']);
            $content .= html_writer::end_div();
    
            // Course End date.
            $courseenddate = $COURSE->enddate;
            if ($courseenddate != '0') {
                $content .= html_writer::start_div('rui-custom-field-box rui-course-startdate');
                $content .= html_writer::tag('span', get_string('enddate', 'moodle'), ['class' => 'rui-course-enddate-label rui-custom-field-name']);
                $content .= html_writer::tag('span', userdate($courseenddate, get_string('strftimedaydate', 'core_langconfig')), ['class' => 'rui-course-enddate rui-custom-field-value']);
                $content .= html_writer::end_div();
            }
            $content .= html_writer::end_div(); // .rui-course-details.
    
            return $content;
        }

    }

    /**
     *
     * Returns HTML to display course summary.
     *
     */
    protected function course_summary($courseid = 0, $content = '') {
        global $COURSE, $CFG;
        $output = '';

        require_once($CFG->libdir . '/filelib.php');

        $iscourseid = $courseid ? $courseid : $COURSE->id;
        $iscontent = $content ? $content : $COURSE->summary;
        $context = context_course::instance($iscourseid);
        $desc = file_rewrite_pluginfile_urls($iscontent, 'pluginfile.php', $context->id, 'course', 'summary', null);

        $output .= html_writer::start_div('rui-course-desc');
        $output .= format_text($desc, FORMAT_HTML);
        $output .= html_writer::end_div();

        return $output;
    }

    /**
     * Outputs the pix url base
     *
     * @return string an URL.
     */
    public function get_pix_image_url_base() {
        global $CFG;

        return $CFG->wwwroot . "/theme/universe/pix";
    }

    /**
     *
     */
    public function course_hero_url() {
        global $CFG, $COURSE, $DB;

        $course = $DB->get_record('course', ['id' => $COURSE->id]);

        $course = new core_course_list_element($course);

        $courseimage = '';
        $imageindex = 1;
        foreach ($course->get_course_overviewfiles() as $file) {
            $isimage = $file->is_valid_image();

            $url = new moodle_url("$CFG->wwwroot/pluginfile.php" . '/' .
                $file->get_contextid() . '/' . $file->get_component() . '/' .
                $file->get_filearea() .
                $file->get_filepath() .
                $file->get_filename(), ['forcedownload' => !$isimage]);

            if ($isimage) {
                $courseimage = $url;
            }

            if ($imageindex == 2) {
                break;
            }

            $imageindex++;
        }

        $html = '';
        // Create html for header.
        if (!empty($courseimage)) {
            $html .= $courseimage;
        }
        return $html;
    }

    /**
     * Returns HTML to display course hero.
     *
     */
    public function course_hero() {
        global $CFG, $COURSE, $DB;

        $course = $DB->get_record('course', ['id' => $COURSE->id]);

        $course = new core_course_list_element($course);

        $courseimage = '';

        $courseutil = new course($course);
        $courseimage = $courseutil->get_summary_image(false); // Remove repeatable pattern on the course page.

        $html = '';
        // Create html for header.
        if (!empty($courseimage)) {
            $html .= $courseimage;
        }
        return $html;
    }


    /**
     * Breadcrumbs
     *
     */
    public function breadcrumbs() {
        global $USER, $COURSE, $CFG;

        $header = new stdClass();
        $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
        $header->navbar = $this->navbar();
        $header->courseheader = $this->course_header();
        $html = $this->render_from_template('theme_universe/breadcrumbs', $header);

        return $html;
    }


    /**
     * Wrapper for header elements.
     *
     * @return string HTML to display the main header.
     */
    public function simple_header() {

        global $USER, $COURSE, $CFG;
        $html = null;

        if (
            $this->page->include_region_main_settings_in_header_actions() &&
            !$this->page->blocks->is_block_present('settings')
        ) {
            // Only include the region main settings if the page has requested it and it doesn't already have
            // the settings block on it. The region main settings are included in the settings block and
            // duplicating the content causes behat failures.
            $this->page->add_header_action(html_writer::div(
                $this->region_main_settings_menu(),
                'd-print-none',
                ['id' => 'region-main-settings-menu']
            ));
        }

        $header = new stdClass();
        $header->settingsmenu = $this->context_header_settings_menu();
        $header->contextheader = $this->context_header();
        $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
        $header->navbar = $this->navbar();
        $header->pageheadingbutton = $this->page_heading_button();
        $header->courseheader = $this->course_header();
        $header->headeractions = $this->page->get_header_actions();

        if ($this->page->pagelayout != 'admin') {
            $html .= $this->render_from_template('theme_universe/header', $header);
        }

        if ($this->page->pagelayout == 'admin') {
            $html .= $this->render_from_template('theme_universe/header_admin', $header);
        }

        return $html;
    }




    public function display_course_progress() {
        $html = null;
        $html .= $this->courseprogress($this->page->course);
        return $html;
    }

    /**
     * Wrapper for header elements.
     *
     * @return string HTML to display the main header.
     */
    public function full_header() {
        global $USER, $COURSE, $CFG;
        $html = null;
        $homepage = get_home_page();
        // Add a special case since /my/courses is a part of the /my subsystem.
        if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
            $homepagetype = 'my-index';
        } else if ($homepage == HOMEPAGE_SITE) {
            $homepagetype = 'site-index';
        }
        if (
            $this->page->include_region_main_settings_in_header_actions() &&
            !$this->page->blocks->is_block_present('settings')
        ) {
            // Only include the region main settings if the page has requested it and it doesn't already have
            // the settings block on it. The region main settings are included in the settings block and
            // duplicating the content causes behat failures.
            $this->page->add_header_action(html_writer::div(
                $this->region_main_settings_menu(),
                'd-print-none',
                ['id' => 'region-main-settings-menu']
            ));
        }

        $header = new stdClass();
        $header->settingsmenu = $this->context_header_settings_menu();
        $header->contextheader = $this->context_header();
        $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
        $header->navbar = $this->navbar();
        $header->pageheadingbutton = $this->page_heading_button();
        $header->courseheader = $this->course_header();
        $header->headeractions = $this->page->get_header_actions();

        if ($this->page->theme->settings->ipcoursedetails == 1) {
            $html .= html_writer::start_tag('div', array('class' => 'rui-course-info-box'));
            $html .= html_writer::start_tag('div', array('class' => 'rui-cinfo-container d-flex flex-wrap'));
            $html .= $this->course_details();
            $html .= html_writer::start_tag('div', array('class' => 'rui-course-header-custom-f'));
            $courseutil = new course($COURSE);
            $html .= $courseutil->course_get_taux();
            $html .= html_writer::end_tag('div'); // .rui-course-header-custom-f.
            $html .= html_writer::end_tag('div');
            $html .= html_writer::end_tag('div');
        }

        $html .= $this->render_from_template('theme_universe/header', $header);
        if ($this->page->theme->settings->ipcoursesummary == 1) {
            $html .= $this->course_summary();
        }

        $html .= html_writer::start_tag('div', array('class' => 'rui-course-header-color'));
        if ($this->page->theme->settings->cccteachers == 1) {
            $html .= $this->course_teachers();
        }

        $html .= html_writer::end_tag('div'); // End .rui-course-header.

        return $html;
    }

    /**
     * Wrapper for header elements.
     *
     * @return string HTML to display the main header.
     */
    public function efull_header() {
        global $USER, $COURSE, $CFG;

        $html = null;

        $html .= html_writer::start_tag('div', array('class' => 'rui-course-header'));

        if ($this->page->theme->settings->ipcoursedetails == 1) {
            $html .= html_writer::start_tag('div', array('class' => 'rui-course-info-box'));
            $html .= html_writer::start_tag('div', array('class' => 'rui-course-header-custom-f'));
            $courseutil = new course($COURSE);
            $html .= $courseutil->course_get_taux();
            $html .= html_writer::end_tag('div'); // .rui-course-header-custom-f.
            $html .= $this->course_details();
            $html .= html_writer::end_tag('div');
        }

        if ($this->page->theme->settings->ecoursesummary == 1) {
            $html .= $this->course_summary();
        }

        $html .= html_writer::end_tag('div'); // Rui-course-header.
        $html .= $this->get_enrollfields();

        return $html;
    }


    /**
     * Wrapper for header elements.
     *
     * @return string HTML to display the main header.
     */
    public function clean_header() {
        global $USER, $COURSE, $CFG;
        $html = null;

        $homepage = get_home_page();
        // Add a special case since /my/courses is a part of the /my subsystem.
        if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
            $homepagetype = 'my-index';
        } else if ($homepage == HOMEPAGE_SITE) {
            $homepagetype = 'site-index';
        }
        if (
            $this->page->include_region_main_settings_in_header_actions() &&
            !$this->page->blocks->is_block_present('settings')
        ) {
            // Only include the region main settings if the page has requested it and it doesn't already have
            // the settings block on it. The region main settings are included in the settings block and
            // duplicating the content causes behat failures.
            $this->page->add_header_action(html_writer::div(
                $this->region_main_settings_menu(),
                'd-print-none',
                ['id' => 'region-main-settings-menu']
            ));
        }

        $header = new stdClass();
        $header->courseheader = $this->course_header();
        $header->headeractions = $this->page->get_header_actions();

        $html .= $this->render_from_template('theme_universe/header', $header);

        return $html;
    }


    /**
     * Returns standard navigation between activities in a course.
     *
     * @return string the navigation HTML.
     */
    public function activity_navigation() {
        // First we should check if we want to add navigation.
        $context = $this->page->context;
        if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
            || $context->contextlevel != CONTEXT_MODULE
        ) {
            return '';
        }
        // If the activity is in stealth mode, show no links.
        if ($this->page->cm->is_stealth()) {
            return '';
        }
        $course = $this->page->cm->get_course();
        $courseformat = course_get_format($course);

        // Get a list of all the activities in the course.
        $modules = get_fast_modinfo($course->id)->get_cms();
        // Put the modules into an array in order by the position they are shown in the course.
        $mods = [];
        $activitylist = [];
        foreach ($modules as $module) {
            // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
            if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
                continue;
            }
            $mods[$module->id] = $module;
            // No need to add the current module to the list for the activity dropdown menu.
            if ($module->id == $this->page->cm->id) {
                continue;
            }
            // Module name.
            $modname = $module->get_formatted_name();
            // Display the hidden text if necessary.
            if (!$module->visible) {
                $modname .= ' ' . get_string('hiddenwithbrackets');
            }
            // Module URL.
            $linkurl = new moodle_url($module->url, array('forceview' => 1));
            // Add module URL (as key) and name (as value) to the activity list array.
            $activitylist[$linkurl->out(false)] = $modname;
        }
        $nummods = count($mods);
        // If there is only one mod then do nothing.
        if ($nummods == 1) {
            return '';
        }
        // Get an array of just the course module ids used to get the cmid value based on their position in the course.
        $modids = array_keys($mods);
        // Get the position in the array of the course module we are viewing.
        $position = array_search($this->page->cm->id, $modids);
        $prevmod = null;
        $nextmod = null;
        // Check if we have a previous mod to show.
        if ($position > 0) {
            $prevmod = $mods[$modids[$position - 1]];
        }
        // Check if we have a next mod to show.
        if ($position < ($nummods - 1)) {
            $nextmod = $mods[$modids[$position + 1]];
        }
        $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
        $renderer = $this->page->get_renderer('core', 'course');
        return $renderer->render($activitynav);
    }


    /**
     * This is an optional menu that can be added to a layout by a theme. It contains the
     * menu for the course administration, only on the course main page.
     *
     * @return string
     */
    public function context_header_settings_menu() {
        $context = $this->page->context;
        $menu = new action_menu();

        $items = $this->page->navbar->get_items();
        $currentnode = end($items);

        $showcoursemenu = false;
        $showfrontpagemenu = false;
        $showusermenu = false;

        // We are on the course home page.
        if (($context->contextlevel == CONTEXT_COURSE) &&
            !empty($currentnode) &&
            ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)
        ) {
            $showcoursemenu = true;
        }

        $courseformat = course_get_format($this->page->course);
        // This is a single activity course format, always show the course menu on the activity main page.
        if (
            $context->contextlevel == CONTEXT_MODULE &&
            !$courseformat->has_view_page()
        ) {

            $this->page->navigation->initialise();
            $activenode = $this->page->navigation->find_active_node();
            // If the settings menu has been forced then show the menu.
            if ($this->page->is_settings_menu_forced()) {
                $showcoursemenu = true;
            } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
                $activenode->type == navigation_node::TYPE_RESOURCE)) {

                // We only want to show the menu on the first page of the activity. This means
                // the breadcrumb has no additional nodes.
                if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
                    $showcoursemenu = true;
                }
            }
        }

        // This is the site front page.
        if (
            $context->contextlevel == CONTEXT_COURSE &&
            !empty($currentnode) &&
            $currentnode->key === 'home'
        ) {
            $showfrontpagemenu = true;
        }

        // This is the user profile page.
        if (
            $context->contextlevel == CONTEXT_USER &&
            !empty($currentnode) &&
            ($currentnode->key === 'myprofile')
        ) {
            $showusermenu = true;
        }

        if ($showfrontpagemenu) {
            $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
            if ($settingsnode) {
                // Build an action menu based on the visible nodes from this navigation tree.
                $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);

                // We only add a list to the full settings menu if we didn't include every node in the short menu.
                if ($skipped) {
                    $text = get_string('morenavigationlinks');
                    $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
                    $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
                    $menu->add_secondary_action($link);
                }
            }
        } else if ($showcoursemenu) {
            $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
            if ($settingsnode) {
                // Build an action menu based on the visible nodes from this navigation tree.
                $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);

                // We only add a list to the full settings menu if we didn't include every node in the short menu.
                if ($skipped) {
                    $text = get_string('morenavigationlinks');
                    $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
                    $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
                    $menu->add_secondary_action($link);
                }
            }
        } else if ($showusermenu) {
            // Get the course admin node from the settings navigation.
            $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
            if ($settingsnode) {
                // Build an action menu based on the visible nodes from this navigation tree.
                $this->build_action_menu_from_navigation($menu, $settingsnode);
            }
        }

        return $this->render($menu);
    }

    public function customeditblockbtn() {
        $header = new stdClass();
        $header->settingsmenu = $this->context_header_settings_menu();
        $header->pageheadingbutton = $this->page_heading_button();

        $html = $this->render_from_template('theme_universe/header_settings_menu', $header);

        return $html;
    }

    /**
     * Renders the context header for the page.
     *
     * @param array $headerinfo Heading information.
     * @param int $headinglevel What 'h' level to make the heading.
     * @return string A rendered context header.
     */
    public function context_header($headerinfo = null, $headinglevel = 1): string {
        global $DB, $USER, $CFG, $SITE;
        require_once($CFG->dirroot . '/user/lib.php');
        $context = $this->page->context;
        $heading = null;
        $imagedata = null;
        $subheader = null;
        $userbuttons = null;

        // Make sure to use the heading if it has been set.
        if (isset($headerinfo['heading'])) {
            $heading = $headerinfo['heading'];
        } else {
            $heading = $this->page->heading;
        }

        // The user context currently has images and buttons. Other contexts may follow.
        if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
            if (isset($headerinfo['user'])) {
                $user = $headerinfo['user'];
            } else {
                // Look up the user information if it is not supplied.
                $user = $DB->get_record('user', array('id' => $context->instanceid));
            }

            // If the user context is set, then use that for capability checks.
            if (isset($headerinfo['usercontext'])) {
                $context = $headerinfo['usercontext'];
            }

            // Only provide user information if the user is the current user, or a user which the current user can view.
            // When checking user_can_view_profile(), either:
            // If the page context is course, check the course context (from the page object) or;
            // If page context is NOT course, then check across all courses.
            $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;

            if (user_can_view_profile($user, $course)) {
                // Use the user's full name if the heading isn't set.
                if (empty($heading)) {
                    $heading = fullname($user);
                }

                $imagedata = $this->user_picture($user, array('size' => 100));

                // Check to see if we should be displaying a message button.
                if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
                    $userbuttons = array(
                        'messages' => array(
                            'buttontype' => 'message',
                            'title' => get_string('message', 'message'),
                            'url' => new moodle_url('/message/index.php', ['id' => $user->id]),
                            'image' => 't/message',
                            'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
                            'page' => $this->page
                        )
                    );

                    if ($USER->id != $user->id) {
                        $iscontact = \core_message\api::is_contact($USER->id, $user->id);
                        $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
                        $contacturlaction = $iscontact ? 't/removecontact' : 't/addcontact';
                        $contactimage = $iscontact ? 't/removecontact' : 't/addcontact';
                        $userbuttons['togglecontact'] = array(
                            'buttontype' => 'togglecontact',
                            'title' => get_string($contacttitle, 'message'),
                            'url' => new moodle_url(
                                '/message/index.php',
                                array(
                                    'user1' => $USER->id,
                                    'user2' => $user->id,
                                    $contacturlaction => $user->id,
                                    'sesskey' => sesskey()
                                )
                            ),
                            'image' => $contactimage,
                            'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
                            'page' => $this->page
                        );
                    }

                    $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
                }
            } else {
                $heading = null;
            }
        }

        $prefix = null;
        if ($context->contextlevel == CONTEXT_MODULE) {
            if ($this->page->course->format === 'singleactivity') {
                $heading = $this->page->course->fullname;
            } else {
                $heading = $this->page->cm->get_formatted_name();
                $imagedata = $this->pix_icon('monologo', '', $this->page->activityname, ['class' => 'activityicon']);
                $purposeclass = plugin_supports('mod', $this->page->activityname, FEATURE_MOD_PURPOSE);
                $purposeclass .= ' activityiconcontainer';
                $purposeclass .= ' modicon_' . $this->page->activityname;
                $imagedata = html_writer::tag('div', $imagedata, ['class' => $purposeclass]);
                $prefix = get_string('modulename', $this->page->activityname);
            }
        }

        $contextheader = new \context_header($heading, $headinglevel, $imagedata, $userbuttons, $prefix);
        return $this->render_context_header($contextheader);
    }


    /**
     * Construct a user menu, returning HTML that can be echoed out by a
     * layout file.
     *
     * @param stdClass $user A user object, usually $USER.
     * @param bool $withlinks true if a dropdown should be built.
     * @return string HTML fragment.
     */
    public function user_menu($user = null, $withlinks = null) {
        global $USER, $CFG;
        require_once($CFG->dirroot . '/user/lib.php');

        if (is_null($user)) {
            $user = $USER;
        }

        // Note: this behaviour is intended to match that of core_renderer::login_info,
        // but should not be considered to be good practice; layout options are
        // intended to be theme-specific. Please don't copy this snippet anywhere else.
        if (is_null($withlinks)) {
            $withlinks = empty($this->page->layout_options['nologinlinks']);
        }

        // Add a class for when $withlinks is false.
        $usermenuclasses = 'usermenu';
        if (!$withlinks) {
            $usermenuclasses .= ' withoutlinks';
        }

        $returnstr = "";

        // If during initial install, return the empty return string.
        if (during_initial_install()) {
            return $returnstr;
        }

        $loginpage = $this->is_login_page();
        $loginurl = get_login_url();
        // If not logged in, show the typical not-logged-in string.
        if (!isloggedin()) {
            if (!$loginpage) {
                $returnstr .= "<a class=\"rui-topbar-btn rui-login-btn text-decoration-none\" href=\"$loginurl\"><span class=\"rui-login-btn-txt\">" .
                    get_string('login') .
                    '</span>
                <svg class="ml-2" width="20" height="20" fill="none" viewBox="0 0 24 24">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M9.75 8.75L13.25 12L9.75 15.25"></path>
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M9.75 4.75H17.25C18.3546 4.75 19.25 5.64543 19.25 6.75V17.25C19.25 18.3546 18.3546 19.25 17.25 19.25H9.75">
                </path>
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 12H4.75"></path>
                </svg></a>';
            }
            return html_writer::div(
                html_writer::span(
                    $returnstr,
                    'login'
                ),
                $usermenuclasses
            );
        }

        // If logged in as a guest user, show a string to that effect.
        if (isguestuser()) {
            $icon = '<svg class="mr-2"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                xmlns="http://www.w3.org/2000/svg">
            <path d="M10 12C10 12.5523 9.55228 13 9 13C8.44772 13 8 12.5523 8
            12C8 11.4477 8.44772 11 9 11C9.55228 11 10 11.4477 10 12Z"
                fill="currentColor"
                />
            <path d="M15 13C15.5523 13 16 12.5523 16 12C16 11.4477 15.5523 11
            15 11C14.4477 11 14 11.4477 14 12C14 12.5523 14.4477 13 15 13Z"
                fill="currentColor"
                />
            <path fill-rule="evenodd"
                clip-rule="evenodd"
                d="M12.0244 2.00003L12 2C6.47715 2 2 6.47715 2 12C2 17.5228
                6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.74235
            17.9425 2.43237 12.788 2.03059L12.7886 2.0282C12.5329 2.00891
            12.278 1.99961 12.0244 2.00003ZM12 20C16.4183 20 20 16.4183 20
            12C20 11.3014 19.9105 10.6237 19.7422
            9.97775C16.1597 10.2313 12.7359 8.52461 10.7605 5.60246C9.31322
            7.07886 7.2982 7.99666 5.06879 8.00253C4.38902 9.17866 4 10.5439 4
            12C4 16.4183 7.58172 20
            12 20ZM11.9785 4.00003L12.0236 4.00003L12 4L11.9785 4.00003Z"
                fill="currentColor"
                /></svg>';
            $returnstr = '<div class="rui-badge-guest">' . $icon . get_string('loggedinasguest') . '</div>';
            if (!$loginpage && $withlinks) {
                $returnstr .= "<a class=\"text-decoration-none rui-topbar-btn rui-login-btn\"
                    href=\"$loginurl\"><span class=\"rui-login-btn-txt\">" .
                    get_string('login') .
                    '</span>
                <svg class="ml-2"
                    width="20"
                    height="20"
                    fill="none"
                    viewBox="0 0 24 24">
                <path stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M9.75 8.75L13.25 12L9.75 15.25"></path>
                <path stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M9.75 4.75H17.25C18.3546 4.75 19.25 5.64543 19.25
                    6.75V17.25C19.25 18.3546 18.3546 19.25 17.25 19.25H9.75"></path>
                    <path stroke="currentColor"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M13 12H4.75"></path></svg></a>';
            }

            return html_writer::div(
                html_writer::span(
                    $returnstr,
                    'login'
                ),
                $usermenuclasses
            );
        }

        // Get some navigation opts.
        $opts = user_get_user_navigation_info($user, $this->page, array('avatarsize' => 56));

        $avatarclasses = "avatars";
        $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
        $usertextcontents = '<span class="rui-fullname">' . $opts->metadata['userfullname'] . '</span>';
        $usertextmail = $user->email;
        $usernick = '<svg class="mr-1"
            width="16"
            height="16"
            fill="none"
            viewBox="0 0 24 24">
        <path stroke="currentColor"
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M12 13V15"></path>
        <circle cx="12"
            cy="9"
            r="1"
            fill="currentColor"></circle>
        <circle cx="12"
            cy="12"
            r="7.25"
            stroke="currentColor"
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="1.5"></circle>
        </svg>' . $user->username;

        // Other user.
        $usermeta = '';
        if (!empty($opts->metadata['asotheruser'])) {
            $avatarcontents .= html_writer::span(
                $opts->metadata['realuseravatar'],
                'avatar realuser'
            );
            $usermeta .= $opts->metadata['realuserfullname'];
            $usermeta .= html_writer::tag(
                'span',
                get_string(
                    'loggedinas',
                    'moodle',
                    html_writer::span(
                        $opts->metadata['userfullname'],
                        'value'
                    )
                ),
                array('class' => 'meta viewingas')
            );
        }

        // Role.
        if (!empty($opts->metadata['asotherrole'])) {
            $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
            $usermeta .= html_writer::span(
                $opts->metadata['rolename'],
                "meta role role-$role"
            );
        }

        // User login failures.
        if (!empty($opts->metadata['userloginfail'])) {
            $usermeta .= html_writer::div(
                '<svg class="mr-1"
                width="16"
                height="16"
                fill="none"
                viewBox="0 0 24 24"><path stroke="currentColor"
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="1.5"
                d="M4.9522 16.3536L10.2152 5.85658C10.9531 4.38481 13.0539
                4.3852 13.7913 5.85723L19.0495 16.3543C19.7156 17.6841 18.7487
                19.25 17.2613 19.25H6.74007C5.25234
                19.25 4.2854 17.6835 4.9522 16.3536Z">
                </path><path stroke="currentColor"
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M12 10V12"></path>
                <circle cx="12" cy="16" r="1" fill="currentColor"></circle></svg>' .
                    $opts->metadata['userloginfail'],
                'meta loginfailures'
            );
        }

        // MNet.
        if (!empty($opts->metadata['asmnetuser'])) {
            $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
            $usermeta .= html_writer::span(
                $opts->metadata['mnetidprovidername'],
                'meta mnet mnet-' . $mnet
            );
        }

        $returnstr .= html_writer::span(
            html_writer::span($avatarcontents, $avatarclasses),
            'userbutton'
        );

        // Create a divider (well, a filler).
        $divider = new action_menu_filler();
        $divider->primary = false;

        $am = new action_menu();
        $am->set_menu_trigger(
            $returnstr
        );
        $am->set_action_label(get_string('usermenu'));
        $am->set_nowrap_on_items();

        if ($CFG->enabledashboard) {
            $dashboardlink = '<div class="dropdown-item-wrapper"><a class="dropdown-item" href="' .
                new moodle_url('/my/') .
                '" data-identifier="dashboard,moodle" title="dashboard,moodle">' .
                get_string('myhome', 'moodle') .
                '</a></div>';
        } else {
            $dashboardlink = null;
        }

        $am->add(
            '<div class="dropdown-user-wrapper"><div class="dropdown-user">' . $usertextcontents  . '</div>'
                . '<div class="dropdown-user-mail text-truncate" title="' . $usertextmail . '">' . $usertextmail . '</div>'
                . '<span class="dropdown-user-nick w-100">' . $usernick . '</span>'
                . '<div class="dropdown-user-meta"><span class="badge-xs badge-sq badge-warning flex-wrap">' .
                $usermeta . '</span></div>'
                . '</div><div class="dropdown-divider dropdown-divider-user"></div>' . $dashboardlink
        );

        if ($withlinks) {
            $navitemcount = count($opts->navitems);
            $idx = 0;
            foreach ($opts->navitems as $key => $value) {

                switch ($value->itemtype) {
                    case 'divider':
                        // If the nav item is a divider, add one and skip link processing.
                        $am->add($divider);
                        break;

                    case 'invalid':
                        // Silently skip invalid entries (should we post a notification?).
                        break;

                    case 'link':
                        $al = '<a class="dropdown-item" href="' .
                            $value->url .
                            '" data-identifier="' .
                            $value->titleidentifier .
                            '" title="' .
                            $value->titleidentifier .
                            '">' .
                            $value->title . '</a>';
                        $am->add($al);
                        break;
                }

                $idx++;

                // Add dividers after the first item and before the last item.
                if ($idx == 1 || $idx == $navitemcount - 1) {
                    $am->add($divider);
                }
            }
        }

        return html_writer::div(
            $this->render($am),
            $usermenuclasses
        );
    }


    /**
     * Returns standard main content placeholder.
     * Designed to be called in theme layout.php files.
     *
     * @return string HTML fragment.
     */
    public function main_content() {
        // This is here because it is the only place we can inject the "main" role over the entire main content area
        // without requiring all theme's to manually do it, and without creating yet another thing people need to
        // remember in the theme.
        // This is an unfortunate hack. DO NO EVER add anything more here.
        // DO NOT add classes.
        // DO NOT add an id.
        return '<div class="main-content" role="main">' . $this->unique_main_content_token . '</div>';
    }

    /**
     * Outputs a heading
     *
     * @param string $text The text of the heading
     * @param int $level The level of importance of the heading. Defaulting to 2
     * @param string $classes A space-separated list of CSS classes. Defaulting to null
     * @param string $id An optional ID
     * @return string the HTML to output.
     */
    public function heading($text, $level = 2, $classes = null, $id = null) {
        $level = (int) $level;
        if ($level < 1 || $level > 6) {
            throw new coding_exception('Heading level must be an integer between 1 and 6.');
        }
        return html_writer::tag('div', html_writer::tag('h' .
            $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes) .
            ' rui-main-content-title rui-main-content-title--h' .
            $level)), array('class' => 'rui-title-container'));
    }


    public function headingwithavatar($text, $level = 2, $classes = null, $id = null) {
        $level = (int) $level;
        if ($level < 1 || $level > 6) {
            throw new coding_exception('Heading level must be an integer between 1 and 6.');
        }
        return html_writer::tag('div', html_writer::tag('h' .
            $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes) .
            ' rui-main-content-title-with-avatar')), array('class' => 'rui-title-container-with-avatar'));
    }

    /**
     * Renders the login form.
     *
     * @param \core_auth\output\login $form The renderable.
     * @return string
     */
    public function render_login(\core_auth\output\login $form) {
        global $CFG, $SITE;

        $context = $form->export_for_template($this);

        // Override because rendering is not supported in template yet.
        if ($CFG->rememberusername == 0) {
            $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
        } else {
            $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
        }
        $context->errorformatted = $this->error_text($context->error);
        $url = $this->get_logo_url();
        if ($url) {
            $url = $url->out(false);
        }
        $context->logourl = $url;
        $context->sitename = format_string(
            $SITE->fullname,
            true,
            ['context' => context_course::instance(SITEID), "escape" => false]
        );

        $setloginlayout = $this->page->theme->settings->setloginlayout;
        switch ($setloginlayout) {
            case 1:
                $context->loginlayout1 = 1;
                break;
            case 2:
                $context->loginlayout2 = 1;
                if (isset($this->page->theme->settings->loginbg)) {
                    $context->loginlayoutimg = 1;
                }
                break;
            case 3:
                $context->loginlayout3 = 1;
                if (isset($this->page->theme->settings->loginbg)) {
                    $context->loginlayoutimg = 1;
                }
                break;
            case 4:
                $context->loginlayout4 = 1;
                break;
            case 5:
                $context->loginlayout5 = 1;
                break;
        }

        if (isset($this->page->theme->settings->loginlogooutside)) {
            $context->loginlogooutside = $this->page->theme->settings->loginlogooutside;
        }

        if (isset($this->page->theme->settings->customsignupoutside)) {
            $context->customsignupoutside = $this->page->theme->settings->customsignupoutside;
        }

        if (isset($this->page->theme->settings->loginidprovtop)) {
            $context->loginidprovtop = $this->page->theme->settings->loginidprovtop;
        }

        if (isset($this->page->theme->settings->stringca)) {
            $context->stringca = format_text(($this->page->theme->settings->stringca),
                FORMAT_HTML,
                array('noclean' => true)
            );
        }

        if (isset($this->page->theme->settings->stringca)) {
            $context->stringca = format_text(($this->page->theme->settings->stringca),
                FORMAT_HTML,
                array('noclean' => true)
            );
        }

        if (isset($this->page->theme->settings->loginhtmlcontent1)) {
            $context->loginhtmlcontent1 = format_text(($this->page->theme->settings->loginhtmlcontent1),
                FORMAT_HTML,
                array('noclean' => true)
            );
        }

        if (isset($this->page->theme->settings->loginhtmlcontent2)) {
            $context->loginhtmlcontent2 = format_text(($this->page->theme->settings->loginhtmlcontent2),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->loginhtmlcontent3)) {
            $context->loginhtmlcontent3 = format_text(($this->page->theme->settings->loginhtmlcontent3),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->loginhtmlcontent2)) {
            $context->loginhtmlcontent2 = format_text(($this->page->theme->settings->loginhtmlcontent2),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->logincustomfooterhtml)) {
            $context->logincustomfooterhtml = format_text(($this->page->theme->settings->logincustomfooterhtml),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->loginhtmlblockbottom)) {
            $context->loginhtmlblockbottom = format_text(($this->page->theme->settings->loginhtmlblockbottom),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->loginfootercontent)) {
            $context->loginfootercontent = format_text(($this->page->theme->settings->loginfootercontent),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->footercopy)) {
            $context->footercopy = format_text(($this->page->theme->settings->footercopy),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->loginintrotext)) {
            $context->loginintrotext = format_text(($this->page->theme->settings->loginintrotext),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->loginintrotext)) {
            $context->loginintrotext = format_text(($this->page->theme->settings->loginintrotext),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (isset($this->page->theme->settings->customloginlogo)) {
            $context->customloginlogo = $this->page->theme->setting_file_url('customloginlogo', 'customloginlogo');
        }

        if (isset($this->page->theme->settings->loginbg)) {
            $context->loginbg = $this->page->theme->setting_file_url('loginbg', 'loginbg');
        }

        if (isset($this->page->theme->settings->hideforgotpassword)) {
            $context->hideforgotpassword = $this->page->theme->settings->hideforgotpassword == 1;
        }

        if (isset($this->page->theme->settings->logininfobox)) {
            $context->logininfobox = format_text(($this->page->theme->settings->logininfobox),
                FORMAT_HTML,
                array('noclean' => true)
            );
        }

        return $this->render_from_template('core/loginform', $context);
    }

    /**
     * Render the login signup form into a nice template for the theme.
     *
     * @param mform $form
     * @return string
     */
    public function render_login_signup_form($form) {
        global $SITE;

        $context = $form->export_for_template($this);
        $url = $this->get_logo_url();
        if ($url) {
            $url = $url->out(false);
        }
        $context['logourl'] = $url;
        $context['sitename'] = format_string(
            $SITE->fullname,
            true,
            ['context' => context_course::instance(SITEID), "escape" => false]
        );

        $setloginlayout = $this->page->theme->settings->setloginlayout;

        switch ($setloginlayout) {
            case 1:
                $context['loginlayout1'] = 1;
                break;
            case 2:
                $context['loginlayout2'] = 1;
                if (isset($this->page->theme->settings->loginbg)) {
                    $context['loginlayoutimg'] = 1;
                }
                break;
            case 3:
                $context['loginlayout3'] = 1;
                if (isset($this->page->theme->settings->loginbg)) {
                    $context['loginlayoutimg'] = 1;
                }
                break;
            case 4:
                $context['loginlayout4'] = 1;
                break;
            case 5:
                $context['loginlayout5'] = 1;
                break;
        }

        if (isset($this->page->theme->settings->loginlogooutside)) {
            $context['loginlogooutside'] = $this->page->theme->settings->loginlogooutside;
        }

        if (isset($this->page->theme->settings->stringbacktologin)) {
            $context['stringbacktologin'] = format_text(($this->page->theme->settings->stringbacktologin),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }
        if (isset($this->page->theme->settings->signupintrotext)) {
            $context['signupintrotext'] = format_text(($this->page->theme->settings->signupintrotext),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }
        if (isset($this->page->theme->settings->signuptext)) {
            $context['signuptext'] = format_text(($this->page->theme->settings->signuptext),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        if (!empty($this->page->theme->settings->customloginlogo)) {
            $url = $this->page->theme->setting_file_url('customloginlogo', 'customloginlogo');
            $context['customloginlogo'] = $url;
        }

        if (!empty($this->page->theme->settings->loginbg)) {
            $url = $this->page->theme->setting_file_url('loginbg', 'loginbg');
            $context['loginbg'] = $url;
        }

        if (isset($this->page->theme->settings->loginfootercontent)) {
            $context['loginfootercontent'] = format_text(($this->page->theme->settings->loginfootercontent),
                FORMAT_HTML,
                ['noclean' => true]
            );
        }

        return $this->render_from_template('core/signup_form_layout', $context);
    }


    /**
     * Renders the header bar.
     *
     * @param context_header $contextheader Header bar object.
     * @return string HTML for the header bar.
     */
    protected function render_context_header(\context_header $contextheader) {
        $heading = null;
        $imagedata = null;
        $html = null;

        // Generate the heading first and before everything else as we might have to do an early return.
        if (!isset($contextheader->heading)) {
            $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
        } else {
            $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
        }

        // All the html stuff goes here.
        $html = html_writer::start_div('page-context-header d-flex align-items-center flex-wrap');

        // Image data.
        if (isset($contextheader->imagedata)) {
            // Header specific image.
            $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
        }

        // Headings.
        if (isset($contextheader->prefix)) {
            $prefix = html_writer::div($contextheader->prefix, 'text-muted text-uppercase small line-height-3');
            $heading = $prefix . $heading;
        }

        if (!isset($contextheader->heading)) {
            $html .= html_writer::tag('h3', $heading, array('class' => 'rui-page-title rui-page-title--page'));
        } else if (isset($contextheader->imagedata)) {
            $html .= html_writer::tag(
                'div',
                $this->heading($contextheader->heading, 4),
                array('class' => 'rui-page-title rui-page-title--icon')
            );
        } else {
            $html .= html_writer::tag('h2', $heading, array('class' => 'page-header-headings
                rui-page-title rui-page-title--context'));
        }

        // Buttons.
        if (isset($contextheader->additionalbuttons)) {
            $html .= html_writer::start_div('btn-group header-button-group my-2 my-lg-0 ml-lg-4');
            foreach ($contextheader->additionalbuttons as $button) {
                if (!isset($button->page)) {
                    // Include js for messaging.
                    if ($button['buttontype'] === 'togglecontact') {
                        \core_message\helper::togglecontact_requirejs();
                    }
                    if ($button['buttontype'] === 'message') {
                        \core_message\helper::messageuser_requirejs();
                    }
                    $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
                        'class' => 'iconsmall',
                        'role' => 'presentation'
                    ));
                    $image .= html_writer::span($button['title'], 'header-button-title');
                } else {
                    $image = html_writer::empty_tag('img', array(
                        'src' => $button['formattedimage'],
                        'role' => 'presentation'
                    ));
                }
                $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
            }
            $html .= html_writer::end_div();
        }
        $html .= html_writer::end_div();

        return $html;
    }

    public function header() {
        global $USER, $COURSE;
        $theme = theme_config::load('universe');

        $context = context_course::instance($COURSE->id);
        $roles = get_user_roles($context, $USER->id, true);

        if (is_array($roles) && !empty($roles)) {
            foreach ($roles as $role) {
                $this->page->add_body_class('role-' . $role->shortname);
            }
        } else {
            $this->page->add_body_class('role-none');
        }

        if ($theme->settings->topbareditmode == '1') {
            $this->page->add_body_class('rui-editmode--top');
        } else {
            $this->page->add_body_class('rui-editmode--footer');
        }

        return parent::header();
    }


    /**
     * See if this is the first view of the current cm in the session if it has fake blocks.
     *
     * (We track up to 100 cms so as not to overflow the session.)
     * This is done for drawer regions containing fake blocks so we can show blocks automatically.
     *
     * @return boolean true if the page has fakeblocks and this is the first visit.
     */
    public function firstview_fakeblocks(): bool {
        global $SESSION;

        $firstview = false;
        if ($this->page->cm) {
            if (!$this->page->blocks->region_has_fakeblocks('side-pre')) {
                return false;
            }
            if (!property_exists($SESSION, 'firstview_fakeblocks')) {
                $SESSION->firstview_fakeblocks = [];
            }
            if (array_key_exists($this->page->cm->id, $SESSION->firstview_fakeblocks)) {
                $firstview = false;
            } else {
                $SESSION->firstview_fakeblocks[$this->page->cm->id] = true;
                $firstview = true;
                if (count($SESSION->firstview_fakeblocks) > 100) {
                    array_shift($SESSION->firstview_fakeblocks);
                }
            }
        }
        return $firstview;
    }


    /**
     * Build the guest access hint HTML code.
     *
     * @param int $courseid The course ID.
     * @return string.
     */
    public function theme_universe_get_course_guest_access_hint($courseid) {
        global $CFG;
        require_once($CFG->dirroot . '/enrol/self/lib.php');

        $html = '';
        $instances = enrol_get_instances($courseid, true);
        $plugins = enrol_get_plugins(true);
        foreach ($instances as $instance) {
            if (!isset($plugins[$instance->enrol])) {
                continue;
            }
            $plugin = $plugins[$instance->enrol];
            if ($plugin->show_enrolme_link($instance)) {
                $html = html_writer::tag('div', get_string(
                    'showhintcourseguestaccesssettinglink',
                    'theme_universe',
                    array('url' => $CFG->wwwroot . '/enrol/index.php?id=' . $courseid)
                ));
                break;
            }
        }

        return $html;
    }


    /**
     * Color Customization
     * @return string HTML fragment.
     */
    public function additional_head_html() {
        global $SITE, $DB, $CFG, $COURSE, $PAGE;
        $output = null;
        if ($PAGE->pagelayout == 'course' || $PAGE->pagelayout == 'incourse') {
            $customfieldid1 = $DB->get_record('customfield_field', array('shortname' => 'maincolor1'));
            $mainthemecolor = $customfieldid1 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid1->id, 'instanceid' => $COURSE->id)) : null;
            $customfieldid2 = $DB->get_record('customfield_field', array('shortname' => 'maincolor2'));
            // $mainthemecolor2 = $customfieldid2 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid2->id, 'instanceid' => $COURSE->id)) : null;
            $customfieldid3 = $DB->get_record('customfield_field', array('shortname' => 'topbarcolor'));
            $topbarcolor = $customfieldid3 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid3->id, 'instanceid' => $COURSE->id)) : null;
            $customfieldid4 = $DB->get_record('customfield_field', array('shortname' => 'dmtopbarcolor'));
            $dmtopbarcolor = $customfieldid4 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid4->id, 'instanceid' => $COURSE->id)) : null;
            // $customfieldid5 = $DB->get_record('customfield_field', array('shortname' => 'colortopbartext'));
            // $colortopbartext = $customfieldid5 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid5->id, 'instanceid' => $COURSE->id)) : null;

            $customfieldid6 = $DB->get_record('customfield_field', array('shortname' => 'footertextcolor'));
            $footertextcolor = $customfieldid6 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid6->id, 'instanceid' => $COURSE->id)) : null;

            $customfieldid7 = $DB->get_record('customfield_field', array('shortname' => 'footerbgcolor'));
            $footercolor = $customfieldid7 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid7->id, 'instanceid' => $COURSE->id)) : null;

            $customfieldid8 = $DB->get_record('customfield_field', array('shortname' => 'topbarcolor2'));
            $topbarcolor2 = $customfieldid8 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid8->id, 'instanceid' => $COURSE->id)) : null;

            $customfieldid9 = $DB->get_record('customfield_field', array('shortname' => 'dmtopbarcolor2'));
            $dmtopbarcolor2 = $customfieldid9 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid9->id, 'instanceid' => $COURSE->id)) : null;

            $customfieldid10 = $DB->get_record('customfield_field', array('shortname' => 'topbartextcolor'));
            $topbartextcolor = $customfieldid10 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid10->id, 'instanceid' => $COURSE->id)) : null;
            $customfieldid11 = $DB->get_record('customfield_field', array('shortname' => 'topbartexthovercolor'));
            $topbartexthovercolor = $customfieldid11 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid11->id, 'instanceid' => $COURSE->id)) : null;
            $customfieldid12 = $DB->get_record('customfield_field', array('shortname' => 'topbarbghovercolor'));
            $topbarbghovercolor = $customfieldid12 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid12->id, 'instanceid' => $COURSE->id)) : null;

            $customfieldid13 = $DB->get_record('customfield_field', array('shortname' => 'dmtopbartextcolor'));
            $dmtopbartextcolor = $customfieldid13 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid13->id, 'instanceid' => $COURSE->id)) : null;
            $customfieldid14 = $DB->get_record('customfield_field', array('shortname' => 'dmtopbartexthovercolor'));
            $dmtopbartexthovercolor = $customfieldid14 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid14->id, 'instanceid' => $COURSE->id)) : null;
            $customfieldid15 = $DB->get_record('customfield_field', array('shortname' => 'dmtopbarbghovercolor'));
            $dmtopbarbghovercolor = $customfieldid15 ? $DB->get_record('customfield_data', array('fieldid' => $customfieldid15->id, 'instanceid' => $COURSE->id)) : null;


            $css = ':root { ';
            if ($mainthemecolor && !empty($mainthemecolor->value)) {
                $css .= '--main-theme-color: ' . $mainthemecolor->value . '; ';
                $css .= '--primary-color-100: ' . \theme_universe\toolbox::tint($mainthemecolor->value, .1) . '; ';
                $css .= '--primary-color-200: ' . \theme_universe\toolbox::tint($mainthemecolor->value, .2) . '; ';
                $css .= '--primary-color-300: ' . \theme_universe\toolbox::tint($mainthemecolor->value, .3) . '; ';
                $css .= '--primary-color-400: ' . \theme_universe\toolbox::tint($mainthemecolor->value, .4) . '; ';
                $css .= '--primary-color-500: ' . \theme_universe\toolbox::tint($mainthemecolor->value, .5) . '; ';
                $css .= '--primary-color-700: ' . \theme_universe\toolbox::shade($mainthemecolor->value, .5) . '; ';
                $css .= '--primary-color-800: ' . \theme_universe\toolbox::shade($mainthemecolor->value, .3) . '; ';
                $css .= '--primary-color-900: ' . \theme_universe\toolbox::shade($mainthemecolor->value, .1) . '; ';
                //$css .= '--main-theme-color-gradient: ' . $mainthemecolor->value . '; ';
                $css .= '--btn-primary-color-bg: ' . $mainthemecolor->value . '; ';
                $css .= '--btn-primary-color-bg-hover: ' . \theme_universe\toolbox::shade($mainthemecolor->value, .5) . '; ';
                //$css .= '--main-theme-color-gradient-2: ' . ($mainthemecolor2 && !empty($mainthemecolor2->value) ? $mainthemecolor2->value :  \theme_universe\toolbox::shade($mainthemecolor->value, .3)) . '; ';
            }

            if ($topbarcolor && !empty($topbarcolor->value)) {
                $css .= '--topbar-color: ' . $topbarcolor->value . '; ';
                $css .= '--dm-topbar-color: ' . ($dmtopbarcolor && !empty($dmtopbarcolor->value) ? $dmtopbarcolor->value : $dmtopbarcolor->value) . '; ';
            }

            if ($topbarcolor2 && !empty($topbarcolor2->value)) {
                $css .= '--topbar-color-2: ' . $topbarcolor2->value . '; ';
            }

            if ($dmtopbarcolor2 && !empty($dmtopbarcolor2->value)) {
                $css .= '--dm-topbar-color-2: ' . ($dmtopbarcolor2 && !empty($dmtopbarcolor2->value) ? $dmtopbarcolor2->value : $dmtopbarcolor2->value) . '; ';
            }

            if ($topbartextcolor && !empty($topbartextcolor->value)) {
                $css .= '--topbar-btn-text: ' . ($topbartextcolor && !empty($topbartextcolor->value) ? $topbartextcolor->value : $topbartextcolor->value) . '; ';
            }

            if ($topbarbghovercolor && !empty($topbarbghovercolor->value)) {
                $css .= '--topbar-btn-hover: ' . ($topbarbghovercolor && !empty($topbarbghovercolor->value) ? $topbarbghovercolor->value : $topbarbghovercolor->value) . '; ';
            }

            if ($topbartexthovercolor && !empty($topbartexthovercolor->value)) {
                $css .= '--topbar-btn-hover-text: ' . ($topbartexthovercolor && !empty($topbartexthovercolor->value) ? $topbartexthovercolor->value : $topbartexthovercolor->value) . '; ';
            }

            if ($dmtopbartextcolor && !empty($dmtopbartextcolor->value)) {
                $css .= '--dm-topbar-btn-text: ' . ($dmtopbartextcolor && !empty($dmtopbartextcolor->value) ? $dmtopbartextcolor->value : $dmtopbartextcolor->value) . '; ';
            }

            if ($dmtopbarbghovercolor && !empty($dmtopbarbghovercolor->value)) {
                $css .= '--dm-topbar-btn-hover: ' . ($dmtopbarbghovercolor && !empty($dmtopbarbghovercolor->value) ? $dmtopbarbghovercolor->value : $dmtopbarbghovercolor->value) . '; ';
            }

            if ($dmtopbartexthovercolor && !empty($dmtopbartexthovercolor->value)) {
                $css .= '--dm-topbar-btn-hover-text: ' . ($dmtopbartexthovercolor && !empty($dmtopbartexthovercolor->value) ? $dmtopbartexthovercolor->value : $dmtopbartexthovercolor->value) . '; ';
            }

            if ($footercolor && !empty($footercolor->value)) {
                $css .= '--footer-color: ' . $footercolor->value . '; ';
            }

            if ($footertextcolor && !empty($footertextcolor->value)) {
                $css .= '--footer-text-color: ' . $footertextcolor->value . '; ';
            }

            $css .= '}';
            if ($css) {
                $output .= '<style>' . $css . '</style>';
            }
        }
        return $output;
    }

    public function custom_course_logo() {
        global $DB, $CFG, $COURSE, $PAGE;

        $output = null;

        if ($PAGE->pagelayout == 'course' || $PAGE->pagelayout == 'incourse') {
            if ($DB->record_exists('customfield_field', array('shortname' => 'customcourselogo'))) {
                // Get custom field ID
                $customfieldpic = $DB->get_record('customfield_field', array('shortname' => 'customcourselogo'));
                $customfieldpicid = $customfieldpic->id;
                // Get value
                $customlogo = $DB->get_record(
                    'customfield_data',
                    array('fieldid' => $customfieldpicid, 'instanceid' => $COURSE->id)
                );

                $customlogoid = $customlogo->id;
                $contextid = $customlogo->contextid;

                if ($customfieldpic != null) {
                    $files = get_file_storage()->get_area_files(
                        $contextid,
                        'customfield_picture',
                        'file',
                        $customlogoid,
                        '',
                        false
                    );

                    if (empty($files)) {
                        return null;
                    }

                    $file = reset($files);
                    $fileurl = moodle_url::make_pluginfile_url(
                        $file->get_contextid(),
                        $file->get_component(),
                        $file->get_filearea(),
                        $file->get_itemid(),
                        $file->get_filepath(),
                        $file->get_filename()
                    );

                    $output .= $fileurl;
                }
            }
        }

        return $output;
    }

    public function custom_course_dmlogo() {
        global $DB, $CFG, $COURSE, $PAGE;

        $output = null;

        if ($PAGE->pagelayout == 'course' || $PAGE->pagelayout == 'incourse') {
            if ($DB->record_exists('customfield_field', array('shortname' => 'customcoursedmlogo'))) {
                // Get custom field ID
                $customfieldpic = $DB->get_record('customfield_field', array('shortname' => 'customcoursedmlogo'));
                $customfieldpicid = $customfieldpic->id;
                // Get value
                $customlogo = $DB->get_record(
                    'customfield_data',
                    array('fieldid' => $customfieldpicid, 'instanceid' => $COURSE->id)
                );

                $customlogoid = $customlogo->id;
                $contextid = $customlogo->contextid;

                if ($customfieldpic != null) {
                    $files = get_file_storage()->get_area_files(
                        $contextid,
                        'customfield_picture',
                        'file',
                        $customlogoid,
                        '',
                        false
                    );

                    if (empty($files)) {
                        return null;
                    }

                    $file = reset($files);
                    $fileurl = moodle_url::make_pluginfile_url(
                        $file->get_contextid(),
                        $file->get_component(),
                        $file->get_filearea(),
                        $file->get_itemid(),
                        $file->get_filepath(),
                        $file->get_filename()
                    );

                    $output .= $fileurl;
                }
            }
            return $output;
        }
    }

    public function custom_course_favicon() {
        global $DB, $CFG, $COURSE, $PAGE;

        $output = null;

        if ($PAGE->pagelayout == 'course' || $PAGE->pagelayout == 'incourse') {
            if ($DB->record_exists('customfield_field', array('shortname' => 'customcoursefavicon'))) {
                // Get custom field ID
                $customfieldpic = $DB->get_record('customfield_field', array('shortname' => 'customcoursefavicon'));
                $customfieldpicid = $customfieldpic->id;
                // Get value
                $customfavicon = $DB->get_record(
                    'customfield_data',
                    array('fieldid' => $customfieldpicid, 'instanceid' => $COURSE->id)
                );

                $customfaviconid = $customfavicon->id;
                $contextid = $customfavicon->contextid;

                if ($customfieldpic != null) {
                    $files = get_file_storage()->get_area_files(
                        $contextid,
                        'customfield_picture',
                        'file',
                        $customfaviconid,
                        '',
                        false
                    );

                    if (empty($files)) {
                        return null;
                    }

                    $file = reset($files);
                    $fileurl = moodle_url::make_pluginfile_url(
                        $file->get_contextid(),
                        $file->get_component(),
                        $file->get_filearea(),
                        $file->get_itemid(),
                        $file->get_filepath(),
                        $file->get_filename()
                    );

                    $output .= $fileurl;
                }
            }
        }

        return $output;
    }

    public function custom_course_name() {
        global $DB, $CFG, $COURSE, $PAGE;

        $output = null;

        if ($PAGE->pagelayout == 'course' || $PAGE->pagelayout == 'incourse') {
            if ($DB->record_exists('customfield_field', array('shortname' => 'customcoursename'), 'id')) {
                // Get custom field by name
                $customfieldid = $DB->get_record('customfield_field', array('shortname' => 'customcoursename'));
                // Get value
                $customcoursename = $DB->get_record('customfield_data', array('fieldid' => $customfieldid->id, 'instanceid' => $COURSE->id));
                if (!empty($customcoursename)) {
                    $output .= $customcoursename->value;
                }
            } else {
                $customcoursename = null;
            }
        }

        return $output;
    }

    /**
     * Get the course pattern datauri to show on a course card.
     *
     * The datauri is an encoded svg that can be passed as a url.
     * @param int $id Id to use when generating the pattern
     * @return string datauri
     */
    public function get_generated_image_for_id($id) {
        global $CFG;

        $theme = \theme_config::load('universe');
        // Add custom course cover.
        $customcover = $theme->setting_file_url('defaultcourseimg', 'defaultcourseimg');

        if (!empty(($customcover))) {
            $urlreplace = preg_replace('|^https?://|i', '//', $CFG->wwwroot);
            $customcover = str_replace($urlreplace, '', $customcover);
            $txt = new moodle_url($customcover);
            return strval($txt);
        } else {
            $color = $this->get_generated_color_for_id($id);
            $pattern = new \core_geopattern();
            $pattern->setColor($color);
            $pattern->patternbyid($id);
            return $pattern->datauri();
        }
    }

    public function moremenu_group_item() {
        global $CFG, $COURSE;

        $courseid = $COURSE->id;
        $sitehomeurl = new moodle_url('/');

        if ($this->page->theme->settings->secnavgroupitem == 1) {
            if (has_capability('moodle/course:managegroups', \context_course::instance($COURSE->id))) {
                $html = $sitehomeurl . "group/index.php?id=" . $courseid;
                return $html;
            }
        }
    }

    public function moremenu_custom_items() {
        global $CFG, $COURSE, $USER;

        $html = '';
        $secnavcount = theme_universe_get_setting('secnavitemscount');

        // Get user role ID.
        $context = context_course::instance($COURSE->id);
        $roles = get_user_roles($context, $USER->id, true);
        $role = key($roles);
        if ($role != null) {
            $roleid = $roles[$role]->id;
        } else {
            $roleid = 99;
        }
        // End.

        if ($this->page->theme->settings->secnavitems == 1) {

            $secnav = new stdClass();
            for ($i = 1; $i <= $secnavcount; $i++) {
                $secnav->title = theme_universe_get_setting("secnavcustomnavlabel" . $i);

                $url = theme_universe_get_setting("secnavcustomnavurl" . $i);
                $courseid = $COURSE->id;
                $newurl = str_replace("{{courseID}}", $courseid, $url);
                $secnav->url = $newurl;

                // User role restriction.
                $selectrole = theme_universe_get_setting("secnavuserrole" . $i);

                if ($selectrole == 1) {
                    if ($roleid == 1 || $roleid == 2 || $roleid == 3 || $roleid == 4) {
                        $secnav->isadmin = true;
                        $secnav->nonrestriction = false;
                    }
                } else {
                    $secnav->isadmin = false;
                    $secnav->nonrestriction = true;
                }
                // End.

                $html .= $this->render_from_template('theme_universe/custom_sec_nav_item', $secnav);
            }
        }
        return $html;
    }

    /**
     *  Display only fields dedicated to enrollment page
     */
    public function get_enrollfields() {
        global $COURSE;
        $course = get_course($COURSE->id);

        $courseelement = new \core_course_list_element($course);

        if ($courseelement->has_custom_fields()) {
            $fields = $courseelement->get_custom_fields();
            $content = '';

            foreach ($fields as $field) {
                if (empty($field->get_value())) {
                    continue;
                }

                // Get field shortname
                $customfieldname = $field->get_field()->get('name');
                $customfieldvalue = $field->get_value();
                $customfieldshortname =  $field->get_field()->get('shortname');

                // Array with custom fields which need to be hidden.
                $hiddencustomfields = array("enrolldesc", "enrollvideo");
                $hiddencftitles = array("tool_courserating");

                if (in_array($customfieldshortname, $hiddencustomfields)) {
                    $content .= html_writer::start_tag('div', array('class' => 'rui-custom-field-box'));
                    $content .= html_writer::tag('div', $customfieldvalue, array('class' => 'rui-custom-field-value'));
                    $content .= html_writer::end_tag('div');
                }
            }
            return $content;
        } else {
            return false;
        }
    }

    public function show_course_filter() {
        global $CFG;

        $showcoursefilter = $this->page->theme->settings->showcoursefilter;

        $siteurl = $CFG->wwwroot;
        $currentUrl = $this->page->url->out(false);
        $compareString = $siteurl . '/course/index.php';

        // Check if the current URL starts with the compare string
        if (strpos($currentUrl, $compareString) === 0 && $showcoursefilter == 1) {
            // Now, check if the length of the current URL is exactly the same as the compare string
            if (strlen($currentUrl) == strlen($compareString)) {
                // The current URL matches 'course/index.php'.
                return false;
            } else {
                // The current URL matches 'course/index.php' but has additional content appended.
                return true;
            }
        } else {
            // The current URL does not match 'course/index.php'.
            return true;
        }
    }

    /**
     * 
     * Returns list of languages.
     * 
     */
    public function course_lang_list() {
        $langs = get_string_manager()->get_list_of_translations();

        $output = '';

        foreach ((array)$langs as $langtype => $langname) {
            $total = html_writer::empty_tag('span', array('class' => 'total'));
            $output .= html_writer::div($langname . $total, 'filtering-filter', array('data-filter-name' => $langtype));
        }

        return $output;
    }



    /**
     * 
     * Returns list of teachers.
     *
     */
    function course_teachers_list() {
        global $DB, $CFG, $COURSE;

        $output = null;

        $uniqueTeachers = [];

        // Get the current page URL.
        //$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $currentURL = $_SERVER['REQUEST_URI'];
        // Parse the URL and extract the query string.
        $query_str = parse_url($currentURL, PHP_URL_QUERY);
        // Parse the query string into an associative array.
        parse_str($query_str, $query_params);
        // Get the category ID.
        $categoryid = $query_params['categoryid'] ?? 'Category ID not found';
        // End - Get the current page URL.

        // Fetch the course details
        $courses = $DB->get_records('course', ['category' => $categoryid]);

        // Iterate over each course
        foreach ($courses as $course) {
            // Get context of the current course
            $context = context_course::instance($course->id);

            // Get all users with the teacher role in the current course
            $teachers = get_role_users(3, $context) + get_role_users(4, $context); // Teacher role ID is 3 and 4, adjust if necessary

            if (isset($teachers) && is_array($teachers)) {
                // Iterate through the list of teachers for the current course
                foreach ($teachers as $teacher) {
                    // Check if the teacher ID already exists in the uniqueTeachers array
                    if (!isset($uniqueTeachers[$teacher->id])) {
                        // If the teacher ID does not exist, add it to the uniqueTeachers array
                        $uniqueTeachers[$teacher->id] = $teacher;
                    }
                }
            } else {
                $uniqueTeachers = null;
            }
        }

        if (!empty($uniqueTeachers)) {
            // Output the list of unique teachers
            foreach ($uniqueTeachers as $teacher) {
                $total = html_writer::empty_tag('span', ['class' => 'total']);
                $teachername = "{$teacher->firstname} {$teacher->lastname}";
                $output .= html_writer::div("$teachername$total", 'filtering-filter', ['data-filter-name' => $teachername]);
            }

            return $output;
        }
    }

    /**
     * 
     * Returns custom filter list based on parameters.
     *
     * @param string $filterNameSetting The name of the filter setting.
     * @param string $filterShowSetting The show filter setting.
     * @return string The HTML output for the filter list.
     */
    function get_course_customfilter_list($filterNameSetting, $filterShowSetting) {
        global $DB, $COURSE;

        // Theme Settings.
        $coursefilteron = $this->page->theme->settings->$filterShowSetting;
        $customfiltername = $this->page->theme->settings->$filterNameSetting;

        if ($coursefilteron == 1 && $customfiltername != null) {
            // Variables.
            $fieldsarr = [];
            $uniqueFields = [];
            $filtertitle = '';
            $record = $DB->get_record('customfield_field', ['shortname' => $customfiltername]);

            // Get the current page URL.
            //$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $currentURL = $_SERVER['REQUEST_URI'];
            // Parse the URL and extract the query string.
            $query_str = parse_url($currentURL, PHP_URL_QUERY);
            // Parse the query string into an associative array.
            parse_str($query_str, $query_params);
            // Get the category ID.
            $categoryid = $query_params['categoryid'] ?? 'Category ID not found';
            // End - Get the current page URL.

            // Fetch the course details.
            $courses = $DB->get_records('course', ['category' => $categoryid]);

            // Iterate over each course.
            foreach ($courses as $course) {
                // Get custom fields.
                $courseelement = new core_course_list_element($course);
                $fields = $courseelement->get_custom_fields();

                foreach ($fields as $field) {
                    if (empty($field->get_value())) {
                        continue;
                    }

                    $customfieldshortname = $field->get_field()->get('shortname');
                    $customfieldtype = $field->get_field()->get('type');

                    if ($customfieldshortname == $customfiltername) {
                        if (str_contains($field->get_value(), ',')) {
                            $itemsArray = explode(",", $field->get_value());
                            foreach ($itemsArray as $item) {
                                $uniqueFields[$item] = $item;
                            }
                        }
                        if($customfieldtype === 'select') {

                            //$fieldid = $DB->get_record('customfield_field', ['id' => $record->fieldid]);
                            $jsonString = $record->configdata;
                                    
                            // Decode JSON string into a PHP associative array
                            $array = json_decode($jsonString, true);
                            // Check if decoding was successful
                            if (json_last_error() === JSON_ERROR_NONE) {
                                // Access the 'options' key
                                $options = $array['options'];
                            } else {
                                // Handle JSON decoding error
                                echo "Error decoding JSON: " . json_last_error_msg();
                            }
                            $optionsArray = explode("\r\n", $options);
                            $temp = $field->get_value() - 1;
                            if($temp >= 0) {
                                $uniqueFields[$field->get_value()] = $optionsArray[$temp];
                            }
                        } else {
                            $uniqueFields[$field->get_value()] = $field->get_value();
                        }

                    }
                }
            }

            // Filter - List.
            if ($record != null) {
                // Output the list of unique fields.
                foreach ($uniqueFields as $field) {
                    $fieldsarr[] = format_string($field);
                }

                // Filter - Title.
                $filtertitle = $record->name;
            }

            $filtergroupno = $customfiltername;

            // Filter - Template.
            $coursefilter = new stdClass();
            $coursefilter->shortname = $customfiltername;
            $coursefilter->filtergroupno = format_string($filtergroupno);
            $coursefilter->title = format_string($filtertitle);
            $coursefilter->item = $fieldsarr;

            return $this->render_from_template('theme_universe/course_filter_item', $coursefilter);
        }
    }

    /**
     * 
     * Returns list #1.
     *
     */
    public function course_customfilter1_list() {
        return $this->get_course_customfilter_list('customfilter1', 'showfilter1', 'customfilter1');
    }

    /**
     * 
     * Returns list #2.
     *
     */
    public function course_customfilter2_list() {
        return $this->get_course_customfilter_list('customfilter2', 'showfilter2', 'customfilter2');
    }

    /**
     * 
     * Returns list #3.
     *
     */
    public function course_customfilter3_list() {
        return $this->get_course_customfilter_list('customfilter3', 'showfilter3', 'customfilter3');
    }

    /**
     * 
     * Returns list #4.
     *
     */
    public function course_customfilter4_list() {
        return $this->get_course_customfilter_list('customfilter4', 'showfilter4', 'customfilter4');
    }

    /**
     * 
     * Returns list #5.
     *
     */
    public function course_customfilter5_list() {
        return $this->get_course_customfilter_list('customfilter5', 'showfilter5', 'customfilter5');
    }

    /**
     * 
     * Returns list #6.
     *
     */
    public function course_customfilter6_list() {
        return $this->get_course_customfilter_list('customfilter6', 'showfilter6', 'customfilter6');
    }
}
