<?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/>.
/**
 * Developer CLI tool. Primes grade generator with random student properties
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_treestudyplan;

define('CLI_SCRIPT', true);
require(__DIR__ . '/../../../config.php');
require_once($CFG->libdir . '/clilib.php');
use core_badges\badge;
use local_treestudyplan\local\randomimage;
require_once($CFG->libdir.'/badgeslib.php');

$usage = "Generate a number of random badges
Usage:
    # php generate_badges.php [--amount|-a=<amount>]
    # php generate_badges.php --help|-h

Options:
    -h --help            Print this help.
    -a --amount=<amount> The amount of badges to generate.
";

list($options, $unrecognised) = cli_get_params([
    'help' => false,
    'amount' => null,
], [
    'h' => 'help',
    'a' => 'amount',
]);

if ($unrecognised) {
    $unrecognised = implode(PHP_EOL . '  ', $unrecognised);
    cli_error(get_string('cliunknowoption', 'core_admin', $unrecognised));
}

if ($options['help']) {
    cli_writeln($usage);
    exit(2);
}

if (empty($options['amount']) || !is_numeric($options['amount'])) {
    cli_error('Missing mandatory integer argument "amount"', 2);
}
$amount = intval($options['amount']);
cli_writeln("Creating {$amount}  new badges");

$fortunepath = "/usr/games/fortune";
if (!is_executable($fortunepath)) {
    // Get a fortune if it is available.
    cli_error('/usr/bin/fortune not found, which is needed for this script. Please install fortune', 2);
}

// Get administrator role and log in as.
$user = get_admin();

if (!$user) {
    cli_error("Unable to find admin user in DB.");
}

$auth = empty($user->auth) ? 'manual' : $user->auth;
if ($auth == 'nologin' || !is_enabled_auth($auth)) {
    cli_error(sprintf("User authentication is either 'nologin' or disabled. Check Moodle authentication method for '%s'",
            $user->username));
}

$authplugin = get_auth_plugin($auth);
$authplugin->sync_roles($user);
login_attempt_valid($user);
complete_user_login($user);

for ($i = 0; $i < $amount; $i++) {
    $fortune = shell_exec("{$fortunepath} -n 160 ");
    $pieces = explode(" ", $fortune);
    $name = implode(" ", array_splice($pieces, 0, 4));

    $fordb = new \stdClass();
    $fordb->id = null;

    $now = time();

    $randomicon = new randomimage(10, 256, 256);

    $fordb->name = $name;
    $fordb->version = 1;
    $fordb->language = "en";
    $fordb->description = $fortune;
    $fordb->imageauthorname = "Generator";
    $fordb->imageauthoremail = "generator@null.null";
    $fordb->imageauthorurl = "";
    $fordb->imagecaption = $name;
    $fordb->timecreated = $now;
    $fordb->timemodified = $now;
    $fordb->usercreated = $USER->id;
    $fordb->usermodified = $USER->id;

    $url = parse_url($CFG->wwwroot);
    $fordb->issuerurl = $url['scheme'] . '://' . $url['host'];
    $fordb->issuername = $CFG->badges_defaultissuername;
    $fordb->issuercontact = $CFG->badges_defaultissuercontact;

    $fordb->expiredate = null;
    $fordb->expireperiod = null;
    $fordb->type = \BADGE_TYPE_SITE; // Site badge.
    $fordb->courseid = null;
    $fordb->messagesubject = get_string('messagesubject', 'badges');
    $fordb->message = get_string('messagebody', 'badges',
            \html_writer::link($CFG->wwwroot . '/badges/mybadges.php', get_string('managebadges', 'badges')));
    $fordb->attachment = 1;
    $fordb->notification = \BADGE_MESSAGE_NEVER;

    $fordb->status = \BADGE_STATUS_INACTIVE;

    $newid = $DB->insert_record('badge', $fordb, true);

    // Trigger event, badge created.
    $eventparams = ['objectid' => $newid, 'context' => $PAGE->context];
    $event = \core\event\badge_created::create($eventparams);
    $event->trigger();

    $newbadge = new badge($newid);
    badges_process_badge_image($newbadge, $randomicon->tempfile);
    cli_writeln("Created new badge '{$name}'");
}

