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

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

require_once($CFG->libdir.'/formslib.php');
require_once($CFG->dirroot.'/user/editlib.php');

use mod_mtcontabilita\currency;

/**
 * step1_form
 */
class step1_form extends moodleform {

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

        $mform = $this->_form;
        $data = $this->_customdata['data'];

        MoodleQuickForm::registerElementType(
            'mtcurrency',
            "$CFG->dirroot/mod/mtcontabilita/form/mtcurrency.php",
            'MoodleQuickForm_mtcurrency'
        );

        $grp = [];
        $repeatoptions = [];
        $repeatoptions['amount']['type'] = PARAM_RAW;
        $repeatoptions['amount']['options'] = ['class' => 'amount'];

        $repeatcount = $data->totitem;
        $mform->addElement('hidden', 'id');
        $mform->setType('id', PARAM_INT);
        $mform->addElement('hidden', 'tp');
        $mform->setType('tp', PARAM_INT);
        $mform->addElement('hidden', 'sort');
        $mform->setType('sort', PARAM_INT);

        $mform->addElement('html', '<table class="table table-striped table-hover">');
        $mform->addElement('html', '<tr>');

        $mform->addElement('html', '<td class="mtc-nowrap">');
        // $mform->addElement('text', 'itemnum', get_string('scrittura', 'mtcontabilita', $data->sort), ['size' => 5]);
        $mform->addElement('text', 'itemnum', get_string('scrittura', 'mtcontabilita', 'N'), ['size' => 5]);
        $mform->addElement('html', '</td>');

        $mform->addElement('html', '<td class="mtc-nowrap">');
        $mform->addElement('text', 'score', get_string('score', 'mtcontabilita'), ['size' => 4]);
        $mform->addElement('html', '</td>');

        $mform->addElement('html', '<td>');
        $mform->addElement('date_selector', 'itemdate', '&nbsp;', get_string('itemdate', 'mtcontabilita'));
        $mform->addElement('html', '</td>');

        $mform->addElement('html', '</tr>');
        $mform->addElement('html', '</table>');

        $mform->setType('itemnum', PARAM_RAW);
        $mform->addRule('itemnum', null, 'required', null, 'client');
        $mform->setType('score', PARAM_RAW);
        $mform->addRule('score', null, 'required', null, 'client');

        $mform->addElement('html', '<table class="table table-striped table-hover">');
        $mform->addElement('html', '<thead><tr>
        <th>'.get_string('denominazioneconto', 'mtcontabilita').'</th>
        <th>'.get_string('itemamount', 'mtcontabilita').'</th>
        <th>'.get_string('dareavere', 'mtcontabilita').'</th>
        <th>'.get_string('action').'</th>
        </tr></thead>');
        $grp[] = $mform->createElement('html', '<tr><td>');
        // $grp[] = $mform->createElement('selectgroups', 'listid', '', $data->list); // Diviso per gruppi.
        $grp[] = $mform->createElement('select', 'listid', '', $data->list);
        $grp[] = $mform->createElement('html', '</td>');
        $grp[] = $mform->createElement('html', '<td>');
        $grp[] = $mform->createElement('mtcurrency', 'amount', '', ['class' => 'amount']);
        $grp[] = $mform->createElement('html', '</td>');

        $grp[] = $mform->createElement('html', '<td>');
        $grp[] = $mform->createElement('select', 'itemtype', '', $data->type);
        $grp[] = $mform->createElement('html', '</td>');
        $grp[] = $mform->createElement('html', '<td>');
        $grp[] = $mform->createElement('submit', 'deletebutton', get_string('delete'));
        $grp[] = $mform->createElement('html', '</td>');
        $grp[] = $mform->createElement('html', '</tr>');

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

        for ($i = 0; $i < $mtnum; $i++) {
            if ($mform->elementExists('amount['.$i.']')) {
                $mform->addRule('listid['.$i.']', null, 'required', null, 'client');
                $mform->addRule('itemtype['.$i.']', null, 'required', null, 'client');
                $mform->addRule('amount['.$i.']', null, 'required', null, 'client');
            }
        }

        $mform->addElement('html', '</table>');

        $this->add_action_buttons();
        $this->set_data($data);
    }

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

        $dare = $avere = 0;
        if (isset($data['date_repeats']) && $data['date_repeats'] > 0) {
            for ($i = 0; $i < $data['date_repeats']; $i++) {
                if (isset($data['amount'][$i])) {

                    $lang = current_language(); // o meglio: fuori dal loop, una volta sola
                    $raw = (string)$data['amount'][$i];
                    $norm = currency::normalize($raw, $lang);

                    if ($norm === '' || !is_numeric($norm)) {
                        continue; // oppure set errore amount[$i]
                    }

                    $val = (float)$norm;
                    if ($data['itemtype'][$i] == 'D') {
                        $dare += $val;
                    } else if ($data['itemtype'][$i] == 'A') {
                        $avere += $val;
                    }
                    if (($i + 1) == $data['date_repeats']) {
                        if ($dare != $avere) {
                            for ($j = 0; $j < $data['date_repeats']; $j++) {
                                $errors["amount[$j]"] = get_string('tipo1', 'mtcontabilita').": $dare - ".get_string('tipo2', 'mtcontabilita').": $avere";
                            }
                        }
                    }
                }
            }
        }
        return $errors;
    }
}
