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

/**
 * Simulatore contabilità
 *
 * @package    mod_mtcontabilita
 * @copyright  2026 Mediatouch 2000 Srl <https://www.mediatouch.it>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @author     Marco Cappuccio <m.cappuccio@mediatouch.it>
 */

namespace mod_mtcontabilita\form;

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

require_once($CFG->dirroot . '/mod/mtcontabilita/lib.php');

use context;
use core_form\dynamic_form;
use html_writer;

/**
 * mtitem class
 */
class mtitem extends dynamic_form {

    /** @var session. */
    protected $session = null;

    /** @var cm. */
    protected $cm = null;

    /**
     * deinition
     */
    public function definition() {
        global $CFG, $DB;

        $mform =& $this->_form;

        $context = $this->get_context_for_dynamic_submission();
        $mtcontabilita = $DB->get_record('mtcontabilita', ['id' => $this->get_cm()->instance], '*', MUST_EXIST);

        // Course Module ID.
        $mform->addElement('hidden', 'cmid');
        $mform->setType('cmid', PARAM_INT);

        $mform->addElement('hidden', 'sessionid', $this->optional_param('sessionid', 0, PARAM_INT));
        $mform->setType('sessionid', PARAM_INT);

        $mform->addElement('header', 'general', get_string('general'));

        $mform->addElement('editor', 'description_editor',
            get_string('description', 'mtcontabilita'), null, $this->get_editor_options($context));
        $mform->setType('description_editor', PARAM_RAW);
        $mform->addRule('description_editor', null, 'required', null, 'client');

        $mform->addElement('header', 'sessions', get_string('mtitemrows', 'mod_mtcontabilita'));
        $repeatarray = [];
        $repeatarray[] = $mform->createElement('html', html_writer::start_div('border rounded p-4 mb-3 br-1 bg-gray-200'));
        $repeatarray[] = $mform->createElement('hidden', 'sessiondateid', 0);
        $repeatarray[] = $mform->createElement('float', 'itemnum', get_string('itemnum', 'mtcontabilita'));
        $repeatarray[] = $mform->createElement('date_selector', 'itemdate', get_string('itemdate', 'mtcontabilita'));
        $slang = $mtcontabilita->slang;
        $pars = ['lang' => $slang, 'courseid' => $this->get_cm()->course];
        $opt = ['' => get_string('choose')] +
            $DB->get_records_menu('mtcontabilita_list', $pars, 'name ASC', 'id,name');
        $repeatarray[] = $mform->createElement('select', 'listid', get_string('listid', 'mtcontabilita'), $opt);

        $opt = ['' => get_string('choose'), 'D' => "Dare", 'A' => "Avere"];
        $repeatarray[] = $mform->createElement('select', 'itemtype', get_string('itemtype', 'mtcontabilita'), $opt);

        $repeatarray[] = $mform->createElement('float', 'amount', get_string('itemamount', 'mtcontabilita'));
        $repeatarray[] = $mform->createElement('submit', 'deletebutton', get_string('deletesession', 'mtcontabilita'));
        $repeatarray[] = $mform->createElement('html', html_writer::end_div());

        $session = $this->get_session();
        $repeatcount = $session ? count($session->sessiondates) : 1;

        // Default mtcontabilita start time rounded to next hour.
        $time = time();
        $repeatoptions = [
            'sessiondateid' => ['type' => PARAM_INT],
            'itemnum' => ['default' => 1],
        ];

        $this->repeat_elements($repeatarray, $repeatcount, $repeatoptions, 'date_repeats', 'date_add_fields',
                               1, get_string('addsession', 'mod_mtcontabilita'), true, 'deletebutton');

    }

