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

namespace mod_booking;

use mod_booking\subscriber_selector_base;

/**
 * User selector control for removing subscribed users
 *
 * @package mod_booking
 * @copyright 2014 Andraž Prinčič
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class existing_subscriber_selector extends subscriber_selector_base {
    /**
     * Finds all subscribed users
     *
     * @param string $search
     * @return array
     */
    public function find_users($search) {
        global $DB;
        [$wherecondition, $params] = $this->search_sql($search, 'u');
        $params['optionid'] = $this->optionid;

        $fields = $this->required_fields_sql('u');
        [$sort, $sortparams] = users_order_by_sql('u', $search, $this->accesscontext);
        $params = array_merge($params, $sortparams);

        $subscribers = $DB->get_records_sql(
            "SELECT $fields
                FROM {user} u
                JOIN {booking_teachers} s ON s.userid = u.id
                WHERE $wherecondition AND s.optionid = :optionid
                ORDER BY $sort",
            $params
        );

        return [get_string("existingsubscribers", 'booking') => $subscribers];
    }
}
