<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

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

   // protected $appends = ['alerts'];

    protected $authPasswordName = 'password';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->reference = (new Snowflake)->id();
        });
    }

    public function getAlertsAttribute()
    {
        return $this->unreadnotifications()->latest()->take(50)->get();
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'company_id',
        'department_id',
        'branch_id',
        'first_name',
        'last_name',
        'name',
        'email',
        'password',
        'phone',
        'remember_token',
        'email_verified_at',
        'role_id',
        'last_login',
        'status',
        'created_by',
    ];

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


    /**
     *@return BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }

    /**
     *@return BelongsTo
     */
  
    /**
     *@return BelongsTo
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by')
            ->select('name', 'id');
    }

    /**
     * @return BelongsTo
     */
    public function department()
    {
        return $this->belongsTo(Department::class, 'department_id')
            ->select('pos_orders_destinations.id', 'pos_orders_destinations.name');
    }

    /**
     * @return BelongsTo
     */
    public function branch()
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }
}
