<?php

namespace App;

use App\Module;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;


class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password' , 'phone', 'photo','role_id','appetite','type_food','time_wake','time_meal','time_sleep','time_work',
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Get the modules of this user
     * @return BelongsToMany
     */
     public function photos()
    {
        return $this->hasMany(DoctorImage::class);
    }
     public function role()
    {
        return $this->belongsTo(Role::class,'role_id')->withTrashed();
    }
    public function modules()
    {
        return $this->belongsToMany(Module::class,'role_modules','role_id','module_id');
    }
    
    public function details()
    {
        return $this->hasOne('App\UserDescription','user_id');
    }
    public function branch()
    {
        return $this->hasMany('App\BranchUser');
    }
    
    public function branches()
    {
        return $this->belongsToMany('App\BranchUser','branch_users','user_id','branch_id');
    }
    public function specialty()
    {
        return $this->belongsToMany('App\SpecialtyPatient','specialty_patients','user_id','specialty_id');
    }
    
    /**
     * Check if the user can access a module
     * @param string, module name
     * @return bool
     */
    public function hasModule($module)
    {   
       if(rolemodule($this->role_id,$module))
        {
            return true;
        }
        return false;
    }

    /**
     * Check if the user can access a module
     * @param string, module name
     * @return bool
     */
    public function canAccess($module)
    {
        
        $module = Module::where('path',$module)->first();
        $module_id = $module->id ;
        if ( 'admin' == $this->role_id ) {
            return true;
        }else {
            return $this->hasModule($module_id);
        }
        return false;
    }
}
