<?php
// This file is part of MuTMS suite of plugins for Moodle™ LMS.
//
// This program 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.
//
// This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.

// phpcs:disable moodle.Files.BoilerplateComment.CommentEndedTooSoon
// phpcs:disable moodle.Files.LineLength.TooLong

namespace tool_mucertify\external;

use core_external\external_function_parameters;
use core_external\external_value;

/**
 * Provides list of candidates for certification assignment.
 *
 * @package     tool_mucertify
 * @copyright   2023 Open LMS (https://www.openlms.net/)
 * @author      Petr Skoda
 * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
final class form_source_manual_assign_users extends \tool_mulib\external\form_autocomplete_field {
    /**
     * True means returned field data is array, false means value is scalar.
     *
     * @return bool
     */
    public static function is_multi_select_field(): bool {
        return true;
    }

    /**
     * Describes the external function arguments.
     *
     * @return external_function_parameters
     */
    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'query' => new external_value(PARAM_RAW, 'The search query', VALUE_REQUIRED),
            'certificationid' => new external_value(PARAM_INT, 'Certification id', VALUE_REQUIRED),
        ]);
    }

    /**
     * Finds users with the identity matching the given query.
     *
     * @param string $query The search request.
     * @param int $certificationid The certification.
     * @return array
     */
    public static function execute(string $query, int $certificationid): array {
        global $DB, $CFG, $OUTPUT;

        ['query' => $query, 'certificationid' => $certificationid] = self::validate_parameters(
            self::execute_parameters(), ['query' => $query, 'certificationid' => $certificationid]);

        $certification = $DB->get_record('tool_mucertify_certification', ['id' => $certificationid], '*', MUST_EXIST);

        // Validate context.
        $context = \context::instance_by_id($certification->contextid);
        self::validate_context($context);
        require_capability('tool/mucertify:assign', $context);

        $fields = \core_user\fields::for_name()->with_identity($context, false);
        $extrafields = $fields->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]);

        list($searchsql, $searchparams) = users_search_sql($query, 'usr', true, $extrafields);
        list($sortsql, $sortparams) = users_order_by_sql('usr', $query, $context);
        $params = array_merge($searchparams, $sortparams);
        $params['certificationid'] = $certificationid;

        $tenantwhere = "";
        if (\tool_mucertify\local\util::is_mutenancy_active()) {
            $tenantwhere = \tool_mutenancy\local\tenancy::get_related_users_exists('usr.id', $context);
        }

        $additionalfields = $fields->get_sql('usr')->selects;
        $sqlquery = <<<SQL
            SELECT usr.id {$additionalfields}
              FROM {user} usr
         LEFT JOIN {tool_mucertify_assignment} pa ON (pa.userid = usr.id AND pa.certificationid = :certificationid)
             WHERE pa.id IS NULL AND {$searchsql} {$tenantwhere}
                   AND usr.deleted = 0 AND usr.confirmed = 1
          ORDER BY {$sortsql}
SQL;

        $rs = $DB->get_recordset_sql($sqlquery, $params, 0, $CFG->maxusersperpage + 1);

        return self::prepare_user_list($rs, $extrafields);
    }

    /**
     * Return function that return label for given value.
     *
     * @param array $arguments
     * @return callable
     */
    public static function get_label_callback(array $arguments): callable {
        return function($value) use ($arguments): string {
            global $DB;

            $certification = $DB->get_record('tool_mucertify_certification', ['id' => $arguments['certificationid']], '*', MUST_EXIST);
            $context = \context::instance_by_id($certification->contextid);

            $error = null; // This is not pretty, but luckily there is a low chance this will happen.
            if (static::validate_form_value($arguments, $value, $context) !== null) {
                $error = ' (' . get_string('error') .')';
            }

            $record = $DB->get_record('user', ['id' => $value]);

            return self::prepare_user_label($record, $context, $error);
        };
    }

    /**
     * Validate data.
     *
     * @param array $arguments
     * @param mixed $value
     * @param \context $context
     * @return string|null error message, NULL means value is ok
     */
    public static function validate_form_value(array $arguments, $value, \context $context): ?string {
        global $DB;

        $user = $DB->get_record('user', ['id' => $value, 'deleted' => 0, 'confirmed' => 1]);
        if (!$user) {
            return get_string('error');
        }

        if ($DB->record_exists('tool_mucertify_assignment', ['certificationid' => $arguments['certificationid'], 'userid' => $user->id])) {
            return get_string('error');
        }

        if (\tool_mucertify\local\util::is_mutenancy_active()) {
            if ($context->tenantid) {
                $usertenantid = \tool_mutenancy\local\tenancy::get_user_tenantid($user->id);
                if ($usertenantid && $usertenantid != $context->tenantid) {
                    return get_string('error');
                }
            }
        }

        return null;
    }
}
