<?php
namespace App\Traits;

use App\Permissions;
use App\Roles;

trait HasPermissionsTait {
    // Get permissions
    public function getAllPermissions($permission)
    {
        return Permissions::whereIn('slug', $permission)->get();
    }

    // Check has permission
    public function hasPermission($permission)
    {
        return (bool) $this->permissions->where('slug', $permission->slug)->count();
    }

    // Check user has role
    public function hasRole(...$roles)
    {
        foreach ($roles as $role) {
            if($this->roles->contains('slug', $slug)){
                return true;
            }
        }
        return false;
    }

    public function hasPermissionTo($permission)
    {
        return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);
    }

    public function hasPermissionThroughRole($permissions)
    {
        foreach ($permissions->roles as $role) {
            if($this->roles->contains($role)){
                return true;
            }
        }
        return false;
    }

    // Give permission to user
    public function givePermissionTo(...$permissions)
    {
        $permissions = $this->getAllPermissions($permissions);
        if ($permissions == null) {
            return $this;
        }
        $this->permissions()->saveMany($permissions);
        return $this;
    }

    // Mention the relation
    public function permissions()
    {
        return $this->belongToMany(Permission::class, 'users_permissions');
    }

    public function roles()
    {
        return $this->belongToMany(Role::class, 'users_roles');
    }
}