<?php

namespace apexl\Io\modules\userDisplay\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\display\components\BasicLink;
use apexl\Io\modules\display\components\CardEntityFilteredDisplayTable;
use apexl\Io\modules\display\components\genericComponents;
use apexl\Io\modules\display\services\Render;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\enums\permissions\Role;
use apexl\Io\modules\user\services\CurrentUserFactory;
use apexl\Io\modules\user\services\Permissions;
use apexl\Io\modules\userDisplay\components\dashboardTiles;
use apexl\Io\modules\userDisplay\forms\rolesForm;
use apexl\Io\services\Output;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class rolesController extends Controller
{
    public function __construct(
        protected Render $render, protected Permissions $permissions,
        Output $output,
    ) {
        parent::__construct($output);
    }


    /**
     * View the roleDisplay.
     * @return ResponseInterface
     */
    public function view(ServerRequestInterface $request, ResponseInterface $response, $args): ResponseInterface
    {
        $rowWrapper = genericComponents::rowWrapper('manageForm-wrapper col-sm-12');
        $rowWrapper->addComponent(dashboardTiles::roleViewTile($args['id']));

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

    public function roleList(RouteManager $routeManager, CurrentUserFactory $currentUserFactory, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $this->render->setPageTitle('Roles List');

        $components = [];

        $currentUser = $currentUserFactory->get();
        if ($currentUser && ($currentUser->isAllowed(Role::CREATE))) {
            $createButton = (new BasicLink())
                ->addText('Create Role')
                ->addRoute($routeManager->getRoutePattern('roleEntity.display.post'))
                ->addClass('btn btn-primary');
            $components[] = $createButton;
        }

        $components[] = (new CardEntityFilteredDisplayTable(new roleEntity(), [], false, 'dropmenu'))
            ->displayPagination(FALSE)
            ->displayShortTotals(FALSE)
            ->hideIdColumn()
            ->addDropMenuItem('roleEntity.display.put', 'Edit')
            ->addTitle('Roles List');

        $this->output->addResponse($request, $this->render->build($components));
        return $this->json($response);
    }

    public function create(ServerRequestInterface $request, ResponseInterface $response, $args): ResponseInterface
    {
        $title = 'Create new role';
        if ($id = $args['id'] ?? false) {
            $role = new roleEntity();
            $role->load($id);
            $title = 'Update ' . $role->name;
        }
        $form = rolesForm::rolesForm($args, $this->permissions);
        $this->render->setPageTitle($title);
        $this->output->addResponse($request, $this->render->build([genericComponents::dashboardBlockWrapper([$form])]));
        return $this->json($response);
    }


    /**
     * @param array $args
     * @return ResponseInterface
     */
    public function updateView(ServerRequestInterface $request, ResponseInterface $response, $args = []): ResponseInterface
    {
        $form = rolesForm::rolesForm($args, $this->permissions);
        $this->render->setPageTitle((isset($args['id']) ? 'Update' : 'Create') . ' Role');
        $this->output->addResponse($request, $this->render->build($form));
        return $this->json($response);
    }

    public function roleSummery(ServerRequestInterface $request, ResponseInterface $response, $args)
    {
        $structure = [
            'tableHeader' => [
                'Role ID',
                'Role Name',
                'Role Created',
                'Role Created By',
                'permissions',
            ],
            'fields' => [
                'id',
                'name',
                'created',
                'created_by',
                'permissions',
            ],
            'callables' => [
                'field__created' => function ($key, $entityId, $row) {
                    return \apexl\Io\modules\userDisplay\callbacks\tableRowAlters::roleShortTable(
                        $key,
                        $entityId,
                        $row
                    );
                },
                'field__created_by' => function ($key, $entityId, $row) {
                    return \apexl\Io\modules\userDisplay\callbacks\tableRowAlters::roleShortTable(
                        $key,
                        $entityId,
                        $row
                    );
                },
                'field__permissions' => function ($key, $entityId, $row) {
                    return \apexl\Io\modules\userDisplay\callbacks\tableRowAlters::roleShortTable(
                        $key,
                        $entityId,
                        $row
                    );
                }
            ]
        ];
        return $this->getEntityData($request, $response, $args, (new roleEntity()), [], $structure);
    }
}
