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

/**
 * Install steps for local_kid: functional roles, defensive extension of the
 * existing `teacher` role, and the fixed 5-level scale seed.
 *
 * @package    local_kid
 */

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

function xmldb_local_kid_install() {
    local_kid_install_roles_and_seed_data();
    return true;
}

/**
 * Shared by the fresh install and (if ever needed) a recovery re-run.
 *
 * Moodle calls db/install.php's xmldb_local_kid_install() BEFORE it calls
 * update_capabilities() to register db/access.php's capabilities — so any
 * assign_capability() call in here on a capability this same plugin just
 * defined would fail with "Capability ... was not found" unless we register
 * them ourselves first. update_capabilities() is idempotent, so the official
 * call Moodle makes later in the install sequence is then a safe no-op.
 */
function local_kid_install_roles_and_seed_data() {
    global $DB;

    update_capabilities('local_kid');

    \local_kid\local\role_setup::create_functional_roles();

    // 5 niveaux fixes, aucune autre donnée.
    if ($DB->count_records('local_kid_niveau') === 0) {
        $now = time();
        $niveaux = [
            ['code' => 'COMPETENCE4', 'libelle' => 'Dépasse les attentes',     'couleur' => '#000091', 'sortorder' => 1, 'codeadesi' => 'COMPETENCE4'],
            ['code' => 'COMPETENCE3', 'libelle' => 'Acquis',                    'couleur' => '#1D6B23', 'sortorder' => 2, 'codeadesi' => 'COMPETENCE3'],
            ['code' => 'COMPETENCE2', 'libelle' => 'En cours d\'acquisition',  'couleur' => '#B34000', 'sortorder' => 3, 'codeadesi' => 'COMPETENCE2'],
            ['code' => 'COMPETENCE1', 'libelle' => 'Non acquis',                'couleur' => '#CE0500', 'sortorder' => 4, 'codeadesi' => 'COMPETENCE1'],
            ['code' => 'COMPETENCE0', 'libelle' => 'Non observé',               'couleur' => '#6B6B6B', 'sortorder' => 5, 'codeadesi' => 'COMPETENCE0'],
        ];
        foreach ($niveaux as $niveau) {
            $niveau['timemodified'] = $now;
            $niveau['usermodified'] = get_admin()->id;
            $DB->insert_record('local_kid_niveau', (object) $niveau);
        }
    }
}
