<?php

namespace Daylight\Core\Modules\Admin\Registries;

use Daylight\Core\Modules\Admin\Entities\Divider;
use Daylight\Core\Modules\Admin\Entities\Page;
use Illuminate\Support\Collection;

class NavigationRegistry
{
    protected Collection $items;

    public function __construct()
    {
        $this->items = collect();
    }

    public static function addPage(Page|Divider $page): self
    {
        return app(self::class)->register($page);
    }

    public function register(array|Collection|Page|Divider $items): self
    {
        if ($items instanceof Page) {
            $items = [$items];
        }

        if ($items instanceof Divider) {
            $items = [$items];
        }

        if (is_array($items)) {
            $items = collect($items);
        }

        $this->items = $this->items->merge($items);

        return $this;
    }

    public function all(): Collection
    {
        return $this
            ->items
            ->whereNull('parent')
            ->unique('key')
            ->map(function (Page|Divider $item) {
                if ($item instanceof Divider) {
                    return $item;
                }

                $children = $this->items->where('parent', $item->key)->values();

                return $item->setChildren([
                    ...$item->children,
                    ...$children->map(function (Page|Divider $child) {
                        if ($child instanceof Divider) {
                            return $child->setParent($child->parent);
                        }

                        return $child->setParent($child->parent)->setChildren([]);
                    })->values(),
                ]);
            })
            ->sortBy('order')
            ->values()
            ->filter(function ($page) {
                return $page->permission
                    ? auth()->user()->can($page->permission)
                    : true;
            });
    }
}
