<?php namespace App\Models;

use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Request;
use Spatie\Permission\Traits\HasPermissions;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Http\Controllers\Logs;

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

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }


    public function getRoles($sep="<br/>")
    {
        $roles=$this->getRoleNames();
        $liste="";
        foreach($roles as $role) $liste.=(($liste=="")?"":$sep).$role;
        return $liste;
     }
 
     /* test si administrateur system */
    public function getSysAdminAttribute()
    {
        if($this->name=="ADMINISTRATEUR") return true;
        return false;
    }

    //LOG
    public function log_transaction($url,$operation,$values="") {
        $log=new Logs;
        if($values=="") {
          $t_values=$this->getAttributes();
          foreach($t_values as $nom=>$value) $values.=(($values=="")?"":";").$nom."=>".$value;
        }

        $log->addlog(['url'=>$url,'table'=>$this->table ,'operation'=>$operation,'values'=>$values]);
    }

    /* SUPPRESSION */
    function getIsSupprimableAttribute() {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole("ADMINISTRATEUR") && !$user->can("USR_SUP")) return false;
        $roles=$this->getRoles();
        if(!$roles) return true;
        return false;
    }

    /* Modifiable */
    function getIsModifiableAttribute() {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole("ADMINISTRATEUR") && !$user->can("USR_MAJ")) return false;
        return true;
    }

}
