<?php

namespace apexl\Io\modules\adminDisplay\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\modules\adminDisplay\components\menuTile;
use apexl\Io\modules\display\components\RowWrapper;
use apexl\Io\modules\display\services\Render;
use apexl\Io\modules\menu\services\MenuManager;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\CurrentUserFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class AdminDisplayController extends Controller
{
    public ?userEntity $currentUser;
    public MenuManager $menu;


    public function __invoke(CurrentUserFactory $currentUserFactory, MenuManager $menu, Render $render, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $render->setPageTitle('Administration Dashboard');

        $rowWrapper = new RowWrapper();
        $rowWrapper->addClass('flex-gap');
        // Get all administration links, loop over them and split them by parent item.
        $items = $menu::getMenu('administration');
        $menuItems = $items->getAllItemsAsMenu($currentUserFactory->get());
        foreach ($menuItems as $item) {
            if (isset($item->links)) {
                $tile = new menuTile($item->title);
                foreach ($item->links as $routeInfo) {
                    $tile->addButton($routeInfo->href, $routeInfo->title, $routeInfo->icon);
                }
                $rowWrapper->addComponent($tile);
            }
        }

        $this->output->addResponse($request, $render->build([$rowWrapper]));

        return $this->json($response);
    }
}
