<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'tel', 'lastname', 'patronymic'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Models\Role', 'role_user');
    }

    public function canDo($value, $require = FALSE)
    {
        if (is_array($value)) {
            foreach ($value as $val) {
                $permName = $this->canDo($val);
                if ($permName && !$require) {
                    return true;
                } elseif (!$permName && $require) {
                    return false;
                }
            }
            return true;
        } else {
            foreach ($this->roles as $role) {
                foreach ($role->permissions as $permission) {
                    if (str_is($value, $permission->name)) {
                        return true;
                    }
                }
            }
        }
    }
}
