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

/**
 * Course renderer.
 *
 * @package   theme_universe
 * @copyright 2023 Marcin Czaja (https://rosea.io)
 * @license   Commercial https://themeforest.net/licenses
 */

namespace theme_universe\output\core;

use moodle_url;
use html_writer;
use core_course_category;
use coursecat_helper;
use stdClass;
use core_course_list_element;
use lang_string;
use theme_universe\util\course;

/**
 * @package    theme_universe
 * @copyright  2023 Marcin Czaja - Rosea Themes - rosea.io
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class course_renderer extends \core_course_renderer {

    /**
     * Renders html to display a course search form
     *
     * @param string $value default value to populate the search field
     * @return string
     */
    public function course_search_form($value = '') {

        $data = [
            'action' => \core_search\manager::get_course_search_url(),
            'btnclass' => 'btn-primary',
            'inputname' => 'q',
            'searchstring' => get_string('searchcourses'),
            'hiddenfields' => (object) ['name' => 'areaids', 'value' => 'core_course-course'],
            'query' => $value
        ];

        return $this->render_from_template('core/search_input_fw', $data);
    }

    /**
     * Renders the list of courses
     *
     * This is internal function, please use core_course_renderer::courses_list() or another public
     * method from outside of the class
     *
     * If list of courses is specified in $courses; the argument $chelper is only used
     * to retrieve display options and attributes, only methods get_show_courses(),
     * get_courses_display_option() and get_and_erase_attributes() are called.
     *
     * @param coursecat_helper $chelper various display options
     * @param array $courses the list of courses to display
     * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
     *     defaulted to count($courses)
     * @return string
     *
     * @throws \coding_exception
     * @throws \dml_exception
     * @throws \moodle_exception
     */
    protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
        global $CFG;


        if ($totalcount === null) {
            $totalcount = count($courses);
        }

        if (!$totalcount) {
            // Courses count is cached during courses retrieval.
            return '';
        }

        if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
            // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit.
            if ($totalcount <= $CFG->courseswithsummarieslimit) {
                $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
            } else {
                $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
            }
        }

        // Prepare content of paging bar if it is needed.
        $paginationurl = $chelper->get_courses_display_option('paginationurl');
        $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
        if ($totalcount > count($courses)) {
            // There are more results that can fit on one page.
            if ($paginationurl) {
                // The option paginationurl was specified, display pagingbar.
                $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
                $page = $chelper->get_courses_display_option('offset') / $perpage;
                $pagingbar = $this->paging_bar(
                    $totalcount,
                    $page,
                    $perpage,
                    $paginationurl->out(false, array('perpage' => $perpage))
                );
                if ($paginationallowall) {
                    $pagingbar .= html_writer::tag('div', html_writer::link(
                        $paginationurl->out(false, array('perpage' => 'all')),
                        get_string('showall', '', $totalcount)
                    ), array('class' => 'paging paging-showall'));
                }
            }
        } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
            // There are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode.
            $pagingbar = html_writer::tag(
                'div',
                html_writer::link(
                    $paginationurl->out(
                        false,
                        array('perpage' => $CFG->coursesperpage)
                    ),
                    get_string('showperpage', '', $CFG->coursesperpage)
                ),
                array('class' => 'paging paging-showperpage')
            );
        }

        // Display list of courses.
        $attributes = $chelper->get_and_erase_attributes('courses');
        $content = html_writer::start_tag('div', $attributes);

        if (!empty($pagingbar)) {
            $content .= $pagingbar;
        }

        $coursecount = 1;

        $content .= html_writer::start_tag('div', array('class' => 'rui-course-card-deck mt-2'));

        foreach ($courses as $course) {
            $content .= $this->coursecat_coursebox($chelper, $course);

            $coursecount++;
        }

        $content .= html_writer::end_tag('div');

        if (!empty($pagingbar)) {
            $content .= $pagingbar;
        }

        if (!empty($morelink)) {
            $content .= $morelink;
        }

        $content .= html_writer::end_tag('div'); // End courses.

        return $content;
    }

    protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
        global $CFG;
        $subcategories = [];
        if (!$chelper->get_categories_display_option('nodisplay')) {
            $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
        }
        $totalcount = $coursecat->get_children_count();
        if (!$totalcount) {
            // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children().
            // To avoid extra DB requests.
            // Categories count is cached during children categories retrieval.
            return '';
        }

        // Prepare content of paging bar or more link if it is needed.
        $paginationurl = $chelper->get_categories_display_option('paginationurl');
        $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
        if ($totalcount > count($subcategories)) {
            if ($paginationurl) {
                // The option 'paginationurl was specified, display pagingbar.
                $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
                $page = $chelper->get_categories_display_option('offset') / $perpage;
                $pagingbar = $this->paging_bar(
                    $totalcount,
                    $page,
                    $perpage,
                    $paginationurl->out(false, array('perpage' => $perpage))
                );
                if ($paginationallowall) {
                    $pagingbar .= html_writer::tag('div', html_writer::link(
                        $paginationurl->out(false, array('perpage' => 'all')),
                        get_string('showall', '', $totalcount)
                    ), ['class' => 'paging paging-showall']);
                }
            } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
                // The option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id).
                if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
                    $viewmoreurl->param('categoryid', $coursecat->id);
                }
                $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
                $morelink = html_writer::tag(
                    'div',
                    html_writer::link($viewmoreurl, $viewmoretext, array('class' => 'btn btn-secondary w-100')),
                    array('class' => 'paging paging-morelink wrapper-fw')
                );
            }
        } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
            // There are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode.
            $pagingbar = html_writer::tag('div', html_writer::link(
                $paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
                get_string('showperpage', '', $CFG->coursesperpage)
            ), array('class' => 'paging paging-showperpage'));
        }

        // Display list of subcategories.
        $content = html_writer::start_tag('div', array('class' => 'subcategories'));

        if (!empty($pagingbar)) {
            $content .= $pagingbar;
        }

        foreach ($subcategories as $subcategory) {
            $content .= $this->coursecat_category($chelper, $subcategory, $depth);
        }

        if (!empty($pagingbar)) {
            $content .= $pagingbar;
        }
        if (!empty($morelink)) {
            $content .= $morelink;
        }

        $content .= html_writer::end_tag('div');
        return $content;
    }

    /**
     * Returns HTML to display course content (summary, course contacts and optionally category name)
     *
     * This method is called from coursecat_coursebox() and may be re-used in AJAX
     *
     * @param coursecat_helper $chelper various display options
     * @param stdClass|core_course_list_element $course
     *
     * @return string
     *
     * @throws \coding_exception
     * @throws \dml_exception
     * @throws \moodle_exception
     */
    protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
        $theme = \theme_config::load('universe');

        if ($course instanceof stdClass) {
            $course = new core_course_list_element($course);
        }

        $cccteachers = $theme->settings->cccteachers;
        $cccsummary = $theme->settings->cccsummary;
        $coursecarddesclimit = $theme->settings->coursecarddesclimit;

        if ($coursecarddesclimit == null) {
            $coursecarddesclimit = 100;
        }

        $courseprogressbar = $theme->settings->courseprogressbar;

        $courseutil = new course($course);
        $coursecontacts = $courseutil->get_course_contacts();
        $metacoursecontacts = $courseutil->get_meta_course_contacts();
        $metacourselang = $courseutil->get_meta_course_lang();

        $showfilter1 = ($theme->settings->showfilter1 == '1') ? true : false;
        $showfilter2 = ($theme->settings->showfilter2 == '1') ? true : false;
        $showfilter3 = ($theme->settings->showfilter3 == '1') ? true : false;
        $showfilter4 = ($theme->settings->showfilter4 == '1') ? true : false;
        $showfilter5 = ($theme->settings->showfilter5 == '1') ? true : false;
        $showfilter6 = ($theme->settings->showfilter6 == '1') ? true : false;

        $customfiltertitle1 = $theme->settings->customfilter1;
        $customfiltertitle2 = $theme->settings->customfilter2;
        $customfiltertitle3 = $theme->settings->customfilter3;
        $customfiltertitle4 = $theme->settings->customfilter4;
        $customfiltertitle5 = $theme->settings->customfilter5;
        $customfiltertitle6 = $theme->settings->customfilter6;

        $metacoursecustomfilter1 = format_string($courseutil->get_meta_course_customfilter1());
        $metacoursecustomfilter2 = format_string($courseutil->get_meta_course_customfilter2());
        $metacoursecustomfilter3 = format_string($courseutil->get_meta_course_customfilter3());
        $metacoursecustomfilter4 = format_string($courseutil->get_meta_course_customfilter4());
        $metacoursecustomfilter5 = format_string($courseutil->get_meta_course_customfilter5());
        $metacoursecustomfilter6 = format_string($courseutil->get_meta_course_customfilter6());

        $courseenrolmenticons = $courseutil->get_enrolment_icons();
        $courseenrolmenticons = !empty($courseenrolmenticons) ? $this->render_enrolment_icons($courseenrolmenticons) : false;
        $courseprogress = $courseutil->get_progress();
        $hasprogress = $courseprogress != null;

        if ($courseprogressbar == 0) {
            $hasprogress = false;
            $courseprogress = false;
        }
        
        $forcedlanguage = ($theme->settings->courselangbadge == 1) ? strval($course->lang) : null;
        $showcustomfields = ($theme->settings->showcustomfields == 1) ? true : false;

        $coursedates = '';

        if ($this->page->theme->settings->ipcoursedates == 1) {
            $coursedates .= html_writer::start_div('rui-custom-field-box');
                $coursedates .= html_writer::tag('span', get_string('startdate', 'moodle'), ['class' => 'rui-custom-field-name']);
                $coursedates .= html_writer::tag('span', userdate($course->startdate, get_string('strftimedaydate', 'core_langconfig')), ['class' => 'rui-custom-field-value']);
            $coursedates .= html_writer::end_div(); // .rui-custom-field-box.

            // Course End date.
            $courseenddate = $course->enddate;
            if ($courseenddate != '0') {
                $coursedates .= html_writer::start_div('rui-custom-field-box');
                    $coursedates .= html_writer::tag('span', get_string('enddate', 'moodle'), ['class' => 'rui-custom-field-name rui-course-enddate-label']);
                    $coursedates .= html_writer::tag('span', userdate($courseenddate, get_string('strftimedaydate', 'core_langconfig')), ['class' => 'rui-course-enddate rui-custom-field-value']);
                $coursedates .= html_writer::end_div(); // .rui-custom-field-box.
            }
        }
        
        $data = [
            'id' => $course->id,
            'fullname' => $chelper->get_course_formatted_name($course),
            'visible' => $course->visible,
            'image' => $courseutil->get_summary_image(),
            'summary' => $courseutil->get_summary($chelper),
            'category' => $courseutil->get_category(),
            'showcustomfields' => $showcustomfields,
            'customfields' => $courseutil->course_get_taux(),
            'coursedates' => $coursedates,
            'hasprogress' => $hasprogress,
            'progress' => (int) $courseprogress,
            'hasenrolmenticons' => $courseenrolmenticons != false,
            'enrolmenticons' => $courseenrolmenticons,
            'hascontacts' => !empty($coursecontacts),
            'contacts' => $coursecontacts,
            'metacontacts' => $metacoursecontacts,
            'metalang' => $metacourselang,
            'metacoursecatid' => $course->category,
            'metacoursecustomfilter1' => $metacoursecustomfilter1,
            'metacoursecustomfilter2' => $metacoursecustomfilter2,
            'metacoursecustomfilter3' => $metacoursecustomfilter3,
            'metacoursecustomfilter4' => $metacoursecustomfilter4,
            'metacoursecustomfilter5' => $metacoursecustomfilter5,
            'metacoursecustomfilter6' => $metacoursecustomfilter6,
            'showfilter1' => $showfilter1,
            'showfilter2' => $showfilter2,
            'showfilter3' => $showfilter3,
            'showfilter4' => $showfilter4,
            'showfilter5' => $showfilter5,
            'showfilter6' => $showfilter6,
            'customfiltertitle1' => $customfiltertitle1,
            'customfiltertitle2' => $customfiltertitle2,
            'customfiltertitle3' => $customfiltertitle3,
            'customfiltertitle4' => $customfiltertitle4,
            'customfiltertitle5' => $customfiltertitle5,
            'customfiltertitle6' => $customfiltertitle6,
            'courseprogressbar' => $courseprogressbar,
            'cccteachers' => $cccteachers,
            'cccsummary' => $cccsummary,
            'coursecarddesclimit' => $coursecarddesclimit,
            'forcedlanguage' => $forcedlanguage
        ];

        return $this->render_from_template('theme_universe/custom_coursecard', $data);
    }

    /**
     * Displays one course in the list of courses.
     *
     * This is an internal function, to display an information about just one course
     * please use core_course_renderer::course_info_box()
     *
     * @param coursecat_helper $chelper various display options
     * @param core_course_list_element|stdClass $course
     * @param string $additionalclasses additional classes to add to the main <div> tag (usually
     *    depend on the course position in list - first/last/even/odd)
     * @return string
     */
    protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
        if (!isset($this->strings->summary)) {
            $this->strings->summary = get_string('summary');
        }

        if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
            return '';
        }

        if ($course instanceof stdClass) {
            $course = new core_course_list_element($course);
        }

        return $this->coursecat_coursebox_content($chelper, $course);
    }

    /**
     * Returns HTML to display a tree of subcategories and courses in the given category
     *
     * @param coursecat_helper $chelper various display options
     * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
     * @return string
     */
    protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
        // // Reset the category expanded flag for this course category tree first.
        // $this->categoryexpandedonload = false;
        $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
        if (empty($categorycontent)) {
            return '';
        }

        // Start content generation.
        $content = '';
        $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');

        $content .= html_writer::start_tag('div', $attributes);
            $content .= html_writer::tag('div', $categorycontent, ['class' => 'content']);
        $content .= html_writer::end_tag('div'); // End course_category_tree.

        return $content;
    }

    /**
     * Returns HTML to display a course category as a part of a tree
     *
     * This is an internal function, to display a particular category and all its contents
     * use {@link core_course_renderer::course_category()}
     *
     * @param coursecat_helper $chelper various display options
     * @param core_course_category $coursecat
     * @param int $depth depth of this category in the current tree
     * @return string
     */
    protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
        global $DB, $CFG;

        // Open category tag.
        $classes = ['category'];
        if (empty($coursecat->visible)) {
            $classes[] = 'dimmed_category';
        }

        $categorycontent = '';

        // Make sure JS file to expand category content is included.

        $content = html_writer::start_tag('div', [
            'class' => join(' ', $classes),
            'data-categoryid' => $coursecat->id,
            'data-depth' => $depth,
            // 'data-showcourses' => $chelper->get_show_courses(),
            // 'data-type' => self::COURSECAT_TYPE_CATEGORY,
        ]);

        // Number of courses.
        $a = $coursecat->get_courses_count();
        $b = $coursecat->get_children_count();
        $coursesum = $a + $b;
        // End.

        // Category name.
        $categoryname = html_writer::link(
            new moodle_url(
                '/course/index.php',
                ['categoryid' => $coursecat->id]
            ),
            $coursecat->get_formatted_name(),
            ['class' => 'rui-category-link text-decoration-none']
        );

        $html = null;

        // Path for links.
        $siteurl = $CFG->wwwroot;
        $catpath = "/course/index.php?categoryid=";

        // // DB: List all records.
        // $records = $DB->get_records('course_categories');

        // // List of all categories.
        // foreach ($records as $value) {
        //     $caturl = "{$siteurl}{$catpath}{$value->id}";
        //     $classcatdepth = "rui-subcat-badge categories-depth-{$value->depth}";

        //     $attributes = ['class' => $classcatdepth];
        //     $catname = $value->name;

        //     // Depth.
        //     if ($value->parent > 0 && $value->parent == $coursecat->id) {
        //         $html .= html_writer::link($caturl, $catname, $attributes);
        //     }

        // }

        $content .= html_writer::start_tag('div', ['class' => 'rui-categorybox-wrapper']);

        // Category Title.
        $content .= html_writer::start_tag('h3', ['class' => 'rui-categoryname aabtn']);
        $content .= $categoryname;
        $content .= html_writer::end_tag('h3');

        $content .= html_writer::start_tag('h5', ['class' => 'rui-no-courses-title']);
        switch ($coursesum) {
            case '1':
                $content .= $coursesum . '&nbsp;' . get_string('course', 'moodle');
                break;
            default:
                $content .= $coursesum . '&nbsp;' . get_string('courses', 'moodle');
                break;
        }
        $content .= html_writer::end_tag('h5');


        // Category desc.
        // $content .= $chelper->get_category_formatted_description($coursecat);
        $content .= html_writer::end_tag('div'); // End .rui-categorybox-wrapper.

        // Display subcategories if exists.
        if($html != null) {
            $content .= html_writer::tag('div', $html, ['class' => 'rui-category-box-subcat']);
        }

        // Add category content to the output.
        $content .= html_writer::tag('div', $categorycontent, ['class' => 'rui-categorybox-wrapper']);

        $content .= html_writer::end_tag('div'); // End .category.

        // Return the course category tree HTML.
        return $content;
    }

    /**
     * Returns enrolment icons
     *
     * @param array $icons
     *
     * @return array
     */
    protected function render_enrolment_icons(array $icons): array {
        $data = [];

        foreach ($icons as $icon) {
            $data[] = $this->render($icon);
        }

        return $data;
    }

}
