<?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_login();

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

// Se c'è attemptid in POST, enforce del timelimit.
if (!empty($_POST['attemptid'])) {
    $aid = (int)$_POST['attemptid'];
    $tinfo = mtc_timeinfo_for_attempt($aid);
    if ($tinfo['overdue']) {
        // Auto-finisco e mando alla pagina di cortesia.
        $rec = $DB->get_record('mtcontabilita_attempts', ['id' => $aid], '*', MUST_EXIST);
        if ($rec->state !== 'finished') {
            $rec->state = 'finished';
            $rec->timefinish = time();
            $rec->timemodified = $rec->timefinish;
            $DB->update_record('mtcontabilita_attempts', $rec);
        }
        $cmid = required_param('cmid', PARAM_INT); // assicurati che sia già passato nel form
        redirect(new moodle_url('/mod/mtcontabilita/player/endattempt.php', ['id' => $cmid, 'aid' => $aid]));
    }
}


if ($data = data_submitted()) {
    // echo "<pre>"; var_dump($data); die();

    $apesi = $DB->get_field('mtcontabilita', 'options', ['id' => $data->mtcontabilitaid]);
    $peso = json_decode($apesi);
    $adesso = time();

    // Costruisco l'elenco di tutti gli item da processare
    $items = [];

    if (!empty($data->scheme) && is_array($data->scheme)) {
        foreach ($data->scheme as $id => $v) {
            $items[$id] = true;
        }
    }
    if (!empty($data->da) && is_array($data->da)) {
        foreach ($data->da as $id => $v) {
            $items[$id] = true;
        }
    }
    if (!empty($data->mc) && is_array($data->mc)) {
        foreach ($data->mc as $id => $v) {
            $items[$id] = true;
        }
    }

    foreach (array_keys($items) as $itemdetid) {
        $score = 0;

        // Recupero eventuale record esistente per avere i valori "vecchi"
        $params = [
            'attemptid'       => $data->attemptid,
            'mtcontabilitaid' => $data->mtcontabilitaid,
            'itemdetid'       => $itemdetid,
            'bitem'           => 'i',
        ];
        $rec = $DB->get_record('mtcontabilita_attempt_items', $params);

        // Valori arrivati dal form (se il campo è disabilitato non arriva → uso quelli esistenti)
        $scheme      = isset($data->scheme[$itemdetid])
            ? $data->scheme[$itemdetid]
            : ($rec->scheme ?? '');
        $da          = isset($data->da[$itemdetid])
            ? $data->da[$itemdetid]
            : ($rec->da ?? '');
        $macroclasse = isset($data->mc[$itemdetid])
            ? $data->mc[$itemdetid]
            : ($rec->macroclasse ?? '');

        // === Calcolo punteggio SEMPRE (sia SAVE che CHECK) ===
        $sql = "SELECT d.id, d.score, d.itemtype, l.scheme, l.macroclasse
                FROM {mtcontabilita_itemdet} d
                JOIN {mtcontabilita_list} l ON d.listid = l.id
                WHERE d.id = ?";
        $corretta = $DB->get_record_sql($sql, [$itemdetid]);

        $pesopar = 0;
        $p0 = isset($peso[0]) ? (int)$peso[0] : 0; // scheme
        $p1 = isset($peso[1]) ? (int)$peso[1] : 0; // itemtype (d/a)
        $p2 = isset($peso[2]) ? (int)$peso[2] : 0; // macroclasse

        if (strtolower($corretta->scheme) == strtolower($scheme)) {
            $pesopar += $p0;
        }
        if (strtolower($corretta->itemtype) == strtolower($da)) {
            $pesopar += $p1;
        }
        if (strtolower($corretta->macroclasse) == strtolower($macroclasse)) {
            $pesopar += $p2;
        }

        // Somma pesi
        $pesotot = $p0 + $p1 + $p2;

        if ($pesotot == 0) {
            // Nessuna pesatura → score pieno
            $score = $corretta->score;
        } else {
            // Pesato in %
            $score = round($pesopar * $corretta->score / 100, 2);
        }
        // Inserisco / aggiorno il record.
        if (!$rec) {
            $rec = new \stdClass();
            $rec->attemptid       = $data->attemptid;
            $rec->mtcontabilitaid = $data->mtcontabilitaid;
            $rec->itemdetid       = $itemdetid;
            $rec->timecreated     = $adesso;
            $rec->bitem           = 'i';
            $rec->itemnum         = 0;
            $rec->listid          = 0;
        }

        $rec->timemodified = $adesso;
        $rec->scheme       = $scheme;
        $rec->da           = $da;
        $rec->macroclasse  = $macroclasse;
        $rec->score        = $score;
        $rec->bcheck       = ($data->action == 'check');

        if (!isset($rec->id)) {
            $DB->insert_record('mtcontabilita_attempt_items', $rec);
        } else {
            $DB->update_record('mtcontabilita_attempt_items', $rec);
        }
    }

}
$params = ['cmid' => $data->cmid, 'num' => $data->num, 'attemptid' => $data->attemptid];
redirect(new moodle_url('/mod/mtcontabilita/player/attempt.php', $params));
