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

/**
 * Uninstall steps for local_kid.
 *
 * Removes the 4 functional roles this plugin creates (see
 * \local_kid\local\role_setup — core only drops the tables/capabilities
 * declared in install.xml/access.php, it never deletes roles a plugin
 * created itself) and the capability grants this plugin added to the
 * pre-existing `teacher`/`user` roles, so a clean uninstall leaves those
 * shared roles exactly as they were before local_kid was ever installed.
 *
 * @package    local_kid
 */

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

function xmldb_local_kid_uninstall() {
    global $DB;

    $systemcontext = \context_system::instance();

    foreach (array_keys(\local_kid\local\role_setup::FUNCTIONAL_ROLES) as $shortname) {
        $roleid = $DB->get_field('role', 'id', ['shortname' => $shortname]);
        if ($roleid) {
            delete_role($roleid);
        }
    }

    $teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'teacher']);
    if ($teacherroleid) {
        foreach (\local_kid\local\access_helper::TEACHER_WIDENED_CAPABILITIES as $capability) {
            unassign_capability($capability, $teacherroleid, $systemcontext->id);
        }
    }

    $authuserroleid = $DB->get_field('role', 'id', ['shortname' => 'user']);
    if ($authuserroleid) {
        unassign_capability('local/kid:viewown', $authuserroleid, $systemcontext->id);
    }

    return true;
}
