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

$cmid = required_param('id', PARAM_INT); // CMID.
$courseid = optional_param('courseid', false, PARAM_INT);
$action   = optional_param('action', '', PARAM_ALPHA);

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_context($context);
$PAGE->set_url('/mod/mtcontabilita/question2/details.php', ['id' => $cmid]);
require_capability('mod/mtcontabilita:view', $context);

$id = $cm->instance;

$redirect = $CFG->wwwroot.'/mod/mtcontabilita/question2/details.php';
$strdefaultcategory = get_string('profiledefaultcategory', 'admin');
$strcreatefield     = get_string('new');
$mtq = new mtcontabilita_question_sql($id);

$bdecimali = (int)$DB->get_field('mtcontabilita', 'bdecimali', ['id' => $id]);
$ndec = mtc_get_ndec_for_mtcontabilita($id, $bdecimali);

switch ($action) {
    case 'p':
        // itemnum e libero: viene usato come spareggio testuale dopo la data.
        $sql = "SELECT sort,itemnum,itemdate
                  FROM {mtcontabilita_itemdet}
                 WHERE mtcontabilitaid=? AND sort>0
              GROUP BY sort,itemnum,itemdate
              ORDER BY itemdate ASC,itemnum ASC,sort ASC";
        $recs = $DB->get_records_sql($sql, [$id]);
        $num = 1;
        $finalsorts = [];
        foreach ($recs as $rec) {
            $tempsort = -$num;
            $DB->set_field('mtcontabilita_itemdet', 'sort', $tempsort, ['mtcontabilitaid' => $id, 'sort' => $rec->sort]);
            $finalsorts[$tempsort] = $num;
            // $sql = "UPDATE {mtcontabilita_itemdet} SET itemnum=? WHERE mtcontabilitaid=? AND itemnum=? AND itemdate=?";
            // $DB->execute($sql, [$num, $id, $rec->itemnum, $rec->itemdate]);
            $num++;
        }
        foreach ($finalsorts as $tempsort => $finalsort) {
            $DB->set_field('mtcontabilita_itemdet', 'sort', $finalsort, ['mtcontabilitaid' => $id, 'sort' => $tempsort]);
        }
        $DB->set_field('mtcontabilita', 'publish', 1, ['id' => $id]);
        break;
    // Sposta su e giù.
    case 'movefield':
        $sort = required_param('sort', PARAM_INT);
        $dir = required_param('dir', PARAM_ALPHA);

        if (confirm_sesskey()) {
            mtitemnum_move($id, $sort, $dir);
        }
        // redirect($redirect);
        break;
    case 'deletefield':
        $sort = required_param('sort', PARAM_INT);
        $confirm = optional_param('confirm', 0, PARAM_BOOL);

        if ( data_submitted() && $confirm && confirm_sesskey()) {
            mtitemnum_delete($id, $sort);
            redirect($redirect."?id=".$cmid, get_string('deleted'));
        }

        $optionsyes = array ('sort' => $sort, 'id' => $cmid, 'confirm' => 1, 'action' => 'deletefield', 'sesskey' => sesskey());
        $optno = array ('id' => $cmid);
        $strheading = get_string('itemdel', 'mtcontabilita', $sort);
        $PAGE->navbar->add($strheading);
        echo $OUTPUT->header();
        echo $OUTPUT->heading($strheading);
        $formcontinue = new single_button(new moodle_url($redirect, $optionsyes), get_string('yes'), 'post');
        $formcancel = new single_button(new moodle_url($redirect, $optno), get_string('no'), 'get');
        echo $OUTPUT->confirm(get_string('itemdel2', 'mtcontabilita'), $formcontinue, $formcancel);
        echo $OUTPUT->footer();
        die;
        break;
    default:
}
echo $OUTPUT->header();
$outputcategories = [];
$outputfields = [];

if ($recs = $mtq->get_item_dets()) {
    foreach ($recs as $rec) {
        $row = [];
        $row['cmid'] = $cmid;
        $row['mtcontabilitaid'] = $id;
        $row['sort'] = $rec->sort;
        $row['itemnum'] = $rec->itemnum;
        $score = round((float)$rec->score, 2);
        $row['score'] = mtc_get_db($score, mtc_has_fraction($score) ? 2 : 0);
        $row['itemdate'] = userdate($rec->itemdate, get_string('strftimedatefullshort', 'langconfig'));
        $agrp = [];
        $g = 0;
        $grps = $mtq->get_item_dets_list($rec->sort);
        foreach ($grps as $grp) {
            $agrp[$g] = [];
            $agrp[$g]['conto'] = $grp->name;
            $agrp[$g]['schema'] = get_string(strtolower($grp->scheme), 'mtcontabilita');
            if ($grp->itemtype == "D") {
                $agrp[$g]['amount1'] = mtc_get_db($grp->amount, $ndec);
                $agrp[$g]['amount2'] = "-";
            } else {
                $agrp[$g]['amount1'] = "-";
                $agrp[$g]['amount2'] = mtc_get_db($grp->amount, $ndec);
            }
            $g++;
        }
        $row['grp'] = $agrp;
        $row['isfirst'] = $rec->sort == 1;
        $row['islast'] = count($outputfields) == count($recs) - 1;
        $outputfields[] = $row;
    }
}
// Add new field menu.
$menu = new \action_menu();
$menu->set_menu_trigger($strcreatefield);
$options = [
    'tp1' => 'Scrittura',
    'tp2' => 'riga',
];

foreach ($options as $type => $fieldname) {
    $loadlink = new \moodle_url('/mod/mtcontabilita/question2/editlist.php', ['id' => $cmid, 'action' => 'new', 'tp' => $type]);
    $action = new \action_menu_link_secondary($loadlink, new \pix_icon('t/play', ''), $fieldname);
    $menu->add($action);
}
// var_dump($outputfields[0]); die();
$menu->attributes['class'] .= ' float-left mr-1';
// echo count($outputcategories); die();
// echo (int)!count($outputcategories)."----".count($recs)."---";
// echo (int)(count($outputcategories) == count($recs) - 1); die();
$outputcategories[] = [
    'id' => 1,
    'name' => get_string('itemdets', 'mtcontabilita'),
    'fields' => $outputfields,
    'hasfields' => count($outputfields),
    'isfirst' => !count($outputcategories),
    'islast' => count($outputcategories) == count($recs) - 1,
    'candelete' => 1 > 1,
    'azione' => "editlist.php?id=$cmid",
    'azione2' => "details.php?id=$cmid&action=p",
    'addfieldmenu' => $menu->export_for_template($OUTPUT),
];
// var_dump($outputcategories); die();

echo $OUTPUT->render_from_template('mod_mtcontabilita/question2/details', [
    'categories' => $outputcategories,
    'sesskey' => sesskey(),
    'contextid' => $context->id,
    'baseurl' => (new moodle_url('/mod/mtcontabilita/question2/details.php'))->out(false),
]);


echo $OUTPUT->footer();
