<?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;
use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_value;

defined('MOODLE_INTERNAL') || die;

require_once($CFG->dirroot . '/mod/mtcontabilita/lib.php');

/**
 * external api class
 */
class external extends external_api {

    /**
     * Lista account.
     */
    protected static function get_listaccounts_parameters() {
        return new external_function_parameters([
            'term' => new external_value(PARAM_RAW, 'Search term', VALUE_DEFAULT, ''),
        ]);
    }

    /**
     * get listaccount
     */
    public static function get_listaccounts($term = '') {
        global $DB, $COURSE;

        $params = ['hidden' => 0, 'courseid' => $COURSE->id];
        $sql = "SELECT id, name FROM {mtcontabilita_list} WHERE hidden=:hidden AND courseid=:courseid";
        if ($term) {
            $sql .= " AND name LIKE ?";
            $params[] = "%$term%";
        }

        $results = [];
        $records = $DB->get_records_sql($sql . " ORDER BY name ASC", $params);

        foreach ($records as $rec) {
            $results[] = ['value' => $rec->id, 'label' => $rec->name];
        }

        return $results;
    }

    /**
     * get_listaccount
     */
    public static function get_listaccounts_returns() {
        return new external_multiple_structure(
            new external_single_structure([
                'value' => new external_value(PARAM_INT),
                'label' => new external_value(PARAM_TEXT),
            ])
        );
    }

    /**
     * get session
     */
    protected static function get_session_description_parameters() {
        $params = ['sessionid' => new external_value(PARAM_INT, 'The ID of the sessio to get description', VALUE_REQUIRED)];
        return new external_function_parameters($params);
    }

    /**
     * get session
     */
    public static function get_session_description(int $sessionid): string {
        global $PAGE;

        $params = self::validate_parameters(self::get_session_description_parameters(), ['sessionid' => $sessionid]);

        $session = mtcontabilita_get_session($params['sessionid']);
        $cm = get_coursemodule_from_instance('mtcontabilita', $session->mtcontabilitaid, 0, false, MUST_EXIST);
        $context = \context_module::instance($cm->id);

        self::validate_context($context);
        \mod_mtcontabilita\permission::require_can_view_mtcontabilita($context);

        $output = $PAGE->get_renderer('mod_mtcontabilita');

        $description = new \mod_mtcontabilita\output\session_description_modal($session, $context);

        return $output->render_from_template('mod_mtcontabilita/session_description_modal',
            $description->export_for_template($output));
    }

    /**
     * get desc
     */
    public static function get_session_description_returns() {
        return new external_value(PARAM_RAW, 'Session description in HTML.');
    }

    /**
     * Returns the structure of parameters for user_signup function.
     * @return external_function_parameters
     */
    protected static function user_signup_parameters() {
        $params = [
            'sessionid' => new external_value(PARAM_INT, 'The ID of the session to signup for', VALUE_REQUIRED),
        ];
        return new external_function_parameters($params);
    }

    /**
     * Signup for the session.
     *
     *
     * @param int $sessionid The ID of the session
     * @return bool
     */
    public static function user_signup($sessionid) {
        $params = self::validate_parameters(self::user_signup_parameters(), [
            'sessionid' => $sessionid,
        ]);

        $session = mtcontabilita_get_session($params['sessionid']);
        $cm = get_coursemodule_from_instance('mtcontabilita', $session->mtcontabilitaid);
        $context = \context_module::instance($cm->id);

        self::validate_context($context);
        \mod_mtcontabilita\permission::require_can_signup($session, $context);

        attendee::signup_self($session, $context);
        return true;
    }

    /**
     * Describes the return function of user_signup
     *
     * @return external_value
     */
    public static function user_signup_returns() {
        return new external_value(PARAM_BOOL, 'Returns true on successful sign up or throws an error');
    }

    /**
     * Returns the structure of parameters for user_cancel function.
     * @return external_function_parameters
     */
    protected static function user_cancel_parameters() {
        $params = [
            'sessionid' => new external_value(PARAM_INT, 'The ID of the session to cancel booking for', VALUE_REQUIRED),
            'cancelreason' => new external_value(PARAM_TEXT, 'Reason of session booking cancellation', VALUE_DEFAULT, ''),
        ];
        return new external_function_parameters($params);
    }

    /**
     * Cancel session booking.
     *
     * @param int $sessionid The ID of the session
     * @param string $cancelreason Optional justification for cancelling the signup
     * @return bool
     */
    public static function user_cancel($sessionid, $cancelreason) {
        $params = self::validate_parameters(self::user_cancel_parameters(), [
            'sessionid' => $sessionid,
            'cancelreason' => $cancelreason,
        ]);

        $session = mtcontabilita_get_session($params['sessionid']);
        $cm = get_coursemodule_from_instance('mtcontabilita', $session->mtcontabilitaid);
        $context = \context_module::instance($cm->id);

        self::validate_context($context);
        \mod_mtcontabilita\permission::require_can_cancel_signup($session, $context);

        attendee::cancel_self($session, $context, $params['cancelreason']);
        return true;
    }

    /**
     * Describes the return function of user_cancel
     *
     * @return external_value
     */
    public static function user_cancel_returns() {
        return new external_value(PARAM_BOOL, 'True if successfully cancelled session booking or throws an error');
    }
}
