<?php

namespace KupShop\UserManagerBundle\Util;

use Query\Operator;

class UserManagerUtil
{
    public function isUserManager(int $userId): bool
    {
        $count = sqlQueryBuilder()
            ->select('COUNT(id_user)')
            ->from('users_manager_relations')
            ->where(
                Operator::equals(
                    [
                        'id_user_master' => $userId,
                    ]
                )
            )->execute()->fetchColumn();

        if ($count > 0) {
            return true;
        }

        return false;
    }

    public function isUserManaged(int $userId): bool
    {
        $exists = sqlQueryBuilder()
            ->select('id_user')
            ->from('users_manager_relations')
            ->where(
                Operator::equals(
                    [
                        'id_user' => $userId,
                    ]
                )
            )->execute()->fetchColumn();

        return (bool) $exists;
    }

    public function getManagedUsers(int $userId, bool $activeOnly = false): array
    {
        $qb = sqlQueryBuilder()
            ->select('u.id')
            ->from('users_manager_relations', 'umr')
            ->join('umr', 'users', 'u', 'u.id = umr.id_user')
            ->where(
                Operator::equals(
                    [
                        'umr.id_user_master' => $userId,
                    ]
                )
            );

        if ($activeOnly) {
            $qb->andWhere(Operator::equals(['u.figure' => 'Y']));
        }

        $users = [];
        foreach ($qb->execute() as $item) {
            $users[] = \User::createFromId($item['id']);
        }

        return $users;
    }
}
