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

namespace mod_mtcontabilita\local\helpers;

use lang_string;
use tool_reportbuilder\constants;
use tool_reportbuilder\entity_base;
use tool_reportbuilder\local\filter\checkbox;
use tool_reportbuilder\local\filter\number;
use tool_reportbuilder\local\filter\select;
use tool_reportbuilder\local\helpers\columns;
use tool_reportbuilder\local\helpers\customfields;
use tool_reportbuilder\local\helpers\format;
use tool_reportbuilder\report_column;
use tool_reportbuilder\report_filter;

/**
 * Columns, filters and conditions that defines the mtcontabilita_entity and can be reused in any report datasource
 *
 * @package     mod_mtcontabilita
 * @copyright   2019 Moodle Pty Ltd <support@moodle.com>
 * @author      2019 David Matamoros <davidmc@moodle.com>
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class mtcontabilita_entity extends entity_base {
    /** @var customfields */
    protected $customfields;

    /**
     * Which entity class from core reportbuilder should this entity be migrated to
     *
     * @return string name of the class extending {@see \core_reportbuilder\local\entities\entity_base}
     */
    public function convert_get_entity_class(): string {
        return \mod_mtcontabilita\reportbuilder\local\entities\session::class;
    }

    /**
     * Allows to map custom/profile fields during conversion to core reportbuilder
     *
     * @param string $oldfieldname the current column/filter/condition name
     * @return string the identifier of the corresponding column/filter/condition in the converted datasource entity
     */
    protected function convert_get_generic_field_name(string $oldfieldname): string {
        $oldprefix = $this->get_table_alias('mtcontabilita_sessions') . 'id';
        $cfhandler = \core_customfield\handler::get_handler('mod_mtcontabilita', 'mtcontabilita');
        return $this->convert_get_custom_field_name($cfhandler, $oldfieldname, $oldprefix) ?? $oldfieldname;
    }

    /**
     * Database tables that this entity uses and their default aliases
     *
     * @return array
     */
    protected function get_default_table_aliases(): array {
        return [
            'mtcontabilita_sessions' => 'aps',
            'mtcontabilita_sessions_dates' => 'apsd',
        ];
    }

    /**
     * The default machine-readable name for this entity that will be used in the internal names of the columns/filters
     *
     * @return string
     */
    protected function get_default_entity_name(): string {
        return 'mtcontabilita';
    }

    /**
     * The default title for this entity in the list of columns/conditions/filters in the report builder
     *
     * @return \lang_string
     */
    protected function get_default_entity_title(): \lang_string {
        return new \lang_string('mtcontabilita', 'mod_mtcontabilita');
    }

    /**
     * Executed when entity is added to the datasource or system report
     */
    public function add_to_report() {
        $columns = array_merge($this->get_all_columns(), $this->get_custom_fields()->get_columns());
        foreach ($columns as $column) {
            $this->add_column($column);
        }

        $conditions = array_merge($this->get_filters_or_conditions(true), $this->get_custom_fields()->get_conditions());
        foreach ($conditions as $condition) {
            $this->add_condition($condition);
        }

        $filters = array_merge($this->get_filters_or_conditions(false), $this->get_custom_fields()->get_filters());
        foreach ($filters as $filter) {
            $this->add_filter($filter);
        }
    }

    /**
     * Get the custom fields helper
     *
     * @return customfields
     */
    protected function get_custom_fields(): customfields {
        if ($this->customfields === null) {
            $tablealias = $this->get_table_alias('mtcontabilita_sessions');
            $this->customfields = new customfields($tablealias . '.id', $this->get_entity_name(),
                'mod_mtcontabilita', 'mtcontabilita', 0);
            $this->customfields->add_joins($this->get_joins());
        }
        return $this->customfields;
    }

    /**
     * Returns list of all available columns
     *
     * @return report_column[]
     */
    protected function get_all_columns(): array {
        global $DB;

        $dbfamily = $DB->get_dbfamily();

        $tablealias = $this->get_table_alias('mtcontabilita_sessions');
        $columns = [];

        // Column description.
        $newcolumn = (new report_column(
            'description',
            new lang_string('description'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->add_join("LEFT JOIN {modules} m ON m.name = 'mtcontabilita'")
            ->add_join("LEFT JOIN {course_modules} cm ON $tablealias.mtcontabilitaid = cm.instance
            AND cm.course = c.id AND cm.module = m.id")
            ->set_type(constants::DB_TYPE_LONGTEXT)
            ->add_field("$tablealias.description")
            ->add_field("$tablealias.descriptionformat")
            ->add_field("$tablealias.mtcontabilita", 'mtcontabilitaid')
            ->add_field('cm.id')
            ->add_callback([mtcontabilita_format::class, 'description']);
        $columns[] = $newcolumn;
        // Column allowwaitlist.
        $newcolumn = (new report_column(
            'allowwaitlist',
            new lang_string('allowwaitlist', 'mod_mtcontabilita'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->set_type(constants::DB_TYPE_BOOLEAN)
            ->add_field("$tablealias.allowwaitlist")
            ->add_callback([format::class, 'checkbox_as_text']);
        $columns[] = $newcolumn;

        // Column allowcancellations.
        $newcolumn = (new report_column(
            'allowcancellations',
            new lang_string('allowcancellations', 'mod_mtcontabilita'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->set_type(constants::DB_TYPE_BOOLEAN)
            ->add_field("$tablealias.allowcancellations")
            ->add_callback([format::class, 'checkbox_as_text']);
        $columns[] = $newcolumn;

        // Bookings query.
        $bookingsquery = self::get_bookings_query($tablealias);

        // Column seatsbooked.
        $newcolumn = (new report_column(
            'seatsbooked',
            new lang_string('seatsbooked', 'mod_mtcontabilita'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->set_type(constants::DB_TYPE_NUMBER)
            ->add_field($bookingsquery, 'seatsbooked');

        if ($dbfamily === 'mssql' || $dbfamily === 'oracle') {
            $newcolumn->set_groupby_sql("{$tablealias}.id");
        }
        if ($dbfamily === 'mssql') {
            columns::disable_column_aggregation($newcolumn);
        }
        $columns[] = $newcolumn;
        // Column mtcontabilita status.
        $newcolumn = (new report_column(
            'status',
            new lang_string('status', 'mod_mtcontabilita'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->set_type(constants::DB_TYPE_TEXT)
            ->add_field("$tablealias.id", 'sessionid')
            ->add_callback([mtcontabilita_format::class, 'sessionstatus']);
        $columns[] = $newcolumn;

        return $columns;
    }

    /**
     * Filters/conditions for programs.
     *
     * @param bool $iscondition
     * @return array
     */
    protected function get_filters_or_conditions(bool $iscondition): array {
        $tablealias = $this->get_table_alias('mtcontabilita_sessions');
        $filters = [];

        // Filter allowwaitlist.
        $filters[] = (new report_filter(
            checkbox::class,
            'allowwaitlist',
            new lang_string('allowwaitlist', 'mod_mtcontabilita'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->set_field_sql("$tablealias.allowwaitlist");

        // Filter allowcancellations.
        $filters[] = (new report_filter(
            checkbox::class,
            'allowcancellations',
            new lang_string('allowcancellations', 'mod_mtcontabilita'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->set_field_sql("$tablealias.allowcancellations");

        // Bookings query.
        $bookingsquery = self::get_bookings_query($tablealias);

        // Filter seatsbooked.
        $filters[] = (new report_filter(
            number::class,
            'seatsbooked',
            new lang_string('seatsbooked', 'mod_mtcontabilita'),
            $this->get_entity_name()
        ))
            ->add_joins($this->get_joins())
            ->set_field_sql($bookingsquery);

        return $filters;
    }

    /**
     * Returns session availability statuses for filter
     *
     * @return array
     */
    public static function get_sessionavailability_statuses(): array {
        return [
            1 => get_string('fullfilter', 'mod_mtcontabilita'),
            2 => get_string('empty', 'mod_mtcontabilita'),
            3 => get_string('partiallyfull', 'mod_mtcontabilita'),
        ];
    }

    /**
     * Returns a query to retrieve not cancelled session bookings.
     *
     * @param string $tablealias
     * @return string
     */
    private static function get_bookings_query(string $tablealias): string {
        $excludestatuses = [
            MOD_MTCONTABILITA_STATUS_USER_CANCELLED,
            MOD_MTCONTABILITA_STATUS_DECLINED,
            MOD_MTCONTABILITA_STATUS_REQUESTED,
            MOD_MTCONTABILITA_STATUS_WAITLISTED,
        ];
        $excludesql = 'NOT IN (' . implode(',', $excludestatuses) . ')';

        // Bookings query.
        return "(
            SELECT COUNT(asu.id)
              FROM {mtcontabilita_signups} asu
              JOIN {mtcontabilita_signups_status} asus
                ON asu.id = asus.signupid
              JOIN (
                SELECT signupid, max(timecreated) AS timecreated
                  FROM {mtcontabilita_signups_status}
              GROUP BY signupid
                 ) asus2
                ON asus.signupid = asus2.signupid AND asus.timecreated = asus2.timecreated
             WHERE asus.statuscode {$excludesql} AND asu.sessionid = {$tablealias}.id)";
    }
}
