<?php

namespace App;

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


/**
 * @property mixed role
 * @property mixed modules
 * @property mixed password
 * @property mixed device_token
 * @property mixed phone
 * @mixin  Builder
 */
class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'gender',
        'employer',
        'city_id', // Country code +966
        'device_token',
        'api_token',
        'verify_code',
        'attempt_send_code',
        'last_attempt_date',
        'code_verify_attempt',
        'photo',
        'status',
        'agreement',
        'admin_token',
        'email_verified_at',
        'password',
        'role',
    ];

    /**
     * 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',
        'device_token' => 'array',
    ];


    public function routeNotificationForFcm()
    {
//        return $this->getDeviceTokens();
        return is_string($this->device_token) ? json_decode($this->device_token, true)['token'] : ($this->device_token['token'] ?? null);
    }

    /**
     * Get the modules of this user
     * @return BelongsToMany
     */
    public function modules() :BelongsToMany
    {
        return $this->belongsToMany(Module::class,'user_modules');
    }

    /**
     * Check if the user can access a module
     * @param string, module name
     * @return bool
     */
    public function hasModule($module) :bool
    {
        if($this->modules->contains('path',$module))
        {
            return true;
        }
        return false;
    }

    /**
     * Check if the user can access a module
     * @param string, module name
     * @return bool
     */
    public function canAccess($module)
    {
        if ($this->role == 'super_admin') {
            return true;
        } else {
            return $this->hasModule($module);
        }
        return false;
    }


    public function evaluates()
    {
        return $this->hasMany(ConsultingEvaluate::class);
    }


    public function coupon()
    {
        return $this->hasOne(Coupon::class);
    }
}
