<?php
// This file is part of the Studyplan plugin for Moodle
//
// 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.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
/**
 * Model class for study lines
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

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

require_once($CFG->libdir.'/externallib.php');
/**
 * Model class for study lines
 */
class studyline {
    /**
     * Studyline is not enrollable
     * @var int
     */
    public const ENROLLABLE_NONE = 0;

    /**
     * Studyline can be enrolled into by the student
     * @var int
     */
    public const ENROLLABLE_SELF = 1;

    /**
     * Studyline can be enrolled into by specific role(s)
     * @var int
     */
    public const ENROLLABLE_ROLE = 2;

    /**
     * Studyline can be enrolled by user and/or role
     * @var int
     */
    public const ENROLLABLE_SELF_ROLE = 3;

    /**
     * Handle for course slots in the period for webservice export
     * @var string
     */
    public const SLOTSET_COURSES = 'courses';
    /**
     * Handle for filter slots around the periods for webservice export
     * @var string
     */
    public const SLOTSET_FILTER = 'filters';

    /**
     * List of item types allowed in the course slot
     * @var array
     */
    public const COURSE_TYPES = [
        studyitem::COURSE,
    ];
    /**
     * List of item types allowed in the filter slot
     * @var array
     */
    public const FILTER_TYPES = [
        studyitem::JUNCTION,
        studyitem::BADGE,
        studyitem::FINISH,
        studyitem::START,
    ];

    /**
     * List of item types allowed in the first filter slot
     * @var array
     */
    public const FILTER0_TYPES = [
        studyitem::START,
    ];

    /** @var string */
    public const TABLE = "local_treestudyplan_line";

    /**
     * Cache retrieved studylines for optimization
     * @var array
     */
    private static $cache = [];

    /**
     * Holds database record
     * @var stdClass
     */
    private $r;
    /** @var int */
    private $id;
    /** @var studyplanpage */
    private $page;
    /** @var studyplan*/
    private $studyplan;

    /**
     * Return the context the studyplan is associated to
     */
    public function context(): \context {
        return $this->studyplan->context();
    }

    /**
     * Return the studyplan for this line
     */
    public function studyplan(): studyplan {
        return $this->studyplan;
    }

    /**
     * Return the studyplan page for this line
     */
    public function page(): studyplanpage {
        return $this->page;
    }

    /**
     * Find record in database and return management object
     * @param int $id Id of database record
     */
    public static function find_by_id($id): self {
        if (!array_key_exists($id, self::$cache)) {
            self::$cache[$id] = new self($id);
        }
        return self::$cache[$id];
    }

    /**
     * Construct new instance from DB record
     * @param int $id Id of database record
     */
    private function __construct($id) {
        global $DB;
        $this->id = $id;
        $this->r = $DB->get_record(self::TABLE, ['id' => $id]);
        $this->page = studyplanpage::find_by_id($this->r->page_id);
        $this->studyplan = $this->page->studyplan();
    }

    /**
     * Return database identifier
     */
    public function id(): int {
        return $this->id;
    }

    /**
     * Return full name
     */
    public function name(): string {
        return $this->r->name;
    }

    /**
     * Return short name
     */
    public function shortname(): string {
        return $this->r->shortname;
    }

    /**
     * Whether this line is enrollable by the student
     */
    public function self_enrollable(): bool {
        return ($this->r->enrollable == self::ENROLLABLE_SELF || $this->r->enrollable == self::ENROLLABLE_SELF_ROLE);
    }

    /**
     * Whether this line is enrollable by a role
     */
    public function role_enrollable(): bool {
        return ($this->r->enrollable == self::ENROLLABLE_ROLE || $this->r->enrollable == self::ENROLLABLE_SELF_ROLE);
    }

