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

declare(strict_types=1);

namespace mod_mtcontabilita\reportbuilder\local\systemreports;

use context_module;
use lang_string;
use stdClass;
use core_reportbuilder\system_report;
use core_reportbuilder\local\report\filter;
use mod_mtcontabilita\output\sessions_list_item;
use mod_mtcontabilita\reportbuilder\local\entities\session_date;
use mod_mtcontabilita\reportbuilder\local\filters\datestart;

/**
 * sessions class
 */
class sessions extends system_report {

    /** @var customfields */
    protected $currentsession = null;
    /** @var customfields */
    protected $usersubmission = false;

    /**
     * initialise
     */
    protected function initialise(): void {
        $mtcontabilitaid = $this->get_parameter('mtcontabilitaid', 0, PARAM_INT);
        [$course, $coursemodule] = get_course_and_cm_from_instance($mtcontabilitaid, 'mtcontabilita');

        $this->set_main_table('mtcontabilita_item', 's');

        $this->add_base_condition_simple('s.mtcontabilitaid', $mtcontabilitaid);

        // Add required fields for actions/callbacks.
        $this->add_base_fields('s.id');

        // Prepare data.
        $this->set_usersubmission($mtcontabilitaid);

        // Add session date entity.
        $sessiondateentity = new session_date();
        $sessiondatealias = $sessiondateentity->get_table_alias('mtcontabilita_itemdet');

        $this->add_entity($sessiondateentity
            ->add_join("LEFT JOIN (
                    SELECT mtcontabilitaid, itemdate
                      FROM {mtcontabilita_itemdet}
                  GROUP BY mtcontabilitaid
              ) {$sessiondatealias} ON {$sessiondatealias}.mtcontabilitaid = s.id"));

        $this->add_columns($coursemodule->context);
        $this->add_filters($sessiondateentity);

        $this->set_downloadable(false);
    }

    /**
     * per page
     */
    public function get_default_per_page(): int {
        return 10;
    }

    /**
     * set submission
     */
    private function set_usersubmission($mtcontabilitaid) {
        global $USER;
        if ($submissions = mtcontabilita_get_user_submissions($mtcontabilitaid, $USER->id)) {
            $this->usersubmission = array_shift($submissions);
        }
    }

    /**
     * col container
     */
    public function col_container(?int $timestart, stdClass $row, context_module $contextmodule): string {
        global $OUTPUT, $PAGE;

        $context = new sessions_list_item($this->currentsession, $this->usersubmission, $contextmodule);
        $renderer = $PAGE->get_renderer('core');

        return $OUTPUT->render_from_template('mod_mtcontabilita/session_item/main', $context->export_for_template($renderer));
    }

    /**
     * Validates access to view this report with the given parameters
     */
    public function can_view(): bool {
        $mtcontabilitaid = $this->get_parameter('mtcontabilitaid', 0, PARAM_INT);
        [$course, $coursemodule] = get_course_and_cm_from_instance($mtcontabilitaid, 'mtcontabilita');

        return \mod_mtcontabilita\permission::can_view_mtcontabilita($coursemodule->context);
    }

    /**
     * Adds report columns
     *
     * @param context_module $context
     */
    protected function add_columns(context_module $context): void {
        $this->add_column_from_entity('session_date:datestart')
            ->set_callback([$this, 'col_container'], $context);

        $this->set_initial_sort_column('session_date:datestart', SORT_ASC);
    }

    /**
     * Adds report filters
     *
     * @param session_date $sessiondateentity
     */
    protected function add_filters(session_date $sessiondateentity): void {

    }

    /**
     * Get data prior to row rendering.
     *
     * @param \stdClass $row
     */
    public function row_callback(\stdClass $row): void {
        $this->currentsession = mtcontabilita_get_session($row->id);
    }

    /**
     * Remove the table-stripped and table-hover effects.
     *
     * @param stdClass $row
     * @return string
     */
    public function get_row_class(stdClass $row): string {
        return 'bg-white session-row';
    }
}
