<?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_multiple_structure;
use core_external\external_single_structure;
use core_external\external_value;
use local_kid\local\access_helper;
use local_kid\local\moodle_assign_bridge;

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

/**
 * Level 2 of the category → course → devoir cascading picker on the
 * évaluation form (classes/form/eval_form.php): the courses of one category,
 * fetched on demand so the form never has to list every course on the site.
 */
class get_courses_for_category extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'categoryid' => new external_value(PARAM_INT, 'course category id'),
        ]);
    }

    public static function execute(int $categoryid): array {
        ['categoryid' => $categoryid] = self::validate_parameters(
            self::execute_parameters(),
            ['categoryid' => $categoryid]
        );

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

        $courses = [];
        foreach (moodle_assign_bridge::get_courses_for_category($categoryid) as $id => $fullname) {
            $courses[] = ['id' => $id, 'fullname' => $fullname];
        }

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

    public static function execute_returns(): external_single_structure {
        return new external_single_structure([
            'courses' => new external_multiple_structure(
                new external_single_structure([
                    'id' => new external_value(PARAM_INT, 'course id'),
                    'fullname' => new external_value(PARAM_TEXT, 'course full name'),
                ])
            ),
        ]);
    }
}
