<?php

declare(strict_types=1);

namespace App\Models\Pouzivatel;

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

    /**
     * RoleAndPermissionsRepository constructor.
     */
    public function __construct(RolesPermissions ...$roles)
    {
        $this->roles = $roles;
    }

    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);
    }

    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);
    }

    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);
    }
}
