<?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('init_form.php');

use mod_mtcontabilita\currency;

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

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

$id = $cm->instance;
$currenttab = 'tab';
$title = get_string('init', 'mtcontabilita');
$returnurl = new moodle_url('/mod/mtcontabilita/question2/', ['id' => $cmid]);

$PAGE->set_context($context);
$PAGE->set_url('/mod/mtcontabilita/question2/init.php',  ['id' => $cmid]);

$lang = current_language();
$bdecimali = $DB->get_field('mtcontabilita', 'bdecimali', ['id' => $id]);
$linguaconti = $DB->get_field('mtcontabilita', 'slang', ['id' => $id]);
// Aggancio: nel tuo caso gli input hanno markup tipo: .mtcurrency input[type="text"]
$PAGE->requires->js_call_amd('mod_mtcontabilita/currency', 'attach', [
    'input[data-mtcurrency="1"]',
    $lang,
    (int)$bdecimali,
    (object)[],
]);

$data = new stdClass();
$data->id = $cmid;
$data->type = ['' => get_string('choose'), 'D' => get_string('tipo1', 'mtcontabilita'), 'A' => get_string('tipo2', 'mtcontabilita')];

$params = ['hidden' => 0, 'courseid' => $course->id, 'lang' => $linguaconti];
$select = "hidden=:hidden AND courseid=:courseid AND lang=:lang";
// $data->list = ['' => get_string('choose')] + $DB->get_records_select_menu('mtcontabilita_list', $select, $params, 'name ASC', 'id,name');
// $recs = $DB->get_records_select('mtcontabilita_list', $select, $params, 'scheme, name ASC', 'id,name,scheme');
// $grouped = ['' => [get_string('choose')]];

// foreach ($recs as $rec) {
//     $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->list = ['' => get_string('choose')] +
    $DB->get_records_select_menu(
        'mtcontabilita_list',
        $select,
        $params,
        'name ASC',
        'id,name'
    );



// Prendo le scritture che sono non della situazione inziale
$sql = "SELECT i.* FROM {mtcontabilita_itemdet} i, {mtcontabilita_list} l
        WHERE i.listid=l.id AND i.mtcontabilitaid=? AND i.type>? AND lang=?
        ORDER BY i.sortorder";
// var_dump([$id, 0, $linguaconti]); echo $sql; die();
if ($recs = $DB->get_records_sql($sql, [$id, 0, $linguaconti])) {
    foreach ($recs as $rec) {
        $i = $rec->sortorder - 1;
        $data->itemdate = $rec->itemdate;
        $data->listid[$i] = $rec->listid;
        $data->itemtype[$i] = $rec->itemtype;
        $data->amount[$i] = $rec->amount;
        // $data->score[$i] = mtc_get_db($rec->score);
        $data->score[$i] = $rec->score;
    }
    $data->totitem = $rec->sortorder;
} else {
    $data->totitem = 2;
    $data->itemnum = 0;
}
$mform1 = new init_form( null, ['data' => $data ] );
if ($mform1->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $mform1->get_data()) {
    $DB->delete_records('mtcontabilita_itemdet', [
        'mtcontabilitaid' => $id,
        'itemdate' => 0,
        'type' => 1,
    ]);

    $c = 0;

    for ($i = 0; $i < $data->date_repeats; $i++) {
        // Protezione: se la riga non è compilata, salto.
        if (empty($data->listid[$i]) || !isset($data->amount[$i]) || trim((string)$data->amount[$i]) === '') {
            continue;
        }
        $new = new stdClass();
        $new->mtcontabilitaid = $id;
        $new->itemnum = 0;
        $new->itemdate = 0;
        $new->sortorder = ++$c;
        $new->listid = (int)$data->listid[$i];
        $new->itemtype = $data->itemtype[$i];

        // NORMALIZZO L'IMPORTO PRIMA DI SALVARE
        $rawamount = $data->amount[$i];
        $new->amount = currency::normalize($rawamount, $lang);

        $new->score = isset($data->score[$i]) ? (int)$data->score[$i] : 0;
        $new->type = 1;
        $DB->insert_record('mtcontabilita_itemdet', $new);
        
    }
    redirect('initsummary.php?id='.$cmid.'&sez=6&pt=1');
}

echo $OUTPUT->header();
require('tabs.php');

$url = $CFG->wwwroot."/mod/mtcontabilita/importsi/?id=$cmid";
echo '<a href="'.$url.'" class="btn btn-success">'.get_string('importsi', 'mtcontabilita').'</a>';
echo $OUTPUT->heading($title);
$mform1->display();
echo $OUTPUT->footer();
