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

defined('MOODLE_INTERNAL') || die();

/**
 * mtcontabilita_import_si class
 */
class mtcontabilita_import_si {

    /** @var var */
    private $stdfields;
    /** @var var */
    private $id;
    /** @var var */
    private $cmid;
    /** @var var */
    private $lang;

    /**
     * construct
     */
    public function __construct($id, $cmid, $lang) {
        $this->id = $id;
        $this->cmid = $cmid;
        $this->lang = $lang;
    }

    /**
     * validate
     */
    public function validate(csv_import_reader $cir, moodle_url $returnurl) {
        global $DB;

        $columns = $cir->get_columns();
        if (empty($columns)) {
            $cir->close();
            $cir->cleanup();
            redirect('index.php');
        }
        $processed = $columns;
        return [$processed];
    }

    /**
     * result
     */
    public function result($cir, $filecolumns, $cid) {
        global $DB, $USER;

        $adesso = time();
        $linenum = 1;
        $recordnew = 0;
        $recordupt = 0;
        $skipped = '';
        $this->stdfields[] = 'line';
        $this->stdfields[] = get_string('account', 'mtcontabilita');
        $this->stdfields[] = get_string('balance', 'mtcontabilita');
        $this->stdfields[] = get_string('dc', 'mtcontabilita');
        $this->stdfields[] = get_string('score', 'mtcontabilita');
        $this->stdfields[] = "status";
        $maxsortorder = $DB->get_field('mtcontabilita_itemdet', 'MAX(sortorder)', ['mtcontabilitaid' => $this->id, 'type' => 1]);
        // **************************************************************************************
        // Cicla tutte le linee del CSV e scrive i dati                                         *
        // **************************************************************************************
        $upt = new mtcontabilita_import_si_tracciamento($this->stdfields);
        $upt->start();
        while ($line = $cir->next()) {
            $upt->flush();
            $linenum++;
            $upt->track('line', $linenum);
            $upt->track(get_string('account', 'mtcontabilita'), $line[0]);
            $upt->track(get_string('balance', 'mtcontabilita'), $line[1]);
            $upt->track(get_string('dc', 'mtcontabilita'), $line[2]);
            $upt->track(get_string('score', 'mtcontabilita'), $line[3]);
            // Controllo esistenza listid.
            $val = mb_strtolower($line[0], 'UTF-8');
            if (!$listid = $DB->get_field('mtcontabilita_list', 'id', ['name' => $val, 'lang' => $this->lang])) {
                $upt->track('status', get_string('account_err', 'mtcontabilita'), 'error');
                $skipped++;
                continue;
            }
            // Controllo DA.
            $val = mb_strtolower($line[2], 'UTF-8');
            $acheck = $this->get_dg_check();
            if (array_key_exists($val, $acheck)) {
                $l2 = strtoupper($this->get_dg_check($val));
            } else {
                $upt->track('status', get_string('dg_err', 'mtcontabilita'), 'error');
                $skipped++;
                continue;
            }
            $new = [];
            $new['mtcontabilitaid'] = $this->id;
            $new['listid'] = $listid;
            $new['itemtype'] = $l2;
            $new['amount'] = str_replace(",", ".", $line[1]);
            $new['score'] = $line[3];
            $new['type'] = 1;
            if ($mtid = $DB->get_field('mtcontabilita_itemdet', 'id', ['listid' => $listid, 'type' => 1, 'mtcontabilitaid' => $this->id])) {
                $new['id'] = $mtid;
                $DB->update_record('mtcontabilita_itemdet', (object)$new);
                $recordupt++;
            } else {
                $new['sortorder'] = ++$maxsortorder;
                $DB->insert_record('mtcontabilita_itemdet', (object)$new);
                $recordnew++;
            }
            // Reorder.
            $so = 0;
            $recs = $DB->get_records('mtcontabilita_itemdet', ['mtcontabilitaid' => $this->id, 'type' => 1]);
            foreach ($recs as $rec) {
                $rec->sortorder = ++$so;
                $DB->update_record('mtcontabilita_itemdet', $rec);
            }

            foreach ($this->stdfields as $field) {
                if (isset($formdata->$field)) {
                    // process templates.
                    $riga->$field = uu_process_template($formdata->$field, $new);
                    $formdefaults[$field] = true;
                    if (in_array($field, $upt->columns)) {
                        $upt->track($field, s($new->$field), 'normal');
                    }
                }
            }
        }
        $rit = array($skipped, $recordnew, $recordupt);
        $upt->close();

        return $rit;
    }

    /**
     * get dg check
     */
    private function get_dg_check($val = "") {
        $rit = [
            "d" => "d",
            "dare" => "d",
            "a" => "a",
            "avere" => "a",
            "c" => "a",
            "debit" => "d",
            "credit" => "a",
        ];
        if ($val == "") {
            return $rit;
        } else {
            return $rit[$val];
        }
    }
}

/**
 * mtcontabilita_import_si_tracciamento class
 */
class mtcontabilita_import_si_tracciamento {

    /** @var var */
    private $_row;
    /** @var var */
    public $columns;

    /**
     * construct
     */
    public function __construct($stdfields) {
        $this->columns = $stdfields;
    }

    /**
     * start
     */
    public function start() {
        echo '<table id="tab" class="generaltable flexible-wrap" summary="summary">';
        echo '<tr class="heading r0">';
        for ($i = 0; $i < count($this->columns); $i++) {
            echo '<th class="header c'.$i.'" scope="col">'.$this->columns[$i].'</th>';
        }
        echo '</tr>';
        $this->_row = null;
    }

    /**
     * flush
     */
    public function flush() {
        if (empty($this->_row) || empty($this->_row['line']['normal'])) {
            $this->_row = array();
            foreach ($this->columns as $col) {
                $this->_row[$col] = array('normal' => '', 'info' => '', 'warning' => '', 'error' => '');
            }
            return;
        }
        $ci = 0;
        $ri = 1;
        echo '<tr class="r'.$ri.'">';
        foreach ($this->_row as $key => $field) {
            foreach ($field as $type => $content) {
                if ($field[$type] !== '') {
                    $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
                } else {
                    unset($field[$type]);
                }
            }
            echo '<td class="cell c'.$ci++.'">';
            echo !empty($field) ? implode('<br />', $field) : '&nbsp;';
            echo '</td>';
        }
        echo '</tr>';
        foreach ($this->columns as $col) {
            $this->_row[$col] = array('normal' => '', 'info' => '', 'warning' => '', 'error' => '');
        }
    }

    /**
     * track
     */
    public function track($col, $msg, $level = 'normal', $merge = true) {
        if (empty($this->_row)) {
            $this->flush();
        }
        if (!in_array($col, $this->columns)) {
            debugging('Incorrect column:'.$col);
            return;
        }
        if ($merge) {
            if ($this->_row[$col][$level] != '') {
                $this->_row[$col][$level] .= '<br />';
            }
            $this->_row[$col][$level] .= $msg;
        } else {
            $this->_row[$col][$level] = $msg;
        }
    }

    /**
     * close
     */
    public function close() {
        $this->flush();
        echo '</table>';
    }
}
