<?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 class utility class
 *
 * @package   theme_universe
 * @copyright 2024 Marcin Czaja (https://rosea.io)
 * @license   Commercial https://themeforest.net/licenses
 */

namespace theme_universe\util;

use moodle_url;
use core_course_list_element;
use coursecat_helper;
use core_course_category;
use html_writer;
use context_course;
use theme_config;

/**
 * Course class utility class
 *
 * @package   theme_universe
 * @copyright 2024 Marcin Czaja (https://rosea.io)
 * @license   Commercial https://themeforest.net/licenses
 */
class course {
    /**
     * @var \stdClass $course The course object.
     */
    protected $course;

    /**
     * Class constructor
     *
     * @param core_course_list_element $course
     *
     */
    public function __construct($course) {
        $this->course = $course;
    }

    /**
     * Returns the first course's summary image url
     *
     * @return string
     */
    public function get_summary_image($returngeneratedimageifnone = true) {
        global $CFG, $OUTPUT;

        foreach ($this->course->get_course_overviewfiles() as $file) {
            if ($file->is_valid_image()) {
                $url = moodle_url::make_file_url(
                    "$CFG->wwwroot/pluginfile.php",
                    '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
                        $file->get_filearea() . $file->get_filepath() . $file->get_filename(),
                    !$file->is_valid_image()
                );
                return $url->out();
            }
        }

        if (!$returngeneratedimageifnone) {
            return '';
        }

        return $OUTPUT->get_generated_image_for_id($this->course->id);
    }

    /**
     * Returns HTML to display course contacts.
     *
     * @return array
     */
    public function get_course_contacts() {
        $theme = \theme_config::load('universe');

        $contacts = [];
        if ($this->course->has_course_contacts() && $theme->settings->cccteachers == 1) {
            $instructors = $this->course->get_course_contacts();

            foreach ($instructors as $instructor) {
                $user = $instructor['user'];
                $userutil = new user($user->id);

                $contacts[] = [
                    'id' => $user->id,
                    'fullname' => fullname($user),
                    'userpicture' => $userutil->get_user_picture(),
                    'role' => $instructor['role']->displayname
                ];
            }
        }

        return $contacts;
    }

    /**
     * Returns HTML to display course contacts for filter.
     *
     * @return array
     */
    public function get_meta_course_contacts() {
        if ($this->course->has_course_contacts()) {
            $contacts = [];

            $instructors = $this->course->get_course_contacts();
        
            // Counter for teachers IDs separator.
            $k = 0;
            $last_key = count($instructors);

            foreach ($instructors as $instructor) {
                $k++;
                $user = $instructor['user'];

                $contacts = "{$user->firstname} {$user->lastname}";

                // Counter for teachers IDs separator.
                if ($k < $last_key) {
                    $contacts =  ', ';
                }
            }
        
            return $contacts;
        }
    }

    /**
     * Returns HTML to display course language for filter.
     *
     * @return array
     */
    public function get_meta_course_lang() {
        $lang = strval($this->course->lang);
        return $lang;
    }

    /**
     * Returns HTML to display course custom field for a given filter.
     *
     * @param int $filterNumber The filter number (e.g., 1, 2, 3, etc.).
     * @return string The HTML output for the filter.
     */
    public function get_meta_course_customfilter($filterNumber) {
        global $DB;
        $output = '';

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

        $customfilter = $theme->settings->{'customfilter' . $filterNumber};
        $record = $DB->get_record('customfield_field', ['shortname' => $customfilter]);

        if ($record != null) {
            $cfid = $record;
            $record = $DB->get_record('customfield_data', ['fieldid' => $cfid->id, 'instanceid' => $this->course->id]);

            if ($record != null) {
                if($record->intvalue != null) {

                    $fieldid = $DB->get_record('customfield_field', ['id' => $record->fieldid]);
                    $jsonString = $fieldid->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'];
                        
                        // // Print the options
                        // echo $options;
                    } else {
                        // Handle JSON decoding error
                        echo "Error decoding JSON: " . json_last_error_msg();
                    }
                    $optionsArray = explode("\r\n", $options);
                    $key = $record->intvalue - 1;
                    if($key >= 0) {
                        $output .= $optionsArray[$key];
                    }
                } else {
                    $output .= $record->value;
                }
            }

        }

        return $output;
    }

    /**
     * Returns HTML to display course custom field #1 for filter.
     */
    public function get_meta_course_customfilter1() {
        return $this->get_meta_course_customfilter(1);
    }

    /**
     * Returns HTML to display course custom field #2 for filter.
     */
    public function get_meta_course_customfilter2() {
        return $this->get_meta_course_customfilter(2);
    }

    /**
     * Returns HTML to display course custom field #3 for filter.
     */
    public function get_meta_course_customfilter3() {
        return $this->get_meta_course_customfilter(3);
    }

    /**
     * Returns HTML to display course custom field #4 for filter.
     */
    public function get_meta_course_customfilter4() {
        return $this->get_meta_course_customfilter(4);
    }

    /**
     * Returns HTML to display course custom field #5 for filter.
     */
    public function get_meta_course_customfilter5() {
        return $this->get_meta_course_customfilter(5);
    }

    /**
     * Returns HTML to display course custom field #6 for filter.
     */
    public function get_meta_course_customfilter6() {
        return $this->get_meta_course_customfilter(6);
    }


    /**
     * Returns HTML to display course category name.
     *
     * @return string
     *
     * @throws \moodle_exception
     */
    public function get_category(): string {
        $cat = core_course_category::get($this->course->category, IGNORE_MISSING);

        if (!$cat) {
            return '';
        }

        return $cat->get_formatted_name();
    }

    /**
     * Returns course summary.
     *
     * @param coursecat_helper $chelper
     */
    public function get_summary(coursecat_helper $chelper): string {
        if ($this->course->has_summary()) {
            return $chelper->get_course_formatted_summary(
                $this->course,
                ['overflowdiv' => true, 'noclean' => true, 'para' => false]
            );
        }

        return false;
    }

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

        $course = get_course($this->course->id);
        $customfieldvalue = null;
        $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');

                switch ($field->get_field()->get('type')) {
                    case 'select':
                        $value = $field->get_value();

                        if ($value != null) {
                            $customfieldvalue = null;
                        }

                        $options = $field->get_field()->get_options();
                        if (array_key_exists($value, $options)) {
                            $customfieldvalue = format_string(
                                $options[$value],
                                true,
                                ['context' => $field->get_field()->get_handler()->get_configuration_context()]
                            );
                        }
                        break;
                    default:
                        $customfieldvalue = $field->get_value();
                        break;
                }
                
                $customfieldshortname =  $field->get_field()->get('shortname');

                // Array with custom fields which need to be hidden.
                $hiddencustomfields = array(
                    "enrolldesc",
                    "enrollvideo",
                    "customcoursefavicon",
                    "topbarcolor",
                    "dmtopbarcolor",
                    "maincolor1",
                    "maincolor2",
                    "customcourselogo",
                    "customcoursedmlogo",
                    "footercolor",
                    "topbartextcolor",
                    "topbarbghovercolor",
                    "topbartexthovercolor",
                    "dmtopbartextcolor",
                    "dmtopbarbghovercolor",
                    "dmtopbartexthovercolor",
                    "topbarcolor2",
                    "dmtopbarcolor2"
                );
                $hiddencftitles = ["tool_courserating"];

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


    /**
     * Returns HTML to display course enrolment icons.
     *
     * @return array
     */
    public function get_enrolment_icons(): array {
        if ($icons = enrol_get_course_info_icons($this->course)) {
            return $icons;
        }

        return [];
    }

    /**
     * Get the user progress in the course.
     *
     * @param null $userid
     *
     * @return mixed
     */
    public function get_progress($userid = null) {
        return \core_completion\progress::get_course_progress_percentage($this->course, $userid);
    }
}
