<?php

namespace App;

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

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'nickname', 'email', 'password', 'role_id'
    ];

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

    public function role()
    {
        return $this->belongsTo('App\Models\Role', 'role_id', 'id');
//        return $this->hasOne('App\Models\Role', 'id', 'role_id');
    }

    public function items()
    {
        return $this->hasMany('App\Models\Item');
    }

    public function offersToUser()
    {
        return $this->hasManyThrough('App\Models\Offer', 'App\Models\Item', 'user_id', 'item_id');
    }

    public function offersFromUser()
    {
        return $this->hasManyThrough('App\Models\Offer', 'App\Models\Item', 'user_id', 'item_offer_id');
    }

    public function __get($key)
    {
        if ($key === 'name') return $this->attributes['nickname'];
        if ($key === 'role') {
            return $this->role()->first()->name;
        };
        return parent::__get($key);
    }

    public function isAdmin()
    {
        return ($this->role === 'admin');
//        return ($this->role()->first()->name === 'admin');
    }

}
