<?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 3 of the category → course → devoir cascading picker on the
 * évaluation form (classes/form/eval_form.php): the Devoirs Moodle
 * (mod_assign) of one course, fetched on demand.
 */
class get_assigns_for_course extends external_api {

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

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

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

        $assigns = [];
        foreach (moodle_assign_bridge::get_assigns_for_course($courseid) as $cmid => $name) {
            $assigns[] = ['cmid' => $cmid, 'name' => $name];
        }

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

    public static function execute_returns(): external_single_structure {
        return new external_single_structure([
            'assigns' => new external_multiple_structure(
                new external_single_structure([
                    'cmid' => new external_value(PARAM_INT, 'course module id'),
                    'name' => new external_value(PARAM_TEXT, 'assignment name'),
                ])
            ),
        ]);
    }
}
