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

/**
 * Exception class for upload managed shares.
 *
 * @package    local_treestudyplan
 * @copyright  2025 P.M. Kuipers
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
namespace local_treestudyplan\local\tools;

/**
 * An exception for reporting errors when processing files
 */
class invitation_tools {
    /**
     * Send invitation to invited person
     * @param mixed $inviteid Database id of the invitation
     *
     */
    public static function send_invite($inviteid) {
        global $DB, $USER, $CFG;
        $invite = $DB->get_record("local_treestudyplan_invit", ['id' => $inviteid]);
        $user = $DB->get_record('user', ['id' => $invite->user_id]);
        $noreply = 'noreply@' . get_host_from_url($CFG->wwwroot);
        $mailer = get_mailer();
        if ($mailer != null) {
            $fullname = \core_user::get_fullname($user);
            $mailer->setFrom($noreply, "{$fullname}");
            $mailer->addAddress($invite->email, $invite->name);
            $mailer->addReplyTo($USER->email, "{$fullname}");

            $invitehref = $CFG->wwwroot . "/local/treestudyplan/invited.php?key={$invite->invitekey}";

            $data = [   'permissions' => '',
                        'invitee' => $invite->name,
                        'sender' => $fullname,
                        'user' => $fullname,
                        'link' => $invitehref];

            if ($invite->allow_details || $invite->allow_calendar || $invite->allow_badges) {
                $data['permissions'] = get_string('invite_mail_permissions', 'local_treestudyplan');
                $data['permissions'] .= "<ul>\n";
                if ($invite->allow_details) {
                    $data['permissions'] .= "<li>" . get_string('invite_allow_details', 'local_treestudyplan') . "</li>\n";
                }
                if ($invite->allow_calendar) {
                    $data['permissions'] .= "<li>" . get_string('invite_allow_calendar', 'local_treestudyplan') . "</li>\n";
                }
                if ($invite->allow_badges) {
                    $data['permissions'] .= "<li>" . get_string('invite_allow_badges', 'local_treestudyplan') . "</li>\n";
                }

                $data['permissions'] .= "</ul></p>\n";
            }

            if ($USER->id == $user->id) {
                // Use this text if the user themself is initiating the invite.
                $body = get_string('invite_mail_text', 'local_treestudyplan', $data);
                $subject = get_string('invite_mail_subject', 'local_treestudyplan', $data);
            } else {
                // Use this text if the invite is sent by a manager.
                $body = get_string('invite_mail_managed_text', 'local_treestudyplan', $data);
                $subject = get_string('invite_mail_subject', 'local_treestudyplan', $data);
            }

            $html = "
            <!DOCTYPE html>
            <html xmlns='http://www.w3.org/1999/xhtml'>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
            <title>{$subject}</title>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
            </head>
            <body>
            {$body}
            </body>
            </html>";

            $mailer->isHTML(true);
            $mailer->Subject = $subject;
            $mailer->Body = $html;
            $mailer->AltBody = strip_tags($body);

            $mailer->send();
        }
    }


    /**
     * Generate an invitaiton key.
     *
     * @return str Random string used as invitiation key
     */
    public static function generate_invitekey() {
        global $DB;
        // Create a new random key for the invite.
        do {
            $length = 20;
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $characterslength  = strlen($characters);
            $randomkey = '';
            for ($i = 0; $i < $length; $i++) {
                $randomkey .= $characters[rand(0, $characterslength - 1)];
            }

            // Double check that the key is unique before inserting.
        } while (
            $DB->record_exists_select(
                "local_treestudyplan_invit",
                $DB->sql_compare_text("invitekey") . " = " . $DB->sql_compare_text(":invitekey"),
                ['invitekey' => $randomkey]
            )
        );
        return $randomkey;
    }
}
