<?php

declare(strict_types=1);

namespace App\Models\Pouzivatel;

/**
 * Class RoleAndPermissionsAggregator
 *
 * @package App\Models\Pouzivatel
 */
final class RoleAndPermissionsAggregator
{
    /**
     * @var array|\App\Models\Pouzivatel\RolesPermissions[]
     */
    protected array $roles;

    /**
     * RoleAndPermissionsRepository constructor.
     *
     * @param \App\Models\Pouzivatel\RolesPermissions ...$roles
     */
    public function __construct(RolesPermissions ...$roles)
    {
        $this->roles = $roles;
    }

    /**
     * @param array $aisekRole
     *
     * @return array
     */
    public function vratOpravneniaPreRole(array $aisekRole = []): array
    {
        $roles = [];

        collect($this->roles)->each(function (RolesPermissions $rp) use (&$roles) {
            $roles = array_merge_recursive($roles, $rp::vratOpravnenia());
        });

        return $this->vyhladaj($aisekRole, $roles);
    }

    /**
     * @param array $aisekRole
     *
     * @return array
     */
    public function vratRolePreRole(array $aisekRole = []): array
    {
        $roles = [];

        collect($this->roles)->each(function (RolesPermissions $rp) use (&$roles) {
            $roles = array_merge_recursive($roles, $rp::vratRole());
        });

        return $this->vyhladaj($aisekRole, $roles);
    }

    /**
     * @param array $co
     * @param array $kde
     *
     * @return array
     */
    protected function vyhladaj(array $co, array $kde): array
    {
        $role = [];

        collect($co)->each(function ($_rola) use (&$role, $kde) {
            if (array_key_exists($_rola, $kde)) {
                $role = array_merge($role, $kde[$_rola]);
            }
        });

        return array_unique($role);
    }
}
