<?php

namespace Apexl\Io\Menu;

use Apexl\Io\User\Enums\Permissions\Common;
use Apexl\Io\User\Interfaces\PermissionInterface;

final class MenuItem
{
    public string $name;
    public string $title;
    public string $href;
    public PermissionInterface $permission;
    public string $icon;
    public ?array $links;
    public int $weight;
    /** Only ever set on the fallback path before, so isParent() fatalled for a real route. */
    protected bool $parent = false;

    /**
     * @param string|null $href Where the item points, already built. Null when the name
     *                          names no route, which is how a parent item is recognised.
     */
    public function __construct(array $item, ?string $href = null)
    {
        $this->name = str_replace('/', '.', $item['routeName']);
        $this->title = $item['title'] ?? '';
        $this->weight = (int) ($item['weight'] ?? 1);
        $this->icon = $item['icon'] ?? '';
        $this->links = $item['links'] ?? null;
        $this->setHref($href);


        if (!isset($this->permission)) {
            $this->setPermission(Common::ALLOW_ALL);
        }

    }

    private function setHref(?string $href): void
    {
        if ($href !== null) {
            $this->href = $href;
            return;
        }
        $this->href = sprintf(
            '%s%s',
            preg_match('/^https?:\/\//', $this->name) ? '' : '/',
            $this->name
        );

        $this->parent = true; //Assume parent link (or otherwise broken link)
    }

    public function setPermission(string|PermissionInterface $permission): void
    {
        $this->permission = is_string($permission) ? unserialize($permission) : $permission;
    }

    public function isParent(): bool
    {
        return $this->parent;
    }
}
