<?php

namespace apexl\Io\modules\userDisplay\components;

use apexl\Io\includes\Hook;
use apexl\Io\includes\Routes;
use apexl\Io\modules\display\components\BasicLink;
use apexl\Io\modules\display\components\DisplayTable;
use apexl\Io\modules\display\components\FormComponent;
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\services\currentUser;
use apexl\Io\modules\user\services\Permissions;

class dashboardTiles
{
    public static function roleViewTile($id)
    {
        $role = roleEntity::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 = Permissions::getInstance();
        $enabledPerms = [];
        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 = currentUser::getCurrentUser();
        $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 !== '' && $userEntity->active !== '0' ? 'Yes' : 'No'));
        $userInfo->addData('Last Login', date('d-m-Y', $userEntity->last_login));
        $userInfo->addData('Created', date('d-m-Y', $userEntity->created));

        if ($currentUser->isAllowed('CreateUsers')) {
            $adminInfo = new DisplayTable();

            $createdUser = userEntity::load($userEntity->created_by);
            if ($createdUser->id) {
                $adminInfo->addData('Created By', (new BasicLink())->addRoute(Routes::getRoutePattern('userEntity.display.get', ['id' => $createdUser->id]))->addText($createdUser->getNiceName()));
            }
            if ($userEntity->modified !== '' && $userEntity->modified !== '0') {
                $adminInfo->addData('Modified', date('d-m-Y', $userEntity->modified));
                $modifiedUser = userEntity::load($userEntity->modified_by);
                if ($modifiedUser->id) {
                    $adminInfo->addData('Modified By', (new BasicLink())->addRoute(Routes::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 = Hook::processHook('userDisplayAlter', $components, $userEntity->id);
        if (!empty($components)) {
            foreach ($components as $component) {
                $userContent->addComponent($component);
            }
        }

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

        $components = [
            $userTitle,
            $userContent,
            $roleList,
        ];

        if($currentUser->isAllowed('ManageUsers')) {
            $form = (new FormComponent())
                ->src(Routes::getRoutePattern('user.display.forms.loginAsUser', ['userId' => $userEntity->id]))
                ->setID("loginAsUserForm");
            $components[] = $form;
        }

        //build tile
        return genericComponents::dashboardBlockWrapper($components);
    }
}