<?php
// This file is part of the Studyplan plugin for Moodle
//
// 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 <https://www.gnu.org/licenses/>.

/**
 * No file description
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_treestudyplan\form;
defined('MOODLE_INTERNAL') || die();

require_once($CFG->dirroot . '/repository/lib.php');
use local_treestudyplan\studyplan;
use local_treestudyplan\contextinfo;
use local_treestudyplan\studyplanservice;
use local_treestudyplan\courseservice;
use local_treestudyplan\form\text_integer;
use moodle_exception;
use stdClass;
use core\context;

/**
 * Moodleform class for the studyplan editor. A Moodleform is used here to facilitate a rich editor
 * in the studyplan description
 */
class studyplan_fromtemplateform extends formbase {
    /**
     * Capability required to edit study plans
     * @var string
     */
    const CAP_EDIT = "local/treestudyplan:editstudyplan";

    /**
     * Translate parameters into customdata.
     *
     * @param object $params The parameters for form initialization
     * @return object Form data based on parameters
     */
    public static function init_customdata(object $params) {
        $customdata = new stdClass();
        $customdata->context = context::instance_by_id($params->contextid);

        return $customdata;
    }

    /**
     * Generate form data from parameters
     * Also validate parameters and access permissions here
     *
     * @param object $customdata The parameters for form initialization
     * @return object Form data based on parameters
     */
    public function init_formdata(object $customdata) {
        /*  Use direct database retrieval to avoid our abstractions causing trouble
            with existing moodle code assumptions.
            The form API does seem needlessly convoluted in it's use, but we need the editor...
        */
        $entry = new stdClass();
        $entry->context_id = $customdata->context->id;

        // Determine the next august 1st for default value purposes.
        $august = strtotime("first day of august this year");
        if ($august < time()) {
            $august = strtotime("first day of august next year");
        }
        $entry->startdate = $august;
        $entry->enddate = $august + (364 * 24 * 60 * 60); // Not bothering about leap years here.
        $entry->periods = 4;
        $entry->template_id = 0;

        return $entry;
    }

    /**
     * Set up the form definition
     */
    public function definition() {
        $mform = $this->_form;
        // Register integer type.
        text_integer::register();

        // Define the form.

        $templatelist = [];
        foreach (studyplan::find_template() as $s) {
            $c = (new contextinfo($s->context()))->model();
            $templatelist[$s->id()] = implode(" / ", $c['path']) . " / " . $s->name();
        }

        if (count($templatelist) > 0) {
            $mform->addElement('hidden', 'hastemplates', 'yes');

            $field = 'template_id';
            $mform->addElement(
                'autocomplete',
                $field,
                get_string('studyplan_fromtemplate', 'local_treestudyplan'),
                $templatelist
            );
            $mform->addRule($field, null, 'required', null, 'client');

            $field = 'name';
            $mform->addElement(
                'text',
                $field,
                get_string('studyplan_name', 'local_treestudyplan'),
                []
            );
            $mform->addRule($field, null, 'required', null, 'client');

            $field = 'shortname';
            $mform->addElement(
                'text',
                $field,
                get_string('studyplan_shortname', 'local_treestudyplan'),
                []
            );
            $mform->addRule($field, null, 'required', null, 'client');

            $field = 'idnumber';
            $mform->addElement(
                'text',
                $field,
                get_string('studyplan_idnumber', 'local_treestudyplan'),
                []
            );

            $contextlist = [];
            foreach (courseservice::list_available_categories('edit') as $c) {
                $contextlist[$c['context_id']] = implode(" / ", $c['category']['path']);
            }

            $field = 'context_id';
            $mform->addElement(
                'autocomplete',
                $field,
                get_string('studyplan_context', 'local_treestudyplan'),
                $contextlist
            );
            $mform->addRule($field, null, 'required', null, 'client');

            $timeless = \get_config("local_treestudyplan", "timelessperiods");
            if (!$timeless) {
                // Only add these fields if the studyplans are timed.
                $field = 'startdate';
                $mform->addElement(
                    'date_selector',
                    $field,
                    get_string('studyplan_startdate', 'local_treestudyplan'),
                    []
                );
                $mform->addRule($field, null, 'required', null, 'client');
            }
        } else {
            $mform->addElement('hidden', 'hastemplates', 'no');

            $field = 'warning';
            $mform->addElement(
                'static',
                $field,
                get_string('warning', 'core'),
                get_string('no_templates', 'local_treestudyplan')
            );
        }
    }

    /**
     * Process the submitted data and perform necessary actions
     * @param object $entry The processed form data;
     * @return mixed Data to pass to receiver if submission successful
     * @throws \moodle_exception if an error must be given for a specific reason.
     */
    protected function process_submitted_data($entry) {
        if ($entry->hastemplates == "yes") {
            // Find template study plan.
            $template = studyplan::find_by_id($entry->template_id);
            // Copy template plan.
            $plan = $template->duplicate($entry->name, $entry->shortname, $entry->context_id, $entry->idnumber, $entry->startdate);

            /* Return the simple model of the plan to make sure we can update stuff.
            Parse it through the clean_returnvalue function of exernal api (of which studyplanservice is a subclass)
            so we return it in a consistent way
            */
            return studyplanservice::clean_returnvalue(studyplan::simple_structure(), $plan->simple_model());
        } else {
            return null;
        }
    }
}