    /**
     * validation
     */
    public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        if (isset($data['date_repeats']) && $data['date_repeats'] > 0) {
            for ($i = 0; $i < $data['date_repeats']; $i++) {
                // Primo step.
                if ($i == 0) {
                    $itemnumtemp = $data['itemnum'][$i];
                    $itemdatetemp = $data['itemdate'][$i];
                } else {
                    if ($data['itemnum'][$i] < $itemnumtemp) {
                        $errors["itemnum[$i]"] = "L'id deve essere progressivo";
                    }
                    if ($data['itemdate'][$i] < $itemdatetemp) {
                        $errors["itemdate[$i]"] = "La data deve essere progressiva";
                    }
                }
                if ($data["itemtype"][$i] == "D") {
                    $dare = $data["amount"][$i];
                } else if ($data["itemtype"][$i] == "A") {
                    $avere = $data["amount"][$i];
                }
                if (($i + 1) == $data['date_repeats']) {
                    if ($dare != $avere) {
                        for ($j = 0; $j < $data['date_repeats']; $j++) {
                            $errors["amount[$j]"] = "Verificare dare e avere";
                        }
                    }
                }
            }
        }
        return $errors;
    }

    /**
     * Check permissions.
     */
    protected function check_access_for_dynamic_submission(): void {
    }

    /**
     * Current course module where session is added or updated
     *
     * @return \cm_info
     */
    protected function get_cm(): \cm_info {
        if (!$this->cm) {
            if ($session = $this->get_session()) {
                [$course, $cm] = get_course_and_cm_from_instance($session->mtcontabilitaid, 'mtcontabilita');
            } else {
                $cmid = $this->optional_param('cmid', 0, PARAM_INT);
                [$course, $cm] = get_course_and_cm_from_cmid($cmid, 'mtcontabilita');
            }
            $this->cm = $cm;
        }
        return $this->cm;
    }

    /**
     * Returns context where this form is used
     *
     * @return \context_module
     */
    public function get_context_for_dynamic_submission(): context {
        return \context_module::instance($this->get_cm()->id);
    }

    /**
     * Process form submission.
     *
     * @return void
     */
    public function process_dynamic_submission() {
        $data = $this->get_data();

        $sessiondates = [];
        for ($i = 0; $i < $data->date_repeats; $i++) {
            if (!isset($data->itemdate[$i])) {
                continue;
            }
            $date = new \stdClass();
            $date->itemdate = $data->itemdate[$i];
            $date->listid = $data->listid[$i];
            $date->itemtype = $data->itemtype[$i];
            $date->amount = $data->amount[$i];
            $date->itemnum = $data->itemnum[$i];
            $sessiondates[] = $date;
        }

        $this->save($data, $sessiondates);
    }

    /**
     * Saves the current form on database.
     *
     * @param \stdClass $data
     * @param array $sessiondates
     */
    protected function save(\stdClass $data, array $sessiondates) {
        $context = $this->get_context_for_dynamic_submission();

        if (!empty($data->sessionid)) {
            // Update session.
            $data->id = $data->sessionid;
            mtcontabilita_update_session($data, $sessiondates);
        } else {
            // Create session.
            mtcontabilita_add_session($data, $sessiondates, $context);
        }
    }

    /**
     * Current session
     *
     * @return \stdClass|null
     */
    protected function get_session(): ?\stdClass {
        $id = $this->optional_param('sessionid', 0, PARAM_INT);
        if ($id && !$this->session) {
            $this->session = mtcontabilita_get_session($id);
        }
        return $this->session;
    }

    /**
     * Options for the d editor.
     *
     * @param \context_module $context
     * @return array
     */
    protected function get_editor_options($context) {
        return [
            'noclean' => false,
            'maxfiles' => EDITOR_UNLIMITED_FILES,
            'context' => $context,
        ];
    }

    /**
     * Set data in the modal form.
     */
    public function set_data_for_dynamic_submission(): void {
        if ($session = $this->get_session()) {
            $session = fullclone($session);
            // Follow repeatable elements format, otherwise form defaults ones will override.
            for ($i = 0; $i < count($session->sessiondates); $i++) {
                $session->{"itemdate[$i]"} = $session->sessiondates[$i]->itemdate;
                $session->{"itemtype[$i]"} = $session->sessiondates[$i]->itemtype;
                $session->{"listid[$i]"} = $session->sessiondates[$i]->listid;
                $session->{"amount[$i]"} = $session->sessiondates[$i]->amount;
                $session->{"itemnum[$i]"} = $session->sessiondates[$i]->itemnum;
            }
            unset($session->sessiondates);
        } else {
            // Create an empty session object.
            $session = (object) ['id' => null];
        }

        $context = $this->get_context_for_dynamic_submission();
        $session = file_prepare_standard_editor($session, 'description', $this->get_editor_options($context),
            $context, 'mod_mtcontabilita', 'session', $session->id);
        // Fill the form with the session data.
        $this->set_data((array)$session + $this->_ajaxformdata);
    }

    /**
     * Returns url to set in $PAGE->set_url() when form is being rendered or submitted via AJAX
     *
     * @return \moodle_url
     */
    protected function get_page_url_for_dynamic_submission(): \moodle_url {
        $cmid = $this->optional_param('cmid', 0, PARAM_INT);
        $id = $this->optional_param('sessionid', 0, PARAM_INT);
        return new \moodle_url('/mod/mtcontabilita/view.php', [
            'action' => 'editsession',
            'sessionid' => $id,
            'cmid' => $cmid,
        ]);
    }
}
