<?php

namespace Plainwork\DatabaseWordPress;

class WordPressUserHelper
{
    public static function getUserFullName($wpUser): string
    {
        $firstName = $wpUser->user_firstname;
        $lastName = $wpUser->user_lastname;

        if (!empty($firstName) && !empty($lastName)) {
            $ret = $firstName . ' ' . $lastName;
        } elseif (!empty($first_name)) {
            $ret = $first_name;
        } elseif (!empty($lastName)) {
            $ret = $lastName;
        } else {
            $ret = $wpUser->display_name; // Fallback to display name
        }

        return $ret;
    }

    public static function getAllRoles()
    {
        global $wp_roles;

        $ret = [];
        foreach ($wp_roles->roles as $id => $e) {
            $ret[$id] = $e['name'];
        }

        return $ret;
    }

    public static function getUserRoles($wpUser): array
    {
        $ret = [];

        if (!$wpUser->roles) {
            return $ret;
        }

        foreach ($wpUser->roles as $roleId) {
            $ret[$roleId] = $roleId;
        }

        $allRoles = static::getAllRoles();
        $ret = array_intersect_key($allRoles, $ret);

        return $ret;
    }

    public static function getRolesById(int $userId): array
    {
        static $cache = [];

        if (!isset($cache[$userId])) {
            $ret = [];

            $wpUser = get_user_by('id', $userId);
            if ($wpUser) {
                $ret = static::getUserRoles($wpUser);
            }

            $cache[$userId] = $ret;
        }

        return $cache[$userId];
    }

    public static function getUserRolesById(int $userId): array
    {
        static $cache = [];

        if (!isset($cache[$userId])) {
            $ret = [];

            $wpUser = get_user_by('id', $userId);
            if ($wpUser) {
                $ret = static::getUserRoles($wpUser);
            }

            $cache[$userId] = $ret;
        }

        return $cache[$userId];
    }

    public static function getWordPressRole($userId)
    {
        static $cache = [];

        if (!isset($cache[$userId])) {
            $ret = [];

            $wpUser = get_user_by('id', $userId);
            if ($wpUser) {
                $ret = static::getUserRoles($wpUser);
            }

            $cache[$userId] = $ret;
        }

        return $cache[$userId];
    }

    public static function countUserByRole()
    {
        $ret = count_users();

        return $ret['avail_roles'] ?? [];
    }
}
