<?php

declare(strict_types=1);

namespace apexl\Io\modules\menu\entities\operators;

use apexl\Vault\exceptions\ExecutionException;

class menuLinksOperator extends menuOperator
{
    public function __construct($table, $primaryKey = 'id')
    {
        parent::__construct($table, $primaryKey);
    }

    /**
     * @throws ExecutionException
     */
    public function load($id, $skipAccessCheck = false): array
    {
        $link = (object) $this->vault->select($this->dbTable)->fields()->where('id', $id)->execute()->fetchAssoc();
        if (!empty($link)) {
            $link->links = $this->getChildLinks($link->id);
        }

        return ['updateEntityData' => true, 'data' => $link];
    }

    /**
     * @throws ExecutionException
     */
    public function getChildLinks(int $parentId): array
    {
        $links = $this->vault->select($this->dbTable)->fields()->where('parentId', $parentId)->execute()->fetchAll();
        $linkEntities = [];
        foreach ($links as $link) {
            $children = $this->getChildLinks($link->id);
            if ($children) {
                $link->links = $children;
            }
            $linkEntities[$link->id] = $link;
        }

        return $linkEntities;
    }

    /**
     * @throws ExecutionException
     */
    public function getMenuLinks(int $menuId): array
    {
        $links = $this->vault->select($this->dbTable)->fields()->where('mid', $menuId)->execute()->fetchAll();
        $linkEntities = [];
        foreach ($links as $link) {
            $children = $this->getChildLinks($link->id);
            if ($children) {
                $link->links = $children;
            }
            $linkEntities[$link->id] = $link;
        }

        return $linkEntities;
    }
}
