<?php

namespace App;

use Illuminate\Notifications\Notifiable;
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',
  ];

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

  //Encrypt password when it's set - this ensures encryption is handled in one place
  public function setPasswordAttribute($password){
    $this->attributes['password'] = bcrypt($password);
  }

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

  public function getPerms(){
    $roles = $this->roles;
    $perms = array();
    foreach ($roles as $role){
      foreach ($role->permissions as $permission){
        $perms[$permission->id]=str_replace(' ', '', $permission->name);
      }
    }
    return $perms;
  }
  public function getAdmin(){
    $roles = $this->roles;
    $categories = array();
    foreach ($roles as $role){
      foreach ($role->permissions as $permission){
        array_push($categories,$permission->category);
      }
    }
    return array_diff(array_unique($categories),[]);
  }
  public function hasPerm($permlist){
    $testperms = explode('.',$permlist);
    $perms = $this->getPerms();
    foreach ($testperms as $perm){
      if (in_array($perm,$perms)){
        return true;
      }
    }
    return false;
  }

  public function recipes(){
    return $this->hasMany('App\Recipe');
  }
}
