<?php

namespace apexl\Io\modules\userDisplay\callbacks;

use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\entities\userEntity;

class tableRowAlters {

    /**
     * A field callback for the getEntityData method.
     * @param $key
     * @param $entityId
     * @param $row
     * @return string
     */
    public static function userShortTable($key, $entityId, $row){
        //switch on the provided key so we know what we're working with
        $entity = new userEntity();
        $entity->load($entityId);
        switch($key) {
            case 'field__last_login':
                return isset($row['last_login']) ? date('d-m-Y H:i:s', $row['last_login']) : 'never';
            case 'field__first_name':
                return $row['first_name'].' '.$row['last_name'];
                break;
            case 'field__roles':
                $roles = unserialize($row['roles']);
                $cleanRoles = [];
                if($roles) {
                    foreach ($roles as $rid) {
                        $role = new roleEntity();
                        $role->load($rid);
                        if ($roleId = $role->id ?? FALSE) {
                            $cleanRoles[] = $role->name;
                        }
                    }
                    return implode(', ', $cleanRoles);
                }
                break;
        }
        return '';
    }

    public static function roleShortTable($key, $entityId, $row){
        //switch on the provided key so we know what we're working with
        $entity = new roleEntity();
        $entity->load($entityId);

        switch($key) {
            case 'field__created':
                return isset($row['created']) ? date('d-m-Y H:i:s', $row['created']) : 'Unknown';
            case 'field__created_by':
                $user = new userEntity();
                $user->load($row['created_by']);
                return $user->getNiceName();
                break;
            case 'field__permissions':
                $perms = unserialize($row['permissions']);
                return count($perms);
        }
        return '';
    }
}