<?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');
require_once($CFG->dirroot . '/mod/mtcontabilita/lib.php');
require_once($CFG->dirroot.'/mod/mtcontabilita/locallib.php');
require_once($CFG->dirroot.'/mod/mtcontabilita/manage/filters/lib.php');

$id = required_param('id', PARAM_INT); // Course Id.
$course = get_course($id);
require_course_login($course, false);
$context = context_course::instance($course->id);
if (!has_capability('mod/mtcontabilita:addinstance', $context)) {
    throw new \moodle_exception('nopermissions', 'error', '', get_string('nopermissions', 'mod_mtcontabilita'));
}

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

$delete       = optional_param('delete', 0, PARAM_INT);
$confirm      = optional_param('confirm', '', PARAM_ALPHANUM);
$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);
$action = optional_param('action', '', PARAM_ALPHA);

$stredit   = get_string('edit');
$strdelete = get_string('delete');
$strshow = get_string('show');
$strhide = get_string('hide');
$strsuspend = get_string('suspenduser', 'admin');

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

$mtc = new \mtcontabilita();

switch ($action) {
    case 'hide':
        $iid  = required_param('iid', PARAM_INT);
        $DB->set_field('mtcontabilita_list', 'hidden', 1, ['id' => $iid]);
        break;
    case 'show':
        $iid  = required_param('iid', PARAM_INT);
        $DB->set_field('mtcontabilita_list', 'hidden', 0, ['id' => $iid]);
        break;
}

if ($delete && confirm_sesskey()) {
    if ($confirm != md5($delete)) {
        echo $OUTPUT->header();
        echo $OUTPUT->heading(get_string('deleteuser', 'admin'));
        $optionsyes = array('delete' => $delete, 'confirm' => md5($delete), 'sesskey' => sesskey());
        $deleteurl = new moodle_url($returnurl, $optionsyes);
        $deletebutton = new single_button($deleteurl, get_string('delete'), 'post');

        echo $OUTPUT->confirm(get_string('deleteaccountconfirm', 'mtcontabilita'), $deletebutton, $returnurl);
        echo $OUTPUT->footer();
        die;
    } else if (data_submitted()) {
        $DB->delete_records('mtcontabilita_list', ['id' => $delete]);
        // \core\session\manager::gc(); // Remove stale sessions.
        $params = [
            'context' => $context,
            'objectid' => $delete,
            'courseid' => $id,
        ];
        $event = \mod_mtcontabilita\event\delete_conto::create($params);
        $event->trigger();

        redirect($returnurl);
    }
}

$ufiltering = new mtmanage_filtering(null, $CFG->wwwroot."/mod/mtcontabilita/manage/?id=".$id);

echo $OUTPUT->header();

$columns = ['denominazioneconto', 'scheme', 'nature', 'macroclasse', 'lang'];

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=$id&sort=$column&amp;dir=$columndir\">".$string[$column]."</a>$columnicon";
}

list($extrasql, $params) = $ufiltering->get_sql_filter();

$users = mtcontabilita_manage::get_users_listing($id, $sort, $dir, $page * $perpage, $perpage, '', '', '',
        $extrasql, $params, $context);
$usercount = mtcontabilita_manage::get_users($id, false, '', false, null, '', '', '', '', '', '*', $extrasql, $params);

// $baseurl = new moodle_url('index.php', array('sort' => $sort, 'dir' => $dir, 'perpage' => $perpage));
echo $OUTPUT->paging_bar($usercount, $page, $perpage, $returnurl);

flush();

if (!$users) {
    $match = array();
    echo $OUTPUT->heading(get_string('nousersfound'));

    $table = null;

} else {

    $table = new html_table();
    $table->head = [];
    $table->colclasses = [];
    $table->attributes['class'] = 'admintable generaltable table-sm';

    $table->head[] = $denominazioneconto;
    $table->head[] = $scheme;
    $table->head[] = $nature;
    $table->head[] = $macroclasse;
    $table->head[] = $lang;
    $table->head[] = get_string('edit');
    // $table->colclasses[4] = 'centeralign';

    $table->id = "users";
    foreach ($users as $user) {
        $buttons = array();
        // $lastcolumn = '';

        $url = new moodle_url('edit.php', array('cid' => $id, 'id' => $user->id));
        $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/edit', $stredit));

        if ((bool)$user->hidden == 0) {
            $url = new moodle_url($returnurl, array('action' => 'hide', 'iid' => $user->id, 'sesskey' => sesskey()));
            $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/hide', $strshow));
        } else {
            $url = new moodle_url($returnurl, array('action' => 'show', 'iid' => $user->id, 'sesskey' => sesskey()));
            $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/show', $strhide));
        }

        if (!$DB->record_exists('mtcontabilita_itemdet', ['listid' => $user->id])) {
            $url = new moodle_url($returnurl, array('delete' => $user->id, 'sesskey' => sesskey()));
            $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/delete', $strdelete));
        }

        $row = array ();
        $row[] = $user->name;
        // $row[] = mtcontabilita_manage::get_type($user->type);
        $row[] = get_string(strtolower(@$user->scheme), 'mtcontabilita');
        $row[] = $mtc->get_nature_list($user->nature);
        $row[] = $mtc->get_macroclasse_list($user->macroclasse);
        $row[] = $user->lang;
        $row[] = implode(' ', $buttons);
        // $row[] = $lastcolumn;
        $table->data[] = $row;
    }
}

$ufiltering->display_add();
$ufiltering->display_active();

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);
}

$url = new moodle_url('edit.php', array('cid' => $id, 'id' => 0));
echo '<a href="'.$url.'" class="btn btn-primary">'.get_string('add').'</a>&nbsp;';
$exporturl = new moodle_url('csv.php', ['id' => $id, 'sort' => $sort, 'dir' => $dir]);
echo html_writer::link($exporturl, get_string('export', 'mtcontabilita'), ['class' => 'btn btn-success']);

echo $OUTPUT->footer();
