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

namespace local_kid\local;

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

/**
 * The promotion being configured in Administration → Compétences (the
 * référentiel-editing "sélecteur B") — a per-user preference deliberately
 * SEPARATE from {@see promotion_selector} (the plugin-wide "displayed
 * promotion", sélecteur A). Never merge these two: sélecteur B must be able
 * to browse/edit any promotion's competencies without ever moving what
 * sélecteur A shows on the dashboard/Évaluations/Stages/CAPP/Vue élève.
 * Deliberately duplicates promotion_selector's shape rather than
 * parameterising it, so the two states can never accidentally share a
 * preference key.
 */
class competences_promotion_selector {

    const PREFERENCE_NAME = 'local_kid_competences_admin_promotion';

    public static function get_selected(int $userid): ?int {
        $value = get_user_preferences(self::PREFERENCE_NAME, null, $userid);
        return $value ? (int) $value : null;
    }

    public static function set_selected(int $promotionid, int $userid): void {
        set_user_preference(self::PREFERENCE_NAME, $promotionid, $userid);
    }

    /**
     * Resolves the promotion to configure: the stored preference if it
     * still exists, otherwise the most recently created active promotion.
     */
    public static function resolve(int $userid): ?\stdClass {
        $selected = self::get_selected($userid);
        if ($selected) {
            $promotion = promotion_repository::get($selected);
            if ($promotion) {
                return $promotion;
            }
        }

        $active = promotion_repository::get_active();
        if (empty($active)) {
            return null;
        }
        usort($active, fn($a, $b) => $b->timecreated <=> $a->timecreated);
        return reset($active);
    }
}
