<?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\mtcontabilita_attempt;

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

$attemptid = optional_param('attemptid', 0, PARAM_INT);
// Get submitted parameters.
$id = required_param('cmid', PARAM_INT); // Course module id
$num = required_param('num', PARAM_INT);
$new = required_param('new', PARAM_BOOL);
$mtcontabilitaid = required_param('mtcontabilitaid', PARAM_INT);

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);
// This script should only ever be posted to, so set page URL to the view page.
$PAGE->set_url(new moodle_url('/mod/mtcontabilita/view.php', ['id' => $id]));
$PAGE->set_cacheable(false);
$PAGE->set_heading($course->fullname);
require_sesskey();

require_sesskey();

$attemptrec = null;

if (!$new) {
    // Se la view ha passato attemptid, usa quello (più sicuro).
    if (!empty($attemptid)) {
        $attemptrec = $DB->get_record('mtcontabilita_attempts', [
            'id' => $attemptid,
            'userid' => $USER->id,
            'mtcontabilitaid' => $mtcontabilitaid,
        ]);
        if ($attemptrec && $attemptrec->state === \mod_mtcontabilita\mtcontabilita_attempt::IN_PROGRESS) {
            redirect(new moodle_url('/mod/mtcontabilita/player/attempt.php', [
                'attemptid' => $attemptrec->id,
                'cmid' => $cm->id,
                // 'num' => $num,
                'num' => (int)$attemptrec->currentpage,

            ]));
            exit;
        }
    }

    // Fallback: cerca ultimo tentativo inprogress.
    $attemptrec = $DB->get_record_sql(
        "SELECT *
           FROM {mtcontabilita_attempts}
          WHERE mtcontabilitaid = :mtcid
            AND userid = :userid
       ORDER BY timemodified DESC, id DESC",
        ['mtcid' => $mtcontabilitaid, 'userid' => $USER->id]
    );

    if ($attemptrec && $attemptrec->state === \mod_mtcontabilita\mtcontabilita_attempt::IN_PROGRESS) {
        redirect(new moodle_url('/mod/mtcontabilita/player/attempt.php', [
            'attemptid' => $attemptrec->id,
            'cmid' => $cm->id,
            // 'num' => $num,
            'num' => (int)$attemptrec->currentpage,

        ]));
        exit;
    }

    // Se non c'è nulla da riprendere, ci penserà la validate_new_attempt() a degradare a new.
}

$mtcontabilitaobj = new stdClass();
$mtcontabilitaobj->mtcontabilitaid = $mtcontabilitaid;
$mtcontabilitaobj->id = $cm->instance;
$mtcontabilitaobj->context = $context;
$mtcontabilitaobj->cm = $cm;
$mtcontabilitaobj->course = $course;
$mtcontabilitaobj->new = $new;
// Validate permissions for creating a new attempt and start a new preview attempt if required.
list($currentattemptid, $attemptnumber, $lastattempt, $messages, $page) =
    mtcontabilita_validate_new_attempt($mtcontabilitaobj, $new, $num, true);

// Check access.
if ($messages) {
    $output = $PAGE->get_renderer('mod_mtcontabilita');
    throw new \moodle_exception('attempterror', 'mtcontabilita', new moodle_url('/mod/mtcontabilita/view.php', ['id' => $cm->id]), []);
}

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

$mtcontabilita = $DB->get_record('mtcontabilita', ['id' => $cm->instance]);
$attempt = mtcontabilita_attempt_save_started($mtcontabilita, $mtcontabilitaobj);

if (!$new && $attemptrec && $attemptrec->state === \mod_mtcontabilita\mtcontabilita_attempt::IN_PROGRESS) {
    $resumenum = (int)$attemptrec->currentpage;

    // sicurezza extra: se NON c'è situazione iniziale e currentpage è 0,
    // forza a 1 (prima scrittura)
    $mtc = $DB->get_record('mtcontabilita', ['id' => $attemptrec->mtcontabilitaid], 'id,binit', MUST_EXIST);
    if (empty($mtc->binit) && $resumenum === 0) {
        $resumenum = 1;
    }

    redirect(new moodle_url('/mod/mtcontabilita/player/attempt.php', [
        'attemptid' => $attemptrec->id,
        'cmid'      => $cm->id,
        'num'       => $resumenum,
    ]));
    exit;
}

// Redirect to the attempt page (NEW attempt).
$startnum = (int)$num;

// Se non c'è situazione iniziale, la prima pagina reale è 1 (non 0).
if (!empty($mtcontabilita) && empty($mtcontabilita->binit) && $startnum === 0) {
    $startnum = 1;
}

redirect(new moodle_url('/mod/mtcontabilita/player/attempt.php', [
    'attemptid' => $attempt->id,
    'cmid'      => $cm->id,
    'num'       => $startnum,
]));
exit;