<?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 "displayed" promotion is a per-user Moodle preference, deliberately
 * separate from the `active` column on local_kid_promotion (section 5 of
 * the cahier des charges forbids conflating "set as active" with a
 * single-selection UI concept).
 */
class promotion_selector {

    const PREFERENCE_NAME = 'local_kid_selected_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 display: 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);
    }
}
