<?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($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/csvlib.class.php');

require_once('locallib.php');
require_once('index_form.php');

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

$cmid = required_param('id', PARAM_INT); // cmid.

list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'mtcontabilita');
require_course_login($course, true, $cm);
$context = context_module::instance($cm->id);
$PAGE->set_url('/mod/mtcontabilita/importsi/');
$PAGE->set_context($context);
if (!has_capability('mod/mtcontabilita:addinstance', $context)) {
    throw new \moodle_exception('nopermissions', 'error', '', get_string('nopermissions', 'mod_mtcontabilita'));
}
$id = $cm->instance;

$iid         = optional_param('iid', '', PARAM_INT);
$filecolumns = optional_param('filecolumns', '', PARAM_RAW);

$lang = $DB->get_field('mtcontabilita', 'slang', ['id' => $id]);

$returnurl = new moodle_url('/mod/mtcontabilita/importsi/index.php', ['id' => $cmid]);
$cl = new mtcontabilita_import_si($id, $cmid, $lang);
// *********************************************************************************************************************
// PASSO 1: CARICAMENTO FILE
// *********************************************************************************************************************
if (empty($iid)) {
    $mform1 = new step1_form( null, ['data' => ['id' => $cmid, 'lang' => $lang] ] );
    if ($mform1->is_cancelled()) {
        $par = ['sez' => 1, 'id' => $cmid, 'sesskey' => sesskey()];
        $urltogo = new moodle_url('/mod/mtcontabilita/question2/init.php', $par);
        redirect($urltogo);
    } else if ($formdata = $mform1->get_data()) {
        $iid = csv_import_reader::get_new_iid('mtcplperform');
        $cir = new csv_import_reader($iid, 'mtcplperform');
        $content = $mform1->get_file_content('userfile');
        // Rimuove BOM UTF-8 (EF BB BF)
        if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
            $content = substr($content, 3);
        }
        // var_dump($formdata); die();
        $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name);
        $csvloaderror = $cir->get_error();
        unset($content);
        if (!is_null($csvloaderror)) {
            print_error('csvloaderror', '', $returnurl, $csvloaderror);
        }
        list($filecolumns) = $cl->validate($cir, $returnurl);
        echo $OUTPUT->header();
        // echo current_language();
        echo $OUTPUT->heading(get_string('uploadresult', 'mtcontabilita'));
        // Elaborazione diretta senza passare da mform2
        $cir->init();
        $result = $cl->result($cir, $filecolumns, $id);
        $cir->close();
        $cir->cleanup(true);
        echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
        // Numero totale di record.
        for ($i = 0; $i <= 2; $i++) {
            echo '<b>'.get_string('msg'.$i, 'mtcontabilita').': '.$result[$i].'</b><br><br>';
        }
        echo $OUTPUT->box_end();
        echo $OUTPUT->continue_button($returnurl);
        echo $OUTPUT->footer();
        exit;
    } else {
        echo $OUTPUT->header();
        echo $OUTPUT->heading_with_help(get_string('uploadsi', 'mtcontabilita'), 'upload', 'mtcontabilita');
        echo $OUTPUT->heading('<a href="'.$CFG->wwwroot.'/mod/mtcontabilita/importsi/template_'.$lang.'.csv">'.get_string('template', 'mtcontabilita').'</a>', '4');
        echo html_writer::tag('div', get_string('istruzionisi', 'mtcontabilita'), array('class' => 'flexible-wrap'));
        $mform1->display();
        echo $OUTPUT->footer();
        die;
    }
}
