<?php

namespace apexl\Io\modules\userDisplay\components;

use apexl\Io\includes\HookManager;
use apexl\Io\modules\display\components\BasicLink;
use apexl\Io\modules\display\components\DisplayTable;
use apexl\Io\modules\display\components\genericComponents;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\enums\permissions\User;
use apexl\Io\modules\user\services\Permissions;
use function apexl\Io\container;

class dashboardTiles
{
    public static function roleViewTile($id)
    {
        $role = new roleEntity();
        $role->load($id);
        $roleTitle = genericComponents::ContentTitle($role->name, 'Viewing the role and its permissions');

        //build the content display. To do this we need to get the role permissions and loop over them.
        $roleContent = genericComponents::rowWrapper('role-permissions');
        $allPerms = container()->get(Permissions::class);
        $enabledPerms = [];
        if ($role->permissions) {
            foreach ($role->permissions as $permission) {
                $permObject = $allPerms->getPermission($permission);
                //we might have permissions that no longer exist, so account for those.
                if ($permObject) {
                    $enabledPerms[$permObject->group][] = $permObject->name;
                }
            }
            //loop over the new grouped perms
            foreach ($enabledPerms as $group => $perms) {
                $roleContent->addComponent(genericComponents::listTile($group, $perms));
            }
        }

        //Tile footer
        $roleButtonWrapper = genericComponents::rowWrapper('tile-footer');
        $roleButtonWrapper->addComponent(genericComponents::simpleButtonLink('/roles/view', 'View all'));
        $roleButtonWrapper->addComponent(genericComponents::simpleButtonLink('/roles/create', 'Create a role'));
        $roleButtonWrapper->addComponent(
            genericComponents::simpleButtonLink('/roles/' . $id . '/edit', 'Edit this role')
        );
        $roleButtonWrapper->addComponent(
            genericComponents::simpleButtonLink('/roles/' . $id . '/delete', 'Delete this role')
        );

        //build tile
        return genericComponents::dashboardBlockWrapper([
            $roleTitle,
            $roleContent,
            $roleButtonWrapper,
        ]);
    }

    public static function userViewTile($id)
    {
        $currentUser = $this->currentUserFactory->get();
        $userEntity = new userEntity();
        $userEntity->load($id);
        $userTitle = genericComponents::ContentTitle($userEntity->getNiceName(), 'Viewing this user.');

        //build the content display. To do this we need to get the role permissions and loop over them.
        $userInfo = new DisplayTable();
        $userInfo->addData('Email', $userEntity->email);
        $userInfo->addData('Active', $userEntity->active ? 'Yes' : 'No');
        $userInfo->addData('Last Login', $userEntity->last_login?->format('d-m-Y'));
        $userInfo->addData('Created', $userEntity->created?->format('d-m-Y'));

        if ($currentUser->isAllowed(User::CREATE)) {
            $adminInfo = new DisplayTable();

            if ($userEntity->created_by ?? false) {
                $createdUser = new userEntity();
                $createdUser->load($userEntity->created_by);
                if ($createdUser->id ?? false) {
                    $adminInfo->addData(
                        'Created By',
                        (new BasicLink())->addRoute(
                            $this->routeManager->getRoutePattern('userEntity.display.get', ['id' => $createdUser->id])
                        )->addText($createdUser->getNiceName())
                    );
                }
            }
            if (!!$userEntity->modified) {
                $adminInfo->addData('Modified', $userEntity->modified->format('d-m-Y'));
                $modifiedUser = new userEntity();
                if ($userEntity->modified_by ?? false) {
                    $modifiedUser->load($userEntity->modified_by);
                    if ($modifiedUser->id ?? false) {
                        $adminInfo->addData(
                            'Modified By',
                            (new BasicLink())->addRoute(
                                $this->routeManager->getRoutePattern(
                                    'userEntity.display.get',
                                    ['id' => $modifiedUser->id]
                                )
                            )->addText($modifiedUser->getNiceName())
                        );
                    }
                }
            }
        }
        $components = [];
        $components[] = genericComponents::ContentTitle("Account");
        $components[] = $userInfo;
        if ($adminInfo) {
            $components[] = genericComponents::ContentTitle("Administration");
            $components[] = $adminInfo;
        }

        //allow modules to add content to the user display.
        $userContent = genericComponents::rowWrapper('user-view-tile');
        $components = HookManager::processHook('userDisplayAlter', $components, $userEntity->id);
        if (!empty($components)) {
            foreach ($components as $component) {
                $userContent->addComponent($component);
            }
        }

        //convert roles into readable names
        $roles = [];
        if (is_iterable($userEntity->roles)) {
            foreach ($userEntity->roles ?? [] as $rid) {
                $role = new roleEntity();
                $role->load($rid);
                if ($role->id !== '' && $role->id !== '0') {
                    $roles[] = $role->name;
                }
            }
        }
        $roleList = genericComponents::listTile('Roles', $roles);

        //build tile
        return genericComponents::dashboardBlockWrapper([
            $userTitle,
            $userContent,
            $roleList,
        ]);
    }
}
