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

$id = required_param('cmid', PARAM_INT); // course_module ID.
// $item = required_param('item', PARAM_INT); // item.
$num = required_param('num', PARAM_ALPHANUM); // num.
$attemptid = required_param('attemptid', PARAM_INT); // attemptid.

$tp = optional_param('tp', 1, PARAM_INT); // per default èlibro mastro.

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

require_course_login($course, true, $cm);
\mod_mtcontabilita\permission::require_can_view_mtcontabilita($context);

$adesso = time();
$params = ['userid' => $USER->id, 'mtcontabilitaid' => $cm->instance];
if (!$attempt = $DB->get_field('mtcontabilita_attempts', 'MAX(attempt)', $params)) {
    $attempt = 0;
}
// *****************************************************************************
// Creo il record attempt.
// *****************************************************************************
if ($rec = $DB->get_record('mtcontabilita_attempts', ['id' => $attemptid])) {
    // $new->mtcontabilitaid = $cm->instance;
    // $new->userid = $USER->id;
    // $new->attempt = $attempt+1;
    // $new->state = "started";
    // $new->timestart = $adesso;
    $rec->timemodified = $adesso;
    $rec->currentpage = $num;
    // $new->timefinish = 0;
    $DB->update_record('mtcontabilita_attempts', $rec);
    redirect($CFG->wwwroot.'/mod/mtcontabilita/player/attempt.php?cmid='.$id.'&num='.$num.'&attemptid='.$attemptid.'&tp='.$tp);
}
