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

/**
 * Condition main class.
 *
 * @package availability_missingproctorreports
 * @copyright 2014 The Open University
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace availability_missingproctorreports;

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

/**
 * Condition main class.
 *
 * @package availability_missingproctorreports
 * @copyright 2014 The Open University
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class condition extends \core_availability\condition {

    /**
     * Saves tree data back to a structure object.
     *
     * @return \stdClass Structure object (ready to be made into JSON format)
     */
    public function save(){
        return (object)['type' => 'missingproctorreports'];
    }

    public function is_available($not, \core_availability\info $info, $grabthelot, $userid) {

        $context = $info->get_context();

        $allow = true;
        if (has_capability('availability/missingproctorreports:restrict', $context, $userid)) {

            // Get all groups the user belongs to.
            $groups = $info->get_modinfo()->get_groups();

            $cm = get_coursemodule_from_id('', $context->instanceid);

            if ($context->contextlevel == CONTEXT_MODULE && $groups && $cm->modname == 'quiz') {
                $instance = 0;
                if ($cm->modname == 'quiz') {
                    $instance = $cm->instance;
                }
                $allow = $this->has_missing_report($groups, $instance) ? false : true;
            }
        }

        // The NOT condition applies before accessallgroups (i.e. if you
        // set something to be available to those NOT in group X,
        // people with accessallgroups can still access it even if
        // they are in group X).
        if ($not) {
            $allow = !$allow;
        }

        return $allow;
    }

    public function get_description($full, $not, \core_availability\info $info) {
        return get_string($not ? 'notrequirestemreport' : 'requirestemreport',
            'availability_missingproctorreports');
    }
    /**
     * Obtains a representation of the options of this condition as a string,
     * for debugging.
     *
     * @return string Text representation of parameters
     */
    protected function get_debug_string(){
        return '';
    }


    /**
     * Returns a JSON object which corresponds to a condition of this type.
     *
     * Intended for unit testing, as normally the JSON values are constructed
     * by JavaScript code.
     *
     * @return \stdClass Object representing condition
     */
    public static function get_json() {
        return (object)['type' => 'missingproctorreports'];
    }

    /**
     * @param $groups
     * @param $quizid
     * @return bool
     * @throws \coding_exception
     * @throws \dml_exception
     */
    public function has_missing_report($groups, $quizid = 0) {
        global $DB;

        foreach ($groups as $key => $groupid) {
            if (!$DB->get_record('groups', ['id' => $groupid, 'schedule' => 2])) {
                unset($groups[$key]);
            }
        }

        if (empty($groups)) {
            return false;
        }

        list($insql, $params) = $DB->get_in_or_equal($groups);
        $params[] = $quizid;

        $sql = "SELECT s.id, r.id reportid
                  FROM {local_tem_session} s
             LEFT JOIN {local_tem_report} r
                    ON s.id = r.sessionid
                 WHERE r.id IS NULL
                   AND s.groupid {$insql}
                   AND s.quizid != ?
                   AND s.quizid NOT IN (SELECT cm.instance 
                                           FROM {tag_instance} ti
                                           JOIN {tag} t ON  ti.tagid = t.id
                                           JOIN {course_modules} cm ON ti.itemid = cm.id
                                           JOIN {modules} m ON cm.module= m.id
                                          WHERE ti.itemtype = 'course_modules' AND t.name = 'tem excluded' AND m.name = 'quiz')";

        return $DB->record_exists_sql($sql, $params);
    }
}
