<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

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

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

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

    // public function setPasswordAttribute($password) {
    //     $this->attributes['password'] = Hash::make($password);
    // }
        
    public function roles() {
        return $this->belongsToMany('App\Models\Role');
    }

    public function rolesUser() {
        $result = DB::table('role_user')->get();
        return $result;
    }

    /**
     * Check if the user has a role
     * @param string $role
     * @return bool
     */ 
    public function hasAnyRole($role) {
        return null !== $this->roles()->where('name', $role)->first();
    }

    /**
     * Check if the user has any given roles
     * @param array $role
     * @return bool
    */
    public function hasAnyRoles(array $role) {
        return null !== $this->roles()->whereIn('name', $role)->first();
    }

    public function getRole($user) {
        // $rolename = $this->roles()->find('name')->where('user_id', $user)->get();
        // DB::enableQueryLog();
        $result = $this->roles()->where('user_id', $user)->first();
        // dd(DB::getQueryLog());

        return $result;
        // return null !== $this->roles()->where('user_id', $user)->get();
    }  

    public function getResidential($user) {
        $result = $this->rolesUser()->where('user_id', $user)->first();
        
        return $result;
    }

    public function getUserData($id) {
        $result = DB::table('users')->where('id', $id)->get();
        return $result;
    }

}
