<?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/>.

/**
 * Parent theme: boost
 *
 * @package   theme_edmo
 * @copyright EnvyTheme
 *
 */

namespace theme_edmo\output;

defined('MOODLE_INTERNAL') || die;

use html_writer;
use custom_menu;
use action_menu_filler;
use action_menu_link_secondary;
use stdClass;
use moodle_url;
use action_menu;
use pix_icon;
use theme_config;
use core_text;
use help_icon;
use context_system;
use core_course_list_element;
use context_course;

/**
 * Renderers to align Moodle's HTML with that expected by Bootstrap
 *
 * @package    theme_edmo
 * @copyright  2021 EnvyTheme
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class core_renderer extends \core_renderer {

    /**
     * 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/custom_menu_item', $context);
        }

        return $content;
    }

    /**
     * Renders the lang menu
     *
     * @return mixed
     */
    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);
            }

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

    /**
     * Gets the logo to be rendered.
     *
     * The priority of get log is: 1st try to get the theme logo, 2st try to get the theme logo
     * If no logo was found return false
     *
     * @return mixed
     */
    public function get_logo() {
        if ($this->should_display_theme_logo()) {
            return $this->get_theme_logo_url();
        }

        $url = $this->get_logo_url();
        if ($url) {
            return $url->out(false);
        }

        return false;
    }

    /**
     * Whether we should display the main theme logo in the navbar.
     *
     * @return bool
     */
    public function should_display_theme_logo() {
        $logo = $this->get_theme_logo_url();

        return !empty($logo);
    }

    /**
     * Get the main logo URL.
     *
     * @return string
     */
    public function get_theme_logo_url() {
        $theme = theme_config::load('edmo');

        return $theme->setting_file_url('logo', 'logo');
    }

    /**
     * Get the footer logo URL.
     *
     * @return string
     */
    public function get_footer_logo() {
        $theme = theme_config::load('edmo');

        return $theme->setting_file_url('footer_logo', 'footer_logo');
    }

    /**
     * Get the footer description
     *
     * @return string
     */
    public function get_footer_desc() {
        $footer_desc = '';
        $footer_desc = theme_edmo_get_setting('footer_desc', true);

        return $footer_desc;
    }

    /**
     * if blog page
     *
     * @return string
     */
    public function if_blog() {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        if ( strpos($actual_link, '/blog') != false ):
            return true;
        endif;
    }

    /**
     * if course page
     *
     * @return string
     */
    public function if_course() {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        if ( strpos($actual_link, 'index.php?categoryid') != false ):
            return true;
        endif;
    }

    /**
     * if home pages
     *
     * @return string
     */
    public function if_home_pages() {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        if ( strpos($actual_link, 'mod/page/view.php?id=48') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=49') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=50') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=51') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=52') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=53') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=54') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=55') != false ):
            return true;
        endif;

        if ( strpos($actual_link, 'mod/page/view.php?id=56') != false ):
            return true;
        endif;
        if ( strpos($actual_link, 'mod/page/view.php?id=57') != false ):
            return true;
        endif;
    }

    /**
     * if course details
     *
     * @return string
     */
    public function if_single_course() {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        if ( strpos($actual_link, '/course/view.php?id=') != false ):
            return true;
        endif;
    }

    /**
     * if user enrolled
     *
     * @return string
     */
    public function edmo_if_user_enrolled() {

        global $USER;
        global $course;

        $courseid = $course->id;
        $userid = $USER->id;

        $context = context_course::instance($courseid);
        if(is_enrolled($context, $userid, '', true) == true):
            return false;
        else:
            return true;
        endif;

    }

    /**
     * enrol link
     *
     * @return string
     */
    public function edmo_enroll_link() {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $id = $_GET['id'];
        global $CFG;
        return $CFG->wwwroot . "/enrol/index.php?id=$id";
    }

    /**
     * course overview
     *
     * @return string
     */
    public function course_overview() {
        global $DB;
        global $course;
        $result = $DB->get_field("course", "summary", array("id"=>$course->id));
        $html = '';
        $html .= $result;

        return $html;
    }

    /**
     * Get the footer social links
     *
     */
    public function get_social_links() {
        $facebook   = '';
        $facebook   = theme_edmo_get_setting('facebook', true);
        $twitter    = '';
        $twitter    = theme_edmo_get_setting('twitter', true);
        $linkedin   = '';
        $linkedin   = theme_edmo_get_setting('linkedin', true);
        $youtube    = '';
        $youtube    = theme_edmo_get_setting('youtube', true);
        $instagram  = '';
        $instagram  = theme_edmo_get_setting('instagram', true);
        $whatsapp   = '';
        $whatsapp   = theme_edmo_get_setting('whatsapp', true);

        $output = '';

        $output .='
            <ul class="social-link">';
                if($facebook):
                    $output .='
                    <li><a href="'.$facebook.'" class="d-block" target="_blank"><i class="bx bxl-facebook"></i></a></li>';
                endif;
                if($twitter):
                    $output .='
                    <li><a href="'.$twitter.'" class="d-block" target="_blank"><i class="bx bxl-twitter"></i></a></li>';
                endif;
                if($linkedin):
                    $output .='
                    <li><a href="'.$linkedin.'" class="d-block" target="_blank"><i class="bx bxl-linkedin"></i></a></li>';
                endif;
                if($youtube):
                    $output .='
                    <li><a href="'.$youtube.'" class="d-block" target="_blank"><i class="bx bxl-youtube"></i></a></li>';
                endif;
                if($instagram):
                    $output .='
                    <li><a href="'.$instagram.'" class="d-block" target="_blank"><i class="bx bxl-instagram"></i></a></li>';
                endif;
                if($whatsapp):
                    $output .='
                    <li><a href="'.$whatsapp.'" class="d-block" target="_blank"><i class="bx bxl-whatsapp"></i></a></li>';
                endif;
                $output .='
            </ul>
        ';
        return $output;
    }

    /**
     * Get the footer info
     *
     */
    public function get_footer_info() {
        $footer_info1       = '';
        $footer_info1       = theme_edmo_get_setting('footer_info1', true);
        $footer_info1_desc  = '';
        $footer_info1_desc  = theme_edmo_get_setting('footer_info1_desc', 'format_html');
        $footer_info2       = '';
        $footer_info2       = theme_edmo_get_setting('footer_info2', true);
        $footer_info2_desc  = '';
        $footer_info2_desc  = theme_edmo_get_setting('footer_info2_desc', 'format_html');
        $footer_info3       = '';
        $footer_info3       = theme_edmo_get_setting('footer_info3', true);
        $footer_info3_desc  = '';
        $footer_info3_desc  = theme_edmo_get_setting('footer_info3_desc', 'format_html');

        ob_start();
        ?>
            <div class='col-lg-2 col-md-6 col-sm-6'>
                <div class='single-footer-widget pl-5'>
                    <?php if($footer_info1): ?>
                        <h3><?php echo $footer_info1; ?></h3>
                    <?php endif; ?>

                    <?php if($footer_info1_desc): ?>
                        <ul class='footer-links-list'>
                            <?php echo $footer_info1_desc; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>

            <div class='col-lg-2 col-md-6 col-sm-6'>
                <div class='single-footer-widget'>
                    <?php if($footer_info2): ?>
                        <h3><?php echo $footer_info2; ?></h3>
                    <?php endif; ?>

                    <?php if($footer_info2_desc): ?>
                        <ul class='footer-links-list'>
                            <?php echo $footer_info2_desc; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>

            <div class='col-lg-4 col-md-6 col-sm-6'>
                <div class='single-footer-widget'>
                    <?php if($footer_info3): ?>
                        <h3><?php echo $footer_info3; ?></h3>
                    <?php endif; ?>

                    <?php if($footer_info3_desc): ?>
                        <ul class='footer-contact-info'>
                            <?php echo $footer_info3_desc; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        <?php
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }

    /**
     * Get the footer bottom
     *
     */
    public function get_footer_bottom() {
        $footer_copyright       = '';
        $footer_copyright       = theme_edmo_get_setting('footer_copyright',  'format_html');
        $footer_menu            = '';
        $footer_menu            = theme_edmo_get_setting('footer_menu',  'format_html');
        ob_start();
        ?>
            <div class="footer-bottom-area">
                <div class="row align-items-center">
                    <div class="col-lg-6 col-md-6">
                        <p><?php echo $footer_copyright; ?></p>
                    </div>

                    <div class="col-lg-6 col-md-6">
                        <ul>
                            <?php echo $footer_menu; ?>
                        </ul>
                    </div>
                </div>
            </div>
        <?php
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }

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

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

    /**
     * Returns the moodle_url for the favicon.
     *
     * @since Moodle 2.5.1 2.6
     * @return moodle_url The moodle_url for the favicon
     */
    public function favicon() {
        global $CFG;

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

        $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();
    }
    /**
     * Secure login info.
     *
     * @return string
     */
    public function secure_login_info() {
        return $this->login_info(false);
    }

    /**
     * Returns a search box.
     */
    public function search_box($id = false) {
        global $CFG;
        $search_placeholder = '';
        $search_placeholder = theme_edmo_get_setting('search_placeholder', true);
        $wwwroot = $CFG->wwwroot;

        return '
            <form class="search-box search-input-form" method="get" action="'.$wwwroot.'/search/index.php">
                <input type="text" class="input-search" name="q" placeholder="Búsqueda">
                <button type="submit"><i class="flaticon-search"></i></button>
            </form>';
    }


    /**
     * 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='default-btn' href=\"$loginurl\"><i class='flaticon-user'></i>".get_string('login').'<span></span></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()) {
            $returnstr = get_string('loggedinasguest');
            if (!$loginpage && $withlinks) {
                $returnstr .= " <a class='default-btn gest-user-btn' href=\"$loginurl\"><i class='flaticon-user'></i>".get_string('login').'<span></span></a>';
            }

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

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

        $avatarclasses = "avatars";
        $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
        $usertextcontents = $opts->metadata['userfullname'];

        // Other user.
        if (!empty($opts->metadata['asotheruser'])) {
            $avatarcontents .= html_writer::span(
                $opts->metadata['realuseravatar'],
                'avatar realuser'
            );
            $usertextcontents = $opts->metadata['realuserfullname'];
            $usertextcontents .= 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'])));
            $usertextcontents .= html_writer::span(
                $opts->metadata['rolename'],
                'meta role role-' . $role
            );
        }

        // User login failures.
        if (!empty($opts->metadata['userloginfail'])) {
            $usertextcontents .= html_writer::span(
                $opts->metadata['userloginfail'],
                'meta loginfailures'
            );
        }

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

        $returnstr .= html_writer::span(
            html_writer::span($usertextcontents, 'usertext mr-1') .
            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_alignment(action_menu::TR, action_menu::BR);
        $am->set_nowrap_on_items();
        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':
                        // Process this as a link item.
                        $pix = null;
                        if (isset($value->pix) && !empty($value->pix)) {
                            $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
                        } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
                            $value->title = html_writer::img(
                                $value->imgsrc,
                                $value->title,
                                array('class' => 'iconsmall')
                            ) . $value->title;
                        }

                        $al = new action_menu_link_secondary(
                            $value->url,
                            $pix,
                            $value->title,
                            array('class' => 'icon')
                        );
                        if (!empty($value->titleidentifier)) {
                            $al->attributes['data-title'] = $value->titleidentifier;
                        }
                        $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
        );
    }

    /**
     * Implementation of user image rendering.
     *
     * @param help_icon $helpicon A help icon instance
     * @return string HTML fragment
     */
    public function render_help_icon(help_icon $helpicon) {
        $context = $helpicon->export_for_template($this);
        // Solving the issue - "Your progress" help tooltip in course home page displays in outside the screen display.
        if ($helpicon->identifier === 'completionicons' && $helpicon->component === 'completion') {
            $context->ltr = right_to_left();
        }

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

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

        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']);
        $url = new moodle_url('/theme/edmo/pix/img/shape8.svg');
        $header->image = $url;
        $header->navbar = $this->navbar();
        $header->pageheadingbutton = $this->page_heading_button();
        $header->courseheader = $this->course_header();
        $header->headeractions = $this->page->get_header_actions();
        return $this->render_from_template('core/full_header', $header);
    }

    /**
     * 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
     * @param string $id An optional ID
     * @return string the HTML to output.
     */
    public function heading($text, $level = 2, $classes = 'main page-section-title-hide', $id = null) {
        return "<h3 id='$id' class='$classes'>$text</h3>";
    }
    /**
     * 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 $this->unique_main_content_token;
    }
}