    /**
     * Whether the current user can enrol a specific user in this line
     * @param int|null $userid ID of user to check for. Checks current user if left empty or null
     */
    public function can_enrol($userid=null): bool {
        global $USER;

        $plan = $this->studyplan();
        if (!empty($userid)) {
            if ($plan->has_linked_user(intval($userid))) {
                if ($this->self_enrollable() && $userid == $USER->id) {
                    return true;
                }
                if ($this->role_enrollable()) {
                    $context = $plan->context();
                    foreach ($this->enrol_roleids() as $rid) {
                        if (\user_has_role_assignment($USER->id, $rid, $context->id)) {
                            return true;
                        }
                    }
                }
            }
        } else {
            if ($this->role_enrollable()) {
                $context = $plan->context();
                foreach ($this->enrol_roleids() as $rid) {
                    if (\user_has_role_assignment($USER->id, $rid, $context->id)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * Whether this line is enrollable at all
     */
    public function enrollable(): bool {
        return $this->r->enrollable != self::ENROLLABLE_NONE;
    }

    /**
     * List the available roles that can enrol the student
     */
    public function enrol_roles(): array {
        global $DB;
        $list = [];
        if ($this->r->enrolrole) {
            $roles = explode(",", $this->r->enrolrole);
            foreach ($roles as $r) {
                $roleid = intval($r);
                if ($roleid > 0) {
                    try {
                        $role = $DB->get_record('role', ["id" => $roleid], "*", MUST_EXIST);
                        $list[] = $role;
                    } catch (\Exception $x) {
                        $role = null;
                    }
                }
            }
        }
        return $list;
    }

    /**
     * List the available roles that can enrol the student
     */
    public function enrol_roleids(): array {
        global $DB;
        $list = [];
        if ($this->r->enrolrole) {
            $roles = explode(",", $this->r->enrolrole);
            foreach ($roles as $r) {
                $roleid = intval($r);
                if ($roleid > 0) {
                    $list[] = $roleid;
                }
            }
        }

        return $list;
    }

    /**
     * List the available roles that can enrol the student in a proper model
     */
    public function enrol_roles_model(): array {
        $list = [];
        foreach ($this->enrol_roles() as $role) {
            $name = role_get_name($role, $this->context()); // Get localized role name.
            $list[] = [
                "id" => $role->id,
                "name" => $name,
            ];
        }

        return $list;
    }

    /**
     * Webservice structure for editor info
     * @param int $value Webservice requirement constant
     */
    public static function editor_structure($value = VALUE_REQUIRED): \external_description {
        return new \external_single_structure([
            "id" => new \external_value(PARAM_INT, 'id of studyline'),
            "name" => new \external_value(PARAM_TEXT, 'shortname of studyline'),
            "shortname" => new \external_value(PARAM_TEXT, 'idnumber of studyline'),
            "color" => new \external_value(PARAM_TEXT, 'description of studyline'),
            "sequence" => new \external_value(PARAM_INT, 'order of studyline'),
            "enrol" => self::enrol_info_structure(),
            "slots" => new \external_multiple_structure(
                new \external_single_structure([
                    self::SLOTSET_COURSES => new \external_multiple_structure(
                                                    studyitem::editor_structure(), 'competency items', VALUE_OPTIONAL),
                    self::SLOTSET_FILTER => new \external_multiple_structure(
                                                    studyitem::editor_structure(), 'filter items'),
                ])
            ),
        ], "Study line editor structure", $value);
    }

    /**
     * Webservice structure for enrolment info
     * @param int $value Webservice requirement constant
     */
    public static function enrol_info_structure($value = VALUE_REQUIRED) {
        return new \external_single_structure([
            "enrollable" => new \external_value(PARAM_INT, 'enrol mode (raw)'),
            "enrolroles" => new \external_multiple_structure(new \external_value(PARAM_INT, 'id of role')),
            "allowedroles" => new \external_multiple_structure(new \external_single_structure([
                "id" => new \external_value(PARAM_INT, 'id of role'),
                "name" => new \external_value(PARAM_TEXT, 'name of role'),
            ])),
            "can_enrol" => new \external_value(PARAM_BOOL, 'enrollable by current user', VALUE_OPTIONAL),
            "enrolled" => new \external_value(PARAM_BOOL, 'student is enrolled', VALUE_OPTIONAL),
            "enrolled_time" => new \external_value(PARAM_INT, 'moment of enrollment', VALUE_OPTIONAL),
            "enrolled_by" => new \external_value(PARAM_TEXT, 'Name of enrolling user', VALUE_OPTIONAL),
            "selfview" => new \external_value(PARAM_BOOL, 'viewing user is the student', VALUE_OPTIONAL),
        ], "Enrollment info", $value);
    }

    /**
     * Webservice structure for simple info
     * @param int $value Webservice requirement constant
     */
    public static function simple_structure($value = VALUE_REQUIRED): \external_description {
        return new \external_single_structure([
            "id" => new \external_value(PARAM_INT, 'id of studyline'),
            "name" => new \external_value(PARAM_TEXT, 'shortname of studyline'),
            "shortname" => new \external_value(PARAM_TEXT, 'idnumber of studyline'),
            "color" => new \external_value(PARAM_TEXT, 'description of studyline'),
            "sequence" => new \external_value(PARAM_INT, 'order of studyline'),
            "enrol" => self::enrol_info_structure(),
        ], "Study line simple structure", $value);
    }

    /**
     * Webservice model for simple info
     * @return array Webservice data model
     */
    public function simple_model(): array {
        return  [
            'id' => $this->r->id,
            'name' => $this->r->name,
            'shortname' => $this->r->shortname,
            'color' => $this->r->color,
            'sequence' => $this->r->sequence,
            'enrol' => $this->enrol_info_model(),
        ];
    }

    /**
     * Webservice model for editor info
     * @return array Webservice data model
     */
    public function editor_model(): array {
        return $this->generate_model("editor");
    }

    /**
     * Create a model for the given type of operation
     * @param string $mode One of [ 'editor', 'export']
     */
    protected function generate_model($mode): array {
        // Mode parameter is used to geep this function for both editor model and export model.
        // (Export model results in fewer parameters on children, but is otherwise basically the same as this function).
        global $DB;

        $model = [
            'id' => $this->r->id,
            'name' => $this->r->name,
            'shortname' => $this->r->shortname,
            'color' => $this->r->color,
            'sequence' => $this->r->sequence,
            'enrol' => $this->enrol_info_model(),
            'slots' => [],
        ];
        if ($mode == "export") {
            // Id and sequence are not used in export model.
            unset($model["id"]);
            unset($model["sequence"]);
        }

        // Get the number of slots.
        // As a safety data integrity measure, if there are any items in a higher slot than currently allowed, .
        // Make sure there are enought slots to account for them.
        // Alternatively, we could ensure that on reduction of slots, the items that no longer have a slot will be removed.
        $maxslot = $DB->get_field_select(studyitem::TABLE, "MAX(slot)", "line_id = :lineid", ['lineid' => $this->id]);
        $numslots = max($this->page->periods(), $maxslot + 1);

        // Create the required amount of slots.
        for ($i = 0; $i < $numslots + 1; $i++) {
            if ($mode == "export") {
                // Export mode does not separate between filter or competency type, since that is determined automatically.
                $slots = [];
            } else {
                if ($i > 0) {
                    $slots = [self::SLOTSET_COURSES => [], self::SLOTSET_FILTER => []];
                } else {
                    $slots = [self::SLOTSET_FILTER => []];
                }
            }
            $model['slots'][$i] = $slots;
        }

        $children = studyitem::find_studyline_children($this);
        foreach ($children as $c) {
            if ($mode == "export") {
                $model['slots'][$c->slot()][] = $c->export_model();
            } else {
                $slotset = null;
                if ($c->slot() > 0) {
                    if (in_array($c->type(), self::COURSE_TYPES)) {
                        $slotset = self::SLOTSET_COURSES;
                    } else if (in_array($c->type(), self::FILTER_TYPES)) {
                        $slotset = self::SLOTSET_FILTER;
                    }
                } else if (in_array($c->type(), self::FILTER0_TYPES)) {
                    $slotset = self::SLOTSET_FILTER;
                }
                if (isset($slotset)) {
                    $model['slots'][$c->slot()][$slotset][] = $c->editor_model();
                }
            }
        }
        return $model;
    }

    /**
     * Add a new study line
     * @param array $fields Properties for study line ['page_id', 'name', 'shortname', 'color']
     */
    public static function add($fields): self {
        global $DB;

        if (!isset($fields['page_id'])) {
            throw new \InvalidArgumentException("parameter 'page_id' missing");
        }

        $pageid = $fields['page_id'];
        $sqmax = $DB->get_field_select(self::TABLE, "MAX(sequence)", "page_id = :page_id", ['page_id' => $pageid]);
        $addable = ['page_id', 'name', 'shortname', 'color', 'enrollable', 'enrolrole'];
        $info = ['sequence' => $sqmax + 1];
        foreach ($addable as $f) {
            if (array_key_exists($f, $fields)) {
                $info[$f] = $fields[$f];
            }
        }
        $id = $DB->insert_record(self::TABLE, $info);
        return self::find_by_id($id);
    }

    /**
     * Edit study line properties
     * @param array $fields Changed roperties for study line ['name', 'shortname', 'color']
     */
    public function edit($fields): self {
        global $DB;
        $editable = ['name', 'shortname', 'color', 'enrollable', 'enrolrole'];
        $info = ['id' => $this->id ];
        foreach ($editable as $f) {
            if (array_key_exists($f, $fields)) {
                $info[$f] = $fields[$f];
            }
        }
        $DB->update_record(self::TABLE, $info);
        // Reload record after edit.
        $this->r = $DB->get_record(self::TABLE, ['id' => $this->id], "*", MUST_EXIST);
        return $this;
    }

    /**
     * Delete studyline
     * @param bool $force Force deletion even if study line contains items
     */
    public function delete($force = false): success {
        global $DB;

        if ($force) {
            $children = studyitem::find_studyline_children($this);
            foreach ($children as $c) {
                $c->delete($force);
            }
        }
        // Check if this item has study items in it.
        if ($DB->count_records(studyitem::TABLE, ['line_id' => $this->id]) > 0) {
            return success::fail('cannot delete studyline with items');
        } else {
            $DB->delete_records(self::TABLE, ['id' => $this->id]);
            return success::success();
        }
    }

    /**
     * Reorder study lines
     * @param int[] $resequence New order of study lines by id
     */
    public static function reorder($resequence): success {
        global $DB;

        foreach ($resequence as $sq) {
            $DB->update_record(self::TABLE, [
                'id' => $sq['id'],
                'sequence' => $sq['sequence'],
            ]);
        }

        return success::success();
    }

    /**
     * Find all studylines associated with a studyplan page
     * @param studyplanpage $page The studyplanpage to search for
     * @return studyline[]
     */
    public static function find_page_children(studyplanpage $page): array {
        global $DB;
        $list = [];
        $ids = $DB->get_fieldset_select(self::TABLE, "id", "page_id = :page_id ORDER BY sequence",
                                        ['page_id' => $page->id()]);
        foreach ($ids as $id) {
            $list[] = self::find_by_id($id);
        }
        return $list;
    }

    /**
     * Webservice structure for userinfo
     * @param int $value Webservice requirement constant
     */
    public static function user_structure($value = VALUE_REQUIRED): \external_description {
        return new \external_single_structure([
            "id" => new \external_value(PARAM_INT, 'id of studyline'),
            "name" => new \external_value(PARAM_TEXT, 'shortname of studyline'),
            "shortname" => new \external_value(PARAM_TEXT, 'idnumber of studyline'),
            "color" => new \external_value(PARAM_TEXT, 'description of studyline'),
            "sequence" => new \external_value(PARAM_INT, 'order of studyline'),
            "enrol" => self::enrol_info_structure(),
            "slots" => new \external_multiple_structure(
                new \external_single_structure([
                    self::SLOTSET_COURSES => new \external_multiple_structure(
                                                        studyitem::user_structure(), 'competency items', VALUE_OPTIONAL),
                    self::SLOTSET_FILTER => new \external_multiple_structure(
                                                        studyitem::user_structure(), 'filter items'),
                ])
                    ),
        ], 'Studyline with user info', $value);
    }

    /**
     * Webservice model for user enrolment info
     * @param int $userid ID of user to check specific info for
     * @return array Webservice data model
     */
    public function enrol_info_model($userid=null) {
        global $DB, $USER;

        $model = [
            'enrolroles' => $this->enrol_roleids(),
            'allowedroles' => $this->enrol_roles_model(),
            'enrollable' => $this->r->enrollable,
        ];

        if (!empty($userid)) {
            $r = $DB->get_record('local_treestudyplan_lineuser', [
                'line_id' => $this->id(),
                'user_id' => $userid,
            ]);

            if (empty($r)) {
                $enrolled = false;
                $enrolledtime = 0;
                $enrolledby = "";
            } else {
                $enrolled = boolval($r->enrolled);
                $enrolledtime = $r->timeenrolled;
                $by = $DB->get_record('user', ["id" => $r->enrolledby]);
                if (empty($by)) {
                    $enrolledby = \get_string("unknownuser", "core");
                } else {
                    $enrolledby = "{$by->firstname} {$by->lastname}";
                }
            }

            $usermodel = [
                'can_enrol' => $this->can_enrol($userid),
                "enrolled" => $enrolled,
                "enrolled_time" => $enrolledtime,
                "enrolled_by" => $enrolledby,
                "selfview" => boolval($userid == $USER->id),
            ];
            $model = array_merge($model, $usermodel);
        } else {
            $model["can_enrol"] = $this->can_enrol();
        }

        return $model;
    }

    /**
     * Get the users enrolled in this studyline if relevant
     * @return array of Userids linked
     */
    public function get_enrolled_userids() {
        $userids = $this->studyplan()->find_linked_userids();
        if ($this->enrollable()) {
            $list = [];
            foreach ($userids as $uid) {
                if ($this->isenrolled($uid)) {
                    $list[] = $uid;
                }
            }
            return $list;
        } else {
            return $userids;
        }
    }

    /**
     * Check if student is enrolled in the line.
     * @param int $userid ID of user to check specific info for
     * @return array Webservice data model
     */
    public function isenrolled($userid) {
        global $DB;
        if ($this->r->enrollable == self::ENROLLABLE_NONE) {
            return true; // If student cannot enrol, the student always is enrolled.
        } else {
            $r = $DB->get_record('local_treestudyplan_lineuser', [
                'line_id' => $this->id(),
                'user_id' => $userid,
            ]);

            if (empty($r)) {
                return false;
            } else {
                return boolval($r->enrolled);
            }
        }
    }

    /**
     * List the course id is linked in this studyplan
     * Used for cohort enrolment cascading
     * @return int[]
     */
    public function get_linked_course_ids(): array {
        global $DB;

        $sql = "SELECT i.course_id
                FROM  {local_treestudyplan_line} l
                INNER JOIN {local_treestudyplan_item} i ON l.id = i.line_id
                WHERE l.id = :studyline_id AND i.type = :itemtype";
        $fields = $DB->get_fieldset_sql($sql, ["studyline_id" => $this->id, "itemtype" => studyitem::COURSE]);

        return $fields;
    }

    /**
     * Enrol student from this line (if line enrollable)
     * NOTE: This function does not check if the current user should be allowed to do this,
     *       the checks need to be done in the calling webservice / function
     * @param int $userid of user to enrol
     */
    public function enrol($userid) {
        global $DB, $USER;

        if ($this->r->enrollable > self::ENROLLABLE_NONE) {
            $r = $DB->get_record("local_treestudyplan_lineuser",
                ["line_id" => $this->id(),
                 "user_id" => $userid]);
            if ($r) {
                // Registration already exists, check if enrol is false and update accordingly.
                if (! boolval($r->enrolled)) {
                    $r->enrolled = 1;
                    $r->timeenrolled = time();
                    $r->enrolledby = $USER->id;
                    $DB->update_record("local_treestudyplan_lineuser", $r);
                }
                // Otherwise, ignore the request.

            } else {
                // Insert new record.
                $r = new \stdClass;
                $r->enrolled = 1;
                $r->line_id = $this->id();
                $r->user_id = $userid;
                $r->timeenrolled = time();
                $r->enrolledby = $USER->id;
                $DB->insert_record("local_treestudyplan_lineuser", $r);
            }

            $this->studyplan()->mark_csync_changed();
        }

    }

    /**
     * Unenrol student from this line (if line enrollable)
     * NOTE: This function does not check if the current user should be allowed to do this,
     *       the checks need to be done in the calling webservice / function
     * @param int $userid of user to unenrol
     */
    public function unenrol($userid) {
        global $DB, $USER;

        if ($this->r->enrollable > self::ENROLLABLE_NONE) {
            // Check if an enrollment line exist.
            $r = $DB->get_record("local_treestudyplan_lineuser",
                ["line_id" => $this->id(),
                 "user_id" => $userid]);
            if ($r) {
                // Registration already exists, check if enrolled is true and update accordingly.
                if (boolval($r->enrolled)) {
                    $r->enrolled = 0;
                    $r->timeenrolled = time(); // Regi.
                    $r->enrolledby = $USER->id;
                    $DB->update_record("local_treestudyplan_lineuser", $r);

                    $this->studyplan()->mark_csync_changed();
                }
                // Otherwise, ignore the request.

            }
            // Otherwise, no action is needed.
        }
    }

    /**
     * Webservice model for user info
     * @param int $userid ID of user to check specific info for
     * @return array Webservice data model
     */
    public function user_model($userid) {

        global $DB;

        $model = [
            'id' => $this->r->id,
            'name' => $this->r->name,
            'shortname' => $this->r->shortname,
            'color' => $this->r->color,
            'sequence' => $this->r->sequence,
            'enrol' => $this->enrol_info_model($userid),
            'slots' => [],
        ];

        // Get the number of slots.
        // As a safety data integrity measure, if there are any items in a higher slot than currently allowed, .
        // Make sure there are enought slots to account for them.
        // Alternatively, we could ensure that on reduction of slots, the items that no longer have a slot will be removed.
        $maxslot = $DB->get_field_select(studyitem::TABLE, "MAX(slot)", "line_id = :lineid", ['lineid' => $this->id]);
        $numslots = max($this->page->periods(), $maxslot + 1);

        // Create the required amount of slots.
        for ($i = 0; $i < $numslots + 1; $i++) {
            if ($i > 0) {
                $slots = [self::SLOTSET_COURSES => [], self::SLOTSET_FILTER => []];
            } else {
                $slots = [self::SLOTSET_FILTER => []];
            }
            $model['slots'][$i] = $slots;
        }

        $children = studyitem::find_studyline_children($this);
        foreach ($children as $c) {
            if ($c->valid()) {
                $slotset = null;
                if ($c->slot() > 0) {
                    if (in_array($c->type(), self::COURSE_TYPES)) {
                        $slotset = self::SLOTSET_COURSES;
                    } else if (in_array($c->type(), self::FILTER_TYPES)) {
                        $slotset = self::SLOTSET_FILTER;
                    }
                } else if (in_array($c->type(), self::FILTER0_TYPES)) {
                    $slotset = self::SLOTSET_FILTER;
                }
                if (isset($slotset)) {
                    $model['slots'][$c->slot()][$slotset][] = $c->user_model($userid);
                }
            }
        }

        return $model;

    }

    /**
     * Duplicate this studyline into another page
     * @param studyplanpage $newpage Studyplan page to copy the line into
     * @param array $translation Mapping array of old item ids to new item ids for connection matching
     * @param bool $bare Set to true to skip copying contents
     */
    public function duplicate($newpage, &$translation, $bare = false): self {
        global $DB;

        // Clone the database fields.
        $fields = clone $this->r;
        // Set new studyplan id.
        unset($fields->id);
        $fields->page_id = $newpage->id();
        // Create new record with the new data.
        $id = $DB->insert_record(self::TABLE, (array)$fields);
        $new = self::find_by_id($id);

        if (!$bare) {
            // Next copy all the study items for this studyline.
            // And record the original and copy id's in the $translation array.
            // So the calling function can connect the new studyitems as required.
            $children = studyitem::find_studyline_children($this);
            $translation = [];
            foreach ($children as $c) {
                $newchild = $c->duplicate($new);
                $translation[$c->id()] = $newchild->id();
            }
        }
        return $new;
    }

    /**
     * Export essential information for export
     * @return array information model
     */
    public function export_model() {
        return $this->generate_model("export");
    }

    /**
     * Import study items into line  from decoded array model
     * @param array $model Decoded array
     * @param array $itemtranslation Link to array to map old item ids to new item ids for connection matching
     * @param array $connections Link to array of connections between item
     * @return null
     */
    public function import_studyitems(array $model, array &$itemtranslation, array &$connections) {
        global $DB;
        foreach ($model as $slot => $slotmodel) {
            $courselayer = 0;
            $filterlayer = 0;
            foreach ($slotmodel as $itemmodel) {
                if ($itemmodel["type"] == "course") {
                    $itemmodel["layer"] = $courselayer;
                    $courselayer++;
                } else {
                    $itemmodel["layer"] = $filterlayer;
                    $filterlayer++;
                }

                $itemmodel["slot"] = $slot;
                $itemmodel["line_id"] = $this->id();
                $item = studyitem::import_item($itemmodel);

                if (!empty($item)) {
                    $itemtranslation[$itemmodel["id"]] = $item->id();

                    if (count($itemmodel["connections"]) > 0) {
                        if (! isset($connections[$item->id()]) || ! is_array($connections[$item->id()])) {
                            $connections[$item->id()] = [];
                        }
                        foreach ($itemmodel["connections"] as $toid) {
                            $connections[$item->id()][] = $toid;
                        }
                    }
                }
            }
        }
    }
}
