<?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>
 */

use mod_mtcontabilita\output\view_page;
use mod_mtcontabilita\mtplayer;

require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once($CFG->dirroot . '/mod/mtcontabilita/player/locallib.php');
require_once('lib.php');
require_once($CFG->dirroot . '/mod/mtcontabilita/locallib.php');

$id = required_param('id', PARAM_INT); // Course Module ID.

list($course, $cm) = get_course_and_cm_from_cmid($id, 'mtcontabilita');
$mtcontabilita = $DB->get_record('mtcontabilita', ['id' => $cm->instance], '*', MUST_EXIST);
$context = context_module::instance($cm->id);

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

$params = ['objectid' => $mtcontabilita->id, 'context' => $context];
$event = \mod_mtcontabilita\event\course_module_viewed::create($params);
$event->add_record_snapshot('mtcontabilita', $mtcontabilita);
$event->trigger();

// Completion update.
$completion = new completion_info($course);
$completion->set_module_viewed($cm);

$PAGE->set_url('/mod/mtcontabilita/view.php', ['id' => $cm->id]);
$PAGE->set_title($course->shortname);
$PAGE->set_heading($course->fullname);
$PAGE->add_body_class('limitedwidth');

$canattempt = has_capability('mod/mtcontabilita:attempt', $context);
$canreviewmine = has_capability('mod/mtcontabilita:reviewmyattempts', $context);

$num = $mtcontabilita->binit ? 0 : 1;
$viewobj = new view_page();

$bresume = false;
$lastattempt = null;

// Recupero ultimo tentativo solo per la logica resume.
if ($mtcontabilita->publish && !empty($mtcontabilita->resume)) {
    $lastattempt = $DB->get_record_sql(
        "SELECT *
           FROM {mtcontabilita_attempts}
          WHERE mtcontabilitaid = :mtcid
            AND userid = :userid
       ORDER BY timemodified DESC, id DESC",
        ['mtcid' => $mtcontabilita->id, 'userid' => $USER->id]
    );

    if ($lastattempt && (
        $lastattempt->state === \mod_mtcontabilita\mtcontabilita_attempt::IN_PROGRESS ||
        $lastattempt->state === \mod_mtcontabilita\mtcontabilita_attempt::OVERDUE
    )) {
        $bresume = true;
    }
}

// ==============================
// Gestione numero tentativi
// ==============================
$maxattempts = isset($mtcontabilita->attempt) ? (int)$mtcontabilita->attempt : 0;

// Conta TUTTI i tentativi dell'utente, a prescindere dallo stato.
$attemptsdone = $DB->count_records('mtcontabilita_attempts', [
    'userid' => $USER->id,
    'mtcontabilitaid' => $mtcontabilita->id,
]);

$remainingattempts = null;
$attemptsexhausted = false;

if ($maxattempts > 0) {
    $remainingattempts = max(0, $maxattempts - $attemptsdone);
    $attemptsexhausted = ($attemptsdone >= $maxattempts);
}

// Se i tentativi sono esauriti ma c'è un tentativo riprendibile,
// permetto comunque il resume.
$showbutton = true;
$buttontext = '';
$url = null;
$lbl = '';
$action = 'post';

if ($mtcontabilita->publish) {
    if ($attemptsexhausted && !$bresume) {
        $showbutton = false;
    } else {
        $params = [
            'cmid' => $id,
            'num' => $num,
            'mtcontabilitaid' => $mtcontabilita->id,
        ];

        if (!$bresume) {
            $buttontext = get_string('startattempt', 'mtcontabilita');
            $params['new'] = true;
        } else {
            $buttontext = get_string('continueattemptmtcontabilita', 'mtcontabilita');
            $params['new'] = false;

            if (!empty($lastattempt->id)) {
                $params['attemptid'] = (int)$lastattempt->id;
            }
        }

        $url = new moodle_url('/mod/mtcontabilita/player/startattempt.php', $params);
        $lbl = $buttontext;
        $action = 'post';
    }
} else {
    $params = ['id' => $course->id];
    $url = new moodle_url('/course/view.php', $params);
    $lbl = get_string('backtocourse', 'mtcontabilita');
    $action = 'get';
    $showbutton = true;
}

$mt = new mtcontabilita();

echo $OUTPUT->header();
echo $mt->get_legend($USER, $mtcontabilita, $course->id);

// Messaggio informativo tentativi solo se il numero è finito (> 0).
if ($maxattempts > 0) {
    if ($attemptsexhausted && !$bresume) {
        echo $OUTPUT->notification(
            'Hai esaurito tutti i tentativi disponibili.',
            'notifyproblem'
        );
    } else if ($remainingattempts !== null) {
            // 'Hai ' . $maxattempts . ' tentativi a disposizione. Te ne restano ' . $remainingattempts . '.',
        if ($remainingattempts == 1) {
            $txt = 'Hai 1 tentativo a disposizione.';
        } else {
            $txt = 'Hai ' . $remainingattempts . ' tentativi a disposizione.';
        }
        echo $OUTPUT->notification(
            $txt,
            'info'
        );
    }
}

if ($showbutton && $url) {
    echo $OUTPUT->single_button($url, $lbl, $action, ['class' => 'continuebutton']);
}

echo $OUTPUT->footer();