<?php
// This file is part of the Studyplan plugin for Moodle
//
// 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 <https://www.gnu.org/licenses/>.

/**
 * Manage mandatory studyplan sharing for users
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

use local_treestudyplan\form\selectuser_form;
use core\context\system as context_system;

require_once("../../config.php");
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->libdir . '/form/autocomplete.php');
admin_externalpage_setup("local_treestudyplan_manageshares");

// Check if user has capability to manage this.
$systemcontext = context_system::instance();
require_capability('local/treestudyplan:manageshares', $systemcontext);

if ($CFG->debugdeveloper) {
    $PAGE->requires->css(new moodle_url($CFG->wwwroot . '/local/treestudyplan/styles.css'));
}


if (!get_config("local_treestudyplan", "enableplansharing")) {
    $PAGE->set_title(get_string('accessdenied', 'admin'));
    $PAGE->set_heading(get_string('accessdenied', 'admin'));

    print $OUTPUT->header();
    print $OUTPUT->render_from_template('local_treestudyplan/error', [
        "title" => get_string('accessdenied', 'admin'),
        "message" => get_string('error:invitationsdisabled', 'local_treestudyplan'),
    ]);
    print $OUTPUT->footer();

    exit; // Just in case some code is added after this if statement erroneously later.
} else {
    // Check if we have a sent confirmation.
    $sent = optional_param('sent', '', PARAM_INT);
    if (!empty($sent)) {
        $invite = $DB->get_record('local_treestudyplan_invit', ['id' => $sent]);
        $invuser = $DB->get_record('user', ['id' => $invite->user_id]);
        $invite->username = \core_user::get_fullname($invuser); // Add username field to record.
        \core\notification::success(get_string('invite_manage_resent_msg', 'local_treestudyplan', $invite));
    };

    $userid = optional_param('userid', 0, PARAM_INT);     // Module name.
    $user = $DB->get_record('user', ['id' => $userid]);

    print $OUTPUT->header();

    $selectuserform = new selectuser_form(get_string('invite_manage_selectuser', 'local_treestudyplan'));
    if ($user) {
        $selectuserform->set_selected_user($user);
        $username = \core_user::get_fullname($user);
    } else {
        $username = null;
    }

    $sql = "SELECT i.*
            FROM {local_treestudyplan_invit} i
            WHERE i.user_id = :userid
                AND i.unlockdate IS NOT NULL
            ";

    $params = [ "userid" => $userid];
    $invites = [];
    $now = (new \DateTime("now", \core_date::get_user_timezone_object()))->getTimestamp();
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $invit) {
        if (intval($invit->unlockdate) < $now) {
            $invit->unlocked = true;
        } else {
            $invit->unlocked = false;
        }
        $invites[] = $invit;
    }
    $rs->close();
    $data = [
        "username" => $username,
        "user" => $user,
        "userselector" => $selectuserform->render(),
        "userselected" => !empty($user),
        "invites" => $invites,
        "hasinvites" => boolval(count($invites) > 0),
        "invitedurl" => "{$CFG->wwwroot}/local/treestudyplan/invited.php",
    ];
    print $OUTPUT->render_from_template('local_treestudyplan/cfg-manageshares', $data);
    print $OUTPUT->footer();
}
