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

defined('MOODLE_INTERNAL') || die();

require_once($CFG->dirroot.'/mod/mtcontabilita/manage/filters/text.php');
require_once($CFG->dirroot.'/mod/mtcontabilita/manage/filters/select.php');
require_once($CFG->dirroot.'/mod/mtcontabilita/manage/filters/simpleselect.php');
require_once($CFG->dirroot.'/mod/mtcontabilita/manage/filters/mtmanage_filter_forms.php');

/**
 * mtmanage_filtering class
 */
class mtmanage_filtering {

    /** @var var */
    public $_fields;
    /** @var var */
    public $_addform;
    /** @var var */
    public $_activeform;

    /**
     * construct
     */
    public function __construct($fieldnames = null, $baseurl = null, $extraparams = null) {
        global $SESSION;
        if (!isset($SESSION->user_filtering)) {
            $SESSION->user_filtering = array();
        }

        if (empty($fieldnames)) {
            // As a start, add all fields as advanced fields (which are only available after clicking on "Show more").
            $fieldnames = array('name' => 0, 'scheme' => 0, 'nature' => 0, 'macroclasse' => 0, 'lang' => 0);
            // Get the config which filters the admin wanted to show by default.
            $userfiltersdefault = get_config('core', 'userfiltersdefault');

            // If the admin did not enable any filter, the form will not make much sense if all fields are hidden behind
            // "Show more". Thus, we enable the 'name' filter automatically.
            if ($userfiltersdefault == '') {
                $userfiltersdefault = array('name');

                // Otherwise, we split the enabled filters into an array.
            } else {
                $userfiltersdefault = explode(',', $userfiltersdefault);
            }

            // Show these fields by default which the admin has enabled in the config.
            foreach ($userfiltersdefault as $key) {
                $fieldnames[$key] = 0;
            }
        }

        $this->_fields  = array();

        foreach ($fieldnames as $fieldname => $advanced) {
            if ($field = $this->get_field($fieldname, $advanced)) {
                $this->_fields[$fieldname] = $field;
            }
        }

        // Fist the new filter form.
        $this->_addform = new mtmanage_add_filter_form($baseurl, array('fields' => $this->_fields, 'extraparams' => $extraparams));
        if ($adddata = $this->_addform->get_data()) {
            // Clear previous filters.
            if (!empty($adddata->replacefilters)) {
                $SESSION->user_filtering = [];
            }

            // Add new filters.
            foreach ($this->_fields as $fname => $field) {
                $data = $field->check_data($adddata);
                if ($data === false) {
                    continue; // Nothing new.
                }
                if (!array_key_exists($fname, $SESSION->user_filtering)) {
                    $SESSION->user_filtering[$fname] = array();
                }
                $SESSION->user_filtering[$fname][] = $data;
            }
        }

        // Now the active filters.
        $this->_activeform = new mtmanage_active_filter_form($baseurl, array('fields' => $this->_fields, 'extraparams' => $extraparams));
        if ($activedata = $this->_activeform->get_data()) {
            if (!empty($activedata->removeall)) {
                $SESSION->user_filtering = array();
            } else if (!empty($activedata->removeselected) && !empty($activedata->filter)) {
                foreach ($activedata->filter as $fname => $instances) {
                    foreach ($instances as $i => $val) {
                        if (empty($val)) {
                            continue;
                        }
                        unset($SESSION->user_filtering[$fname][$i]);
                    }
                    if (empty($SESSION->user_filtering[$fname])) {
                        unset($SESSION->user_filtering[$fname]);
                    }
                }
            }
        }

        // Rebuild the forms if filters data was processed.
        if ($adddata || $activedata) {
            $_POST = []; // Reset submitted data.
            $this->_addform = new mtmanage_add_filter_form($baseurl, ['fields' => $this->_fields, 'extraparams' => $extraparams]);
            $this->_activeform = new mtmanage_active_filter_form($baseurl, ['fields' => $this->_fields, 'extraparams' => $extraparams]);
        }
    }

