<?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\comparateur_repository;
use local_kid\local\competency_repository;
use local_kid\local\promotion_repository;
use local_kid\output\comparateur_page;

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

/**
 * AJAX backing for the Comparateur de bilans' live filtering: re-renders
 * just the results area (toolbar + student cards) for a given filter set,
 * so the table rebuilds as filter checkboxes/chips change — no "Filtrer"
 * click, no full page reload. Read-only, mirrors exactly the selection
 * branch of pages/dashboard.php's 'comparateur' tab via the same
 * {@see comparateur_page::export_results_for_template()} the full page uses.
 */
class get_comparateur_results extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'promotionid' => new external_value(PARAM_INT, 'local_kid_promotion.id'),
            'studentids' => new external_multiple_structure(
                new external_value(PARAM_INT, 'local_kid_student.id')
            ),
            'sourcekeys' => new external_multiple_structure(
                new external_value(PARAM_ALPHANUMEXT, 'eval_N / stage_N / capp_N')
            ),
            'competencyids' => new external_multiple_structure(
                new external_value(PARAM_INT, 'local_kid_competency.id')
            ),
            'niveaucodes' => new external_multiple_structure(
                new external_value(PARAM_ALPHANUMEXT, 'local_kid_niveau.code')
            ),
            'onlyobserved' => new external_value(PARAM_BOOL, 'Hide out-of-scope/non-observed cells'),
            'showcomments' => new external_value(PARAM_BOOL, 'Show truncated comments in cells'),
        ]);
    }

    public static function execute(
        int $promotionid,
        array $studentids,
        array $sourcekeys,
        array $competencyids,
        array $niveaucodes,
        bool $onlyobserved,
        bool $showcomments
    ): array {
        global $USER, $PAGE;

        $params = self::validate_parameters(self::execute_parameters(), [
            'promotionid' => $promotionid,
            'studentids' => $studentids,
            'sourcekeys' => $sourcekeys,
            'competencyids' => $competencyids,
            'niveaucodes' => $niveaucodes,
            'onlyobserved' => $onlyobserved,
            'showcomments' => $showcomments,
        ]);

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

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

        $page = new comparateur_page([
            'promotionid' => $params['promotionid'],
            'studentids' => $params['studentids'],
            'sourcekeys' => $params['sourcekeys'],
            'competencyids' => $params['competencyids'],
            'niveaucodes' => $params['niveaucodes'],
            'onlyobserved' => $params['onlyobserved'],
            'showcomments' => $params['showcomments'],
        ], (int) $USER->id);

        $students = promotion_repository::get_active_students($params['promotionid']);
        $sources = comparateur_repository::get_sources($params['promotionid']);
        $competencies = competency_repository::get_active_for_promotion($params['promotionid']);

        $data = $page->export_results_for_template($students, $sources, $competencies);

        $renderer = $PAGE->get_renderer('local_kid');
        $html = $renderer->render_comparateur_results($data);

        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-comparateur-results"]'),
        ]);
    }
}
