<?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');

$cmid = required_param('id', PARAM_INT); // CMID.
$pt = optional_param('pt', 0, PARAM_INT); // PARTE del riepilogo.

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;
$sez = 5 + $pt;
$currenttab = 'tab'.$sez;
$titsezione = get_string('init'.$sez, 'mtcontabilita');
$returnurl = new moodle_url('/mod/mtcontabilita/question2/index.php', []);

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

$alist = ['spd' => [], 'spa' => [], 'ced' => [], 'cea' => [], 'pnd' => [], 'pna' => []];
$atot = ['spd' => 0, 'spa' => 0, 'ced' => 0, 'cea' => 0, 'pnd' => 0, 'pna' => 0];
// Prima seleziono gli elementi.
$sql = "SELECT d.id, d.amount, l.name, d.itemtype, l.scheme
FROM {mtcontabilita_itemdet} d, {mtcontabilita_list} l
WHERE l.id=d.listid
AND d.type>? AND d.mtcontabilitaid=?
ORDER BY d.type,d.sortorder";
// $DB->set_debug(true);
$recs = $DB->get_records_sql($sql, [0, $id]);
// $DB->set_debug(false); die();
foreach ($recs as $rec) {
    // var_dump($rec);die();
    $alist[strtolower($rec->scheme.$rec->itemtype)][] = [$rec->name, ($rec->amount)];
    $atot[strtolower($rec->scheme.$rec->itemtype)] += $rec->amount;
}
// var_dump($sez, $alist, $atot, $cmid, $id); die();
$txtsez = $sez == 6 ? "sp" : "ce";
$bdecimali = $DB->get_field('mtcontabilita', 'bdecimali', ['id' => $id]);
list($table, $msg) = mtcontabilita_question::display_table_finish($bdecimali, $txtsez, $alist, $atot, $cmid, $id);

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