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

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

/**
 * Saves the Comparateur de bilans' current filter set as a named favori
 * for the calling user. `config` travels as an opaque JSON string built
 * client-side from the filter form state — re-decoded here only to
 * validate it is well-formed JSON before storing, never interpreted.
 */
class dashboard_favori_create extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'name' => new external_value(PARAM_TEXT, 'Favori display name'),
            'config' => new external_value(PARAM_RAW, 'JSON-encoded filter set'),
        ]);
    }

    public static function execute(string $name, string $config): array {
        global $USER;

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

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

        $name = trim($name);
        if ($name === '') {
            throw new \moodle_exception('invalidparameter', 'error');
        }
        $decoded = json_decode($config, true);
        if (!is_array($decoded)) {
            throw new \moodle_exception('invalidparameter', 'error');
        }

        $id = dashboard_favori_repository::create((int) $USER->id, $name, $decoded);

        return ['id' => $id, 'name' => $name];
    }

    public static function execute_returns(): external_single_structure {
        return new external_single_structure([
            'id' => new external_value(PARAM_INT, 'New local_kid_dashboard_favori.id'),
            'name' => new external_value(PARAM_TEXT, 'Stored name'),
        ]);
    }
}
