<?php

namespace apexl\Io\modules\menu\includes;

use apexl\Io\modules\user\enums\permissions\Common;
use apexl\Io\modules\user\interfaces\PermissionInterface;
use apexl\Io\utilityIncludes\Route;

final class menuItem
{
    public string $name;
    public string $title;
    public string $href;
    public PermissionInterface $permission;
    public string $icon;
    public ?array $links;
    public int $weight;
    protected bool $parent;

    public function __construct(array $item, ?Route $route)
    {
        $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($route, $item);


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

    }

    private function setHref(?Route $route, array $item): void
    {
        if ($route) {
            $this->href = $route->getPattern($item['replacements'] ?? []);
            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;
    }
}
