<?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); // id.

list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'mtcontabilita');
require_course_login($course, true, $cm);
$context = context_module::instance($cm->id);

$contextc = context_course::instance($course->id);
if (!has_capability('mod/mtcontabilita:addinstance', $contextc)) {
    throw new \moodle_exception('nopermissions', 'error', '', get_string('nopermissions', 'mod_mtcontabilita'));
}

$PAGE->set_context($context);
$PAGE->set_url('/mod/mtcontabilita/evaluation/', ['id' => $cmid]);

$sort         = optional_param('sort', 'name', PARAM_ALPHANUMEXT);
$dir          = optional_param('dir', 'ASC', PARAM_ALPHA);
$page         = optional_param('page', 0, PARAM_INT);
$perpage      = optional_param('perpage', 30, PARAM_INT);        // how many per page
$action = optional_param('action', '', PARAM_ALPHA);

$stredit = get_string('details');
$returnurl = new moodle_url('/mod/mtcontabilita/manage/index.php', array('id' => $cmid , 'sort' => $sort, 'dir' => $dir, 'perpage' => $perpage, 'page' => $page));

$valscoremax = $DB->get_field('mtcontabilita_itemdet', 'SUM(score)', ['mtcontabilitaid' => $cm->instance]);

$calcolo = $DB->get_field('mtcontabilita', 'calcolo', ['id' => $cm->instance]);
$binit = $DB->get_field('mtcontabilita', 'binit', ['id' => $cm->instance]);

if (!$binit) {
    $calcolo = 1;
}

$params = ['mtid' => $cm->instance];

echo $OUTPUT->header();

$columns = ['name', 'email', 'attempt', 'scorei', 'scores', 'scoretot', 'scoremax'];

foreach ($columns as $column) {
    $string[$column] = get_string($column, 'mtcontabilita');
    if ($sort != $column) {
        $columnicon = "";
        if ($column == "name") {
            $columndir = "DESC";
        } else {
            $columndir = "ASC";
        }
    } else {
        $columndir = $dir == "ASC" ? "DESC" : "ASC";
        if ($column == "name") {
            $columnicon = ($dir == "ASC") ? "sort_desc" : "sort_asc";
        } else {
            $columnicon = ($dir == "ASC") ? "sort_asc" : "sort_desc";
        }
        $columnicon = $OUTPUT->pix_icon('t/' . $columnicon, get_string(strtolower($columndir)), 'core',
                                        ['class' => 'iconsort']);

    }
    $$column = "<a href=\"index.php?id=$cmid&sort=$column&amp;dir=$columndir\">".$string[$column]."</a>$columnicon";
}

list($extrasql, $params) = ["", []];

$users = mtcontabilita_evaluation::get_users_listing($cm->instance, $course->id, $sort, $dir,
        $page * $perpage, $perpage, '', '', '', $extrasql, $params, $context);

// Conteggio reale dei tentativi (solo finished/abandoned).
$usercount = mtcontabilita_evaluation::count_attempts($cm->instance, $course->id,
        '', '', '', $extrasql, $params, $context);

echo $OUTPUT->paging_bar($usercount, $page, $perpage, $returnurl);

flush();

if (!$users) {
    $match = [];
    echo $OUTPUT->heading(get_string('nousersfound'));
    $table = null;
} else {
    $table = new html_table();

    $table->colclasses = [];
    $table->colclasses[] = '';                   // name
    $table->colclasses[] = '';                   // email
    $table->colclasses[] = 'text-right';         // attempt
    if ($binit) {
        $table->colclasses[] = 'text-right';     // score_i
    }
    $table->colclasses[] = 'text-right';         // score_s
    $table->colclasses[] = 'text-right';         // scoretot
    $table->colclasses[] = 'text-right';         // scoremax
    $table->colclasses[] = '';                   // details icon

    $table->attributes['class'] = 'admintable generaltable table-sm';

    $table->head = [];
    $table->head[] = $name;
    $table->head[] = $email;
    $table->head[] = $attempt;
    if ($binit) {
        $table->head[] = $scorei;
    }
    $table->head[] = $scores;
    if ($binit) {
        $table->head[] = $scoretot." (".get_string('calcolo'.$calcolo, 'mtcontabilita').")";
    } else {
        $table->head[] = $scoretot;
    }
    $table->head[] = $scoremax;
    $table->head[] = get_string('details');
    $table->colclasses[] = 'centeralign';

    $table->id = "users";
    foreach ($users as $user) {
        $buttons = [];

        $url = new moodle_url('details.php', ['tp' => 'i', 'attemptid' => $user->id, 'uid' => $user->userid, 'id' => $cmid]);
        $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('e/preview', $stredit));

        $somma = ($user->score_i + $user->score_s);
        $scoretotale = ($calcolo == 1) ? $somma : ($somma / 2);
        $row = [];
        $row[] = $user->name;
        $row[] = $user->email;
        $row[] = $user->attempt;
        if ($binit) {
            $row[] = $user->score_i;
        }
        $row[] = $user->score_s;
        $row[] = format_float($scoretotale, 2, false);
        $row[] = $valscoremax;
        $row[] = implode(' ', $buttons);
        $table->data[] = $row;
    }
}

if (!empty($table)) {
    echo html_writer::start_tag('div', array('class' => 'no-overflow'));
    echo html_writer::table($table);
    echo html_writer::end_tag('div');
    echo $OUTPUT->paging_bar($usercount, $page, $perpage, $returnurl);
}

echo $OUTPUT->footer();
