<?php

namespace Apexl\Io\Admin\Display\Controllers;

use Apexl\Io\Admin\Display\Components\MenuTile;
use Apexl\Io\Display\Components\RowWrapper;
use Apexl\Io\Display\Controllers\DisplayController;
use Apexl\Io\Display\Services\Render;
use Apexl\Io\Menu\Services\MenuManager;
use Apexl\Io\User\Entities\UserEntity;
use Apexl\Io\User\Services\CurrentUserFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class AdminDisplayController extends DisplayController
{
    public ?UserEntity $currentUser;
    public MenuManager $menu;


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

        $rowWrapper = $this->component(RowWrapper::class);
        $rowWrapper->addClass('flex-gap');
        // Get all administration links, loop over them and split them by parent item.
        // 'administration' is the menu key adminDisplayModule registers admin
        // items under (see menuItems()). Was coupled to a consuming project's
        // Menu enum; use the framework key directly so io-admin is standalone.
        $menu = $menuManager->getMenu('administration');
        $menuItems = $menu->getAllItemsAsMenu($currentUserFactory->get());
        foreach ($menuItems as $item) {
            if (isset($item->links)) {
                $tile = $this->component(MenuTile::class, ['title' => $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);
    }
}
