<?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 Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Facades\Request;

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

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

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

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


    public function getRoles()
    {
        $roles=$this->getRoleNames();
        $liste="";
        foreach($roles as $role) $liste.=(($liste=="")?"":"<br/>").$role;
        return $liste;
    }

    
    public function getLastConnectionAttribute()
    {
        $last_cnx =  Connection::where('login', '=', $this->email)
            ->orderby('date','DESC')
            ->first();
        if($last_cnx) return $last_cnx->date;
        return "";
     }

    public function addConnection() {
        $request = Request::instance();
        $adress=$request->getClientIp();
        $connection = new Connection;
        $connection->ip = $adress;
        $connection->login  = $this->email;
        $connection->date   = date('Y-m-d H:i:s');
        $connection->ucname = "";//$connection->ucname = gethostbyaddr($adress); 
        $connection->save();
    }
}
