<?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('../question2/locallib.php');

$cmid    = required_param('id', PARAM_INT);
$mtid    = required_param('mtid', PARAM_INT);
$itemnum = required_param('itemnum', 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);
$contextc = context_course::instance($course->id);

if (!has_capability('mod/mtcontabilita:addinstance', $contextc)) {
    throw new moodle_exception('nopermissions', 'error', '', get_string('nopermissions', 'mod_mtcontabilita'));
}

$PAGE->set_context($context);
$PAGE->set_url(new moodle_url('/mod/mtcontabilita/evaluation/solution.php', [
    'id'      => $cmid,
    'mtid'    => $mtid,
    'itemnum' => $itemnum,
]));
$PAGE->set_pagelayout('popup');
$PAGE->set_title('Soluzione scrittura ' . $itemnum);
$PAGE->set_heading('Soluzione scrittura ' . $itemnum);

$bdecimali = $DB->get_field('mtcontabilita', 'bdecimali', ['id' => $cm->instance]);
$bdecimali = (int)($bdecimali ?? 2);
$ndec = mtc_get_ndec_for_mtcontabilita($cm->instance, $bdecimali);

// Recupero le righe di soluzione da mtcontabilita_itemdet (scritture = type 0)
$sql = "SELECT d.*, l.name AS conto
          FROM {mtcontabilita_itemdet} d
     LEFT JOIN {mtcontabilita_list} l
            ON l.id = d.listid
         WHERE d.mtcontabilitaid = :mtid
           AND d.itemnum = :itemnum
           AND d.type = 0
      ORDER BY d.sortorder, d.id";

$params  = ['mtid' => $mtid, 'itemnum' => $itemnum];
$records = $DB->get_records_sql($sql, $params);

echo $OUTPUT->header();

if ($records) {

    // Data corretta (una per scrittura). Prendo quella del primo record.
    $first = reset($records);
    $datestr = '';
    if (!empty($first->itemdate)) {
        $datestr = userdate($first->itemdate, get_string('strftimedate', 'langconfig'));
    }

    $table = new html_table();
    $table->attributes['class'] = 'generaltable table-sm';
    $table->head = [
        get_string('date'),
        get_string('account', 'mtcontabilita'),
        'Dare',
        'Avere',
        get_string('score', 'mtcontabilita'),
    ];

    foreach ($records as $r) {
        $dare = '';
        $avere = '';

        // itemtype: 'D' / 'A'
        if (!empty($r->itemtype)) {
            if ($r->itemtype === 'D') {
                $dare = mtc_get_db((float)$r->amount, $ndec);
            } else if ($r->itemtype === 'A') {
                $avere = mtc_get_db((float)$r->amount, $ndec);
            }
        }

        $row = [];
        $row[] = $datestr;
        $row[] = format_string($r->conto ?? ''); // <-- FIX: stringa, non numero
        $row[] = $dare;
        $row[] = $avere;
        $row[] = is_null($r->score) ? '' : format_float((float)$r->score, 2);

        $table->data[] = $row;
    }

    echo html_writer::tag('h3', 'Soluzione corretta', ['class' => 'mb-3']);
    echo html_writer::table($table);

} else {
    echo html_writer::div(get_string('nothingtodisplay'), 'alert alert-info');
}

echo $OUTPUT->footer();
