<?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\external;

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_single_structure;
use core_external\external_value;
use local_kid\local\access_helper;
use local_kid\local\competences_promotion_selector;
use local_kid\local\promotion_repository;

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

/**
 * AJAX backing for sélecteur B (Administration → Compétences, "no Afficher
 * button" auto-load): switches which promotion is being configured — a
 * state kept in {@see competences_promotion_selector}, completely separate
 * from promotion_selector (sélecteur A, the plugin-wide "promotion
 * affichée") — and re-renders just that tab's competencies table fragment.
 */
class get_competences_admin_view extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'promotionid' => new external_value(PARAM_INT, 'promotion to configure'),
        ]);
    }

    public static function execute(int $promotionid): array {
        global $USER, $PAGE;

        ['promotionid' => $promotionid] = self::validate_parameters(
            self::execute_parameters(),
            ['promotionid' => $promotionid]
        );

        $context = \context_system::instance();
        self::validate_context($context);
        access_helper::require_capability_or_teacher('local/kid:manage', $context);

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

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

        $renderer = $PAGE->get_renderer('local_kid');
        $html = $renderer->render_competencies_admin_page(new \local_kid\output\competencies_admin_page($promotionid));

        return ['html' => $html];
    }

    public static function execute_returns(): external_single_structure {
        return new external_single_structure([
            'html' => new external_value(PARAM_RAW, 'Rendered HTML fragment for [data-region="kid-competences-region"]'),
        ]);
    }
}
