<?php

namespace App\Models\OLDLMS;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;


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

    const CREATED_AT = 'dCreateOn';
    const UPDATED_AT = 'dUpdateOn';
    const DELETED_AT = 'dDeleteOn';

    protected $connection = 'oldlms';

    protected $table = 'tm_users';

    protected $appends = [
        'full_name',
    ];

    protected $primaryKey = 'nID';
    protected $fillable = [
        'nID',
        'sFirstName',
        'sLastName',
        'sPhone',
        'sEmail',
        'nIDHubunganKeluarga',
        'dUpdateOn',
    ];

    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: function ($value) {
                $names = [];
                if (!empty($this->sFirstName)) {
                    array_push($names, $this->sFirstName);
                }
                if (!empty($this->sLastName)) {
                    array_push($names, $this->sLastName);
                }

                return implode(' ', $names);
            }
        );
    }

    public function detail()
    {
        return $this->hasOne(UserDetail::class, 'nIDUser', 'nID');
    }
    
    public function insurances()
    {
        return $this->hasMany(UserInsurance::class, 'nIDUser', 'nID');
    }

    public function notificationTokens()
    {
        return $this->morphMany(NotificationToken::class, 'notifiabletoken');
    }
}