    /**
     * Creates known user filter if present
     * @param string $fieldname
     * @param boolean $advanced
     * @return object filter
     */
    public function get_field($fieldname, $advanced) {
        global $USER, $CFG, $DB, $SITE;

        $mtc = new \mtcontabilita();
        $opt = $mtc->get_scheme_list();
        $opt2 = $mtc->get_nature_list();
        $optl = ['' => get_string('choose'), 'it' => 'IT', 'en' => 'EN'];

        $titscheme2 = " (".get_string('ce', 'mtcontabilita')."/".get_string('sp', 'mtcontabilita').")";
        switch ($fieldname) {
            case 'name':
                return new mtmanage_filter_text('name', get_string('denominazioneconto', 'mtcontabilita'), $advanced, 'name');
            case 'lang':
                return new mtmanage_filter_select('lang', get_string('lang', 'mtcontabilita'), $advanced, 'lang', $optl, '');
            case 'scheme':
                return new mtmanage_filter_select('scheme', get_string('scheme', 'mtcontabilita').$titscheme2, $advanced, 'scheme', $opt, '');
            case 'nature':
                return new mtmanage_filter_select('nature', get_string('nature', 'mtcontabilita'), $advanced, 'nature', $opt2, '');
            case 'macroclasse':
                return new mtmanage_filter_text('macroclasse', get_string('macroclasse', 'mtcontabilita'), $advanced, 'macroclasse');
            default:
                return null;
        }
    }

    /**
     * Returns sql where statement based on active user filters
     * @param string $extra sql
     * @param array $params named params (recommended prefix ex)
     * @return array sql string and $params
     */
    public function get_sql_filter($extra='', array $params=null) {
        global $SESSION;

        $sqls = array();
        if ($extra != '') {
            $sqls[] = $extra;
        }
        $params = (array)$params;

        if (!empty($SESSION->user_filtering)) {
            foreach ($SESSION->user_filtering as $fname => $datas) {
                if (!array_key_exists($fname, $this->_fields)) {
                    continue; // Filter not used.
                }
                $field = $this->_fields[$fname];
                foreach ($datas as $i => $data) {
                    list($s, $p) = $field->get_sql_filter($data);
                    $sqls[] = $s;
                    $params = $params + $p;
                }
            }
        }

        if (empty($sqls)) {
            return array('', array());
        } else {
            $sqls = implode(' AND ', $sqls);
            return array($sqls, $params);
        }
    }

    /**
     * Print the add filter form.
     */
    public function display_add() {
        $this->_addform->display();
    }

    /**
     * Print the active filter form.
     */
    public function display_active() {
        $this->_activeform->display();
    }

}

/**
 * The base user filter class. All abstract classes must be implemented.
 *
 * @copyright 1999 Martin Dougiamas  http://dougiamas.com
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class mtmanage_filter_type {
    /**
     * The name of this filter instance.
     * @var string
     */
    public $_name;

    /**
     * The label of this filter instance.
     * @var string
     */
    public $_label;

    /**
     * Advanced form element flag
     * @var bool
     */
    public $_advanced;

    /**
     * Constructor
     * @param string $name the name of the filter instance
     * @param string $label the label of the filter instance
     * @param boolean $advanced advanced form element flag
     */
    public function __construct($name, $label, $advanced) {
        $this->_name     = $name;
        $this->_label    = $label;
        $this->_advanced = $advanced;
    }

    /**
     * Old syntax of class constructor. Deprecated in PHP7.
     *
     * @deprecated since Moodle 3.1
     */
    public function mtmanage_filter_type($name, $label, $advanced) {
        debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
        self::__construct($name, $label, $advanced);
    }

    /**
     * Returns the condition to be used with SQL where
     * @param array $data filter settings
     * @return string the filtering condition or null if the filter is disabled
     */
    public function get_sql_filter($data) {
        throw new \moodle_exception('mustbeoveride', 'debug', '', 'get_sql_filter');
    }

    /**
     * Retrieves data from the form data
     * @param stdClass $formdata data submited with the form
     * @return mixed array filter data or false when filter not set
     */
    public function check_data($formdata) {
        throw new \moodle_exception('mustbeoveride', 'debug', '', 'check_data');
    }

    /**
     * Adds controls specific to this filter in the form.
     * @param moodleform $mform a MoodleForm object to setup
     */
    public function setupForm(&$mform) {
        throw new \moodle_exception('mustbeoveride', 'debug', '', 'setupForm');
    }

    /**
     * Returns a human friendly description of the filter used as label.
     * @param array $data filter settings
     * @return string active filter label
     */
    public function get_label($data) {
        throw new \moodle_exception('mustbeoveride', 'debug', '', 'get_label');
    }
}
