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

require_once('../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once('locallib.php');
require_once('editlist_form.php');
require_once($CFG->dirroot.'/mod/mtcontabilita/locallib.php');

use mod_mtcontabilita\currency;

$cmid = required_param('id', PARAM_INT); // cmid.
$sort = optional_param('sort', 0, PARAM_INT);

list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'mtcontabilita');
require_course_login($course, true, $cm);
$context = context_module::instance($cm->id);

$id = $cm->instance;

$PAGE->set_context($context);
$PAGE->set_url('/mod/mtcontabilita/question2/editlist',  ['id' => $cmid, 'sort' => $sort]);
$PAGE->requires->jquery_plugin('ui');


$lang = current_language();

$bdecimali = (int)$DB->get_field('mtcontabilita', 'bdecimali', ['id' => $id]);
if ($bdecimali !== 1 && $bdecimali !== 2) {
    $bdecimali = 2;
}

$PAGE->requires->js_call_amd(
    'mod_mtcontabilita/currency',
    'attach',
    [
        'input[data-mtcurrency="1"]',
        $lang,
        $bdecimali,
        (object)[],
    ]
);


require_capability('mod/mtcontabilita:view', $context);
$returnurl = new moodle_url('/mod/mtcontabilita/question2/details.php', ['id' => $cmid]);
// *********************************************************************************************************************
$data = new stdClass();
$data->id = $cmid;
$opt = [];
$mtc = new \mtcontabilita();
$opt[''] = get_string('choose');

$slang = $DB->get_field('mtcontabilita', 'slang', ['id' => $id]);
// $recs = $DB->get_records('mtcontabilita_list', ['lang' => $slang, 'hidden' => 0, 'courseid' => $course->id], 'scheme,name ASC', 'id,name,nature,scheme');
// $grouped = ['' => [get_string('choose')]];

$recs = $DB->get_records('mtcontabilita_list', ['lang' => $slang, 'hidden' => 0, 'courseid' => $course->id], 'name ASC', 'id,name,nature,scheme');
$grouped = ['' => get_string('choose')];
foreach ($recs as $rec) {
    $grouped[$rec->id] = $rec->name;
    // Grouped non liminare.
    // $group = strtoupper(trim($rec->scheme)) ?: get_string('nogroup', 'mod_mtcontabilita');
    // if (!array_key_exists($group, $grouped)) {
    //     $grouped[$group] = []; // inizializza l'array
    // }
    // $grouped[$group][$rec->id] = $rec->name;
}
$data->list = $grouped; // unisci

$data->type = ['' => get_string('choose'), 'D' => get_string('tipo1', 'mtcontabilita'), 'A' => get_string('tipo2', 'mtcontabilita')];
$data->score = 0;
if ($recs = $DB->get_records('mtcontabilita_itemdet', ['mtcontabilitaid' => $id, 'sort' => $sort, 'type' => 0], 'sortorder ASC')) {
    foreach ($recs as $rec) {
        $i = $rec->sortorder - 1;
        $data->sort = $rec->sort;
        $data->itemnum = $rec->itemnum;
        $data->score += $rec->score;
        $data->itemdate = $rec->itemdate;
        $data->listid[$i] = $rec->listid;
        $data->itemtype[$i] = $rec->itemtype;
        $data->amount[$i] = rtrim(rtrim((string)$rec->amount, '0'), '.');
    }
    $data->totitem = $rec->sortorder;

} else {
    $maxnum = $DB->get_field('mtcontabilita_itemdet', 'MAX(sort)', ['mtcontabilitaid' => $id, 'type' => 0]);
    $data->sort = $maxnum > 0 ? $maxnum + 1 : 1;
    $data->totitem = 2;
    // $data->sortorder = 1;
}
// var_dump($data); die();

$mform1 = new step1_form( null, ['data' => $data ] );
if ($mform1->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $mform1->get_data()) {
    // var_dump($data); die();
    $c = 0;

    $currentsort = $sort > 0 ? $sort : (int)$data->sort;
    // oppure: $currentsort = $sort; (se stai editando una scrittura esistente)

    $DB->delete_records('mtcontabilita_itemdet', [
        'type' => 0,
        'mtcontabilitaid' => $id,
        'sort' => $currentsort,
    ]);

    // 1) Conta quante righe "valide" ci sono (quelle che verranno salvate).
    $righe = 0;
    for ($i = 0; $i < $data->date_repeats; $i++) {
        if (!empty($data->listid[$i]) && $data->amount[$i] !== '' && $data->amount[$i] !== null) {
            $righe++;
        }
    }

    // 2) Ripartisce il punteggio senza perdere centesimi nel salvataggio.
    $rowscores = [];
    if ($righe > 0) {
        $scoredb = currency::normalize((string)$data->score, $lang);
        $scorecents = (int)round(((float)$scoredb) * 100);
        $basecents = intdiv($scorecents, $righe);
        $restcents = $scorecents % $righe;
        for ($i = 0; $i < $righe; $i++) {
            $rowscores[$i] = ($basecents + ($i < $restcents ? 1 : 0)) / 100;
        }
    }

    // 3) Inserisce le righe con score diviso.
    $scoreindex = 0;
    for ($i = 0; $i < $data->date_repeats; $i++) {
        if (!empty($data->listid[$i]) && $data->amount[$i] !== '' && $data->amount[$i] !== null) {
            $new = new stdClass();
            $new->mtcontabilitaid = $id;
            $new->itemnum         = $data->itemnum;
            $new->score           = $rowscores[$scoreindex++] ?? 0;
            $new->itemdate        = $data->itemdate;
            $new->sort            = $currentsort;
            $new->sortorder       = ++$c;
            $new->listid          = $data->listid[$i];
            $new->itemtype        = $data->itemtype[$i];

            $rawamount = (string)$data->amount[$i];
            $amountdb  = currency::normalize($rawamount, $lang);
            if ($amountdb === '' || !is_numeric($amountdb)) {
                continue; // oppure lancia errore, come preferisci
            }
            $new->amount = $amountdb; // stringa "1234.56" o "1234"

            $new->type = 0;
            $DB->insert_record('mtcontabilita_itemdet', $new);
        }
    }

    redirect('details.php?id='.$cmid);
}

echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('new'));
$testoitem = $DB->get_field('mtcontabilita', 'description', ['id' => $id]);
// Applicazione di un div con altezza e scrollbar
echo '<div style="height: 100px; overflow-y: scroll;">' . format_text($testoitem) . '</div>';
$mform1->display();
echo $OUTPUT->footer();
