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

/**
 * Form update_scripts
 *
 * @package    block_ned_teacher_tools
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace block_ned_teacher_tools\form;

defined('MOODLE_INTERNAL') || die();

use block_ned_teacher_tools\shared_lib as SH;

/** @var \stdClass $CFG */
require_once($CFG->libdir.'/formslib.php');

/**
 * Form update_scripts
 *
 * @package    block_ned_teacher_tools
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class update_scripts extends \moodleform {

    const ACTION_QUIZ = 'quiz';
    const ACTION_CM = 'cm';
    const ACTION_GT = 'gt';
    const ACTIONS = [self::ACTION_QUIZ, self::ACTION_CM, self::ACTION_GT];

    public function definition() {
        $data  = $this->_customdata;
        $mform = $this->_form;
        $mform->_attributes['class'] = str_replace('\\', ' ', __CLASS__) . ' ned-form';
        if ($data['class'] ?? false){
            $mform->_attributes['class'] .= ' '.$data['class'];
        }

        if (isset($data['hiddens'])){
            foreach ($data['hiddens'] as $key => $item){
                $mform->addElement('hidden', $key, $item);
                $mform->setType($key, PARAM_TEXT);
            }
        }

        $courses = SH::get_all_courses();
        $courses_options = [-1 => SH::str('none'), 0 => get_string('all')];
        $courses_options += SH::records2menu($courses, 'fullname') ?: [];
        $options = ['multiple' => true];
        $mform->addElement('autocomplete', 'courses', SH::str('courses'), $courses_options, $options);
        $mform->setType('courses', PARAM_ALPHANUMEXT);

        $choices = [
            static::ACTION_QUIZ => SH::str('updatequizzes'),
            static::ACTION_CM => SH::str('updatecms'),
            static::ACTION_GT => SH::str('updategt'),
        ];
        $mform->addElement('select', 'action', SH::str('action'), $choices, static::ACTION_QUIZ);

        $this->add_action_buttons(true, $data['submit'] ?? SH::str('update'));
    }

    /**
     * Render & return form as html
     *
     * @return string
     */
    public function draw() {
        //finalize the form definition if not yet done
        if (!$this->_definition_finalized) {
            $this->_definition_finalized = true;
            $this->definition_after_data();
        }

        return $this->_form->toHtml();
    }

    /**
     * Add error text to the form
     *
     * @param $text
     */
    public function error($text){
        $this->_form->addElement('html', \html_writer::div(
            SH::span(get_string('error').': ', 'error-label').
            SH::span($text, 'error-text'),
            'error'));
    }

    /**
     * Do standard action for this form
     *
     * @param \stdClass $data
     * @param bool $print
     *
     * @return bool
     */
    public function do_action($data=null, $print=true){
        $p = function($text, $h=0) use ($print){
            if (!$print){
                return;
            }
            if(!NO_OUTPUT_BUFFERING){
                ob_flush();
                flush();
            }
            if ($h){
                echo SH::tag('h'.$h, $text);
            } else {
                echo SH::div($text);
            }
        };

        $data = $data ?? $this->get_data();
        $course_ids = $data->courses ?? [];
        if (empty($course_ids)){
            return false;
        }

        $action = $data->action ?? false;
        if (!$action || !in_array($action, static::ACTIONS)){
            return false;
        }

        $all_courses = SH::get_all_courses();
        $courses = [];
        if (in_array(0, $course_ids)){
            $courses = $all_courses;
        } else {
            foreach ($course_ids as $cid){
                if (isset($all_courses[$cid])){
                    $courses[$cid] = $all_courses[$cid];
                }
            }
        }

        if (empty($courses)){
            return false;
        }

        $c = count($courses);
        $p(SH::str('courseforupdate', $c));
        $p('<br>');
        $i = 1;

        foreach ($courses as $course){
            $p("$i) {$course->fullname}", 2);
            switch($action){
                case static::ACTION_QUIZ:
                    \block_ned_teacher_tools\quiz_overview_report::regrade_all_quizzes_by_course($course, $print);
                    break;
                case static::ACTION_CM:
                    block_ned_teacher_tools_update_all_cm_by_course($course);
                    break;
                case static::ACTION_GT:
                    $count = \block_ned_teacher_tools\grading_tracker::check_missed_records_by_course($course);
                    $count += \block_ned_teacher_tools\grading_tracker::check_missed_previous_attempts_by_course($course);
                    if ($count){
                        $p(SH::$C::str('addedsuccessfully_records', $count));
                    } else {
                        $p(SH::$C::str('nonewrecords'));
                    }
                    break;
            }
            $i++;
        }

        return true;
    }
}
