<?php

namespace App\Entities;

use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Sluggable;
    use SoftDeletes;

    protected $table = "users";
    protected $dates = ['deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'slug', 'last_first_name', 'email', 'admin', 'password', 'role_id', 'soporte'
    ];

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

    /**
     * @param $value
     */
    public function setLastFirstNameAttribute($value)
    {
        $this->attributes['last_first_name'] = mb_strtoupper($value, 'utf-8');
    }

    /**
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    /**
     * @return string
     */
    public function getFullNamesAttribute()
    {
        return $this->explodeName(',');
    }

    /**
     * @return string
     */
    public function getFullNameAttribute()
    {
        return $this->explodeName();
    }

    /**
     * @param null $separator
     * @return string
     */
    private function explodeName($separator = null)
    {
        $last_first_name = explode(' ', $this->last_first_name);
        $last = array_pop($last_first_name);
        $plast = array_pop($last_first_name);

        return $plast . "{$separator} " . $last;
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    /**
     * @return array
     */
    public function sluggable()
    {
        return [
            'slug' => [
                'source' => ['last_first_name']
            ]
        ];
    }
}
