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

/**
 * Sélecteur A (colonne de navigation de gauche, templates/nav_sidebar.mustache) :
 * change la promotion "affichée" globale du plugin (promotion_selector),
 * puis revient sur l'écran d'où l'utilisateur venait. Volontairement une
 * simple soumission classique (pas d'AJAX) : la promotion affichée pilote
 * un grand nombre d'écrans très différents (tableau de bord, Évaluations,
 * Stages, CAPP, Vue élève, Administration), chacun avec sa propre logique
 * de rendu — un rechargement complet est le moyen le plus simple et le
 * plus sûr de garantir que chacun se remet à jour correctement.
 *
 * @package    local_kid
 */

require(__DIR__ . '/../../../config.php');

use local_kid\local\nav_helper;
use local_kid\local\promotion_repository;
use local_kid\local\promotion_selector;

require_login();
$context = context_system::instance();
if (!nav_helper::can_switch_promotion()) {
    throw new \required_capability_exception($context, 'local/kid:selectpromotion', 'nopermissions', '');
}

$promotionid = required_param('promotionid', PARAM_INT);
$returnurl = required_param('returnurl', PARAM_LOCALURL);
require_sesskey();

if (!promotion_repository::get($promotionid)) {
    throw new \moodle_exception('invalidrecord', 'error');
}

promotion_selector::set_selected($promotionid, $USER->id);

// Several screens (dashboard.php, admin.php, ...) bake their own resolved
// `promotionid` into $PAGE->set_url(), which is exactly what returnurl was
// captured from — redirecting back to that exact URL unchanged would let
// its now-stale promotionid query param win over the preference we just
// updated (every controller checks the URL param before falling back to
// promotion_selector). Strip it so each screen re-resolves fresh.
$returnmoodleurl = new moodle_url($returnurl);
$returnmoodleurl->remove_params('promotionid');

redirect($returnmoodleurl);
