<?php
namespace services\authorization;

use models\UserRole;
/**
 * Role assignation service
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2019-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class AssignUserRoles {

    private $userId;
    private $roles;

    public function __construct( $userId, array $roles ) {
        $this->userId = $userId;
        $this->roles = $roles;
    }

    public function perform( $listener ) {
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'assign_user_roles' );
        
        $userRoles = UserRole::findMany( '*', ['user_id' => $this->userId] );
        foreach( $this->roles as $roleId => $isAssigned ) {
            if ( $isAssigned && ( !in_array( $roleId, array_column( $userRoles, 'role_id' ) ) ) ) {
                $userRole = new UserRole();
                $userRole->user_id = $this->userId;
                $userRole->role_id = $roleId;
                $userRole->save();
            } else if ( !$isAssigned && ( in_array( $roleId, array_column( $userRoles, 'role_id' ) ) ) ) {
                $userRole = array_column( $userRoles, NULL, 'role_id' )[$roleId];
                $userRole->delete();         
            }
        }
    }
}
