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

/**
 * Form to edit invitations to view the user's studyplans
 * @package    local_treestudyplan
 * @copyright  2025 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_treestudyplan\form;

use local_treestudyplan\local\tools\invitation_tools;
use local_treestudyplan\shareservice;
use core\context\system as context_system;

defined('MOODLE_INTERNAL') || die();
require_once("$CFG->libdir/formslib.php");

/**
 * Form to edit invitations to view the user's studyplans
 */
class editmanagedshare_form extends \moodleform {
    // Add elements to form.

    /**
     * Setup form
     */
    public function definition() {
        global $CFG;
        $context = context_system::instance();
        $mform = $this->_form; // Don't forget the underscore!

        $mform->addElement('hidden', 'add', 0);
        $mform->setType('add', PARAM_ALPHANUM);

        $mform->addElement('hidden', 'update', 0);
        $mform->setType('update', PARAM_INT);

        $options = [
            'ajax' => 'local_treestudyplan/form-user-selector',
            'multiple' => false,
            'perpage' => $CFG->maxusersperpage,
            'userfields' => implode(',', \core_user\fields::get_identity_fields($context, true)),
            'valuehtmlcallback' => function ($value) {
                global $DB, $OUTPUT;
                $user = $DB->get_record('user', ['id' => (int)$value], '*', IGNORE_MISSING);
                $details = shareservice::get_user_details($user);
                return $OUTPUT->render_from_template(
                    'local_treestudyplan/form/form-user-selector-suggestion',
                    $details
                );
            },
        ];
        $mform->addElement('autocomplete', 'user_id', get_string('selectauser', 'core_grades'), [], $options);

        $mform->addRule('user_id', null, 'required', null, 'client');

        $mform->addElement('text', 'name', get_string('invite_name', 'local_treestudyplan'), ['size' => 50]);
        $mform->setType('name', PARAM_NOTAGS);                   // Set type of element.
        $mform->setDefault('name', '');        // Default value.
        $mform->addRule('name', get_string('required'), 'required', null, 'client');

        $mform->addElement('text', 'email', get_string('invite_email', 'local_treestudyplan'), ['size' => 20]);
        $mform->setType('email', PARAM_EMAIL);          // Set type of element.
        $mform->setDefault('email', '');                // Default value.
        $mform->addRule('email', get_string('required'), 'required', null, 'client');
        $mform->addRule('email', get_string('email'), 'email', null, 'client');

        $mform->addElement('date_selector', 'unlockdate', get_string('invite_unlock_date', 'local_treestudyplan'), ['size' => 20]);
        $mform->setDefault('unlockdate', time() + 31536000);  // Default value is one year from now.
        $mform->addRule('unlockdate', get_string('required'), 'required', null, 'client');

        $mform->addElement('text', 'identifier', get_string('invite_identifier', 'local_treestudyplan'), ['size' => 20]);
        $mform->setType('identifier', PARAM_NOTAGS);    // Set type of element.
        $mform->setDefault('identifier', '');           // Default value.

        $mform->addElement('static', get_string('invite_email', 'local_treestudyplan'));

        $this->add_action_buttons();
    }

    /**
     * Custom validation should be added here.
     * @param array $data Supplied user data
     * @param array $files Any uploaded files
     * @return array validation data
     */
    public function validation($data, $files) {
        return [];
    }

    /**
     * Get supplied user data
     * @return object The supplied data
     */
    public function get_data() {
        global $USER;

        $data = parent::get_data();
        if ($data != null) {
            if (empty($data->user_id)) {
                $data->user_id = $USER->id;
            }

            if (empty($data->update)) {
                $date = new \DateTime("now", \core_date::get_user_timezone_object());
                $date->setTime(0, 0, 0);

                $data->idate = $date->getTimeStamp();
            }

            if (empty($data->update)) {
                $data->invitekey = invitation_tools::generate_invitekey();
            }
        }
        return $data;
    }
}
