<?php

namespace App\Models\SRO_VT_ACCOUNT;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\Z_Website\User;
use App\Models\SRO_VT_ACCOUNT\SkSilk;

class TbUser extends Authenticatable
{
    use Notifiable;

    protected $connection = 'sqlsrv_account';
    public $timestamps = false;
    protected $table = 'dbo.TB_User';
    protected $primaryKey = 'JID';
    public $incrementing = true;
    protected $keyType = 'int';

    protected $fillable = [
        'StrUserID', 'Name', 'password', 'Email', 'Status', 'GMrank',
        'regtime', 'reg_ip'
    ];

    protected $hidden = ['password'];

    // Override للـ Authentication
    public function getAuthIdentifierName()
    {
        return 'StrUserID';
    }

    public function getAuthIdentifier()
    {
        return $this->{$this->getAuthIdentifierName()};
    }

    public function getAuthPassword()
    {
        return $this->password;
    }

    // تعطيل remember token لأنه غير موجود في DB
    public function getRememberToken()
    {
        return null;
    }

    public function setRememberToken($value)
    {
        // لا نفعل شيء
    }

    public function getRememberTokenName()
    {
        return null;
    }

    // علاقات
    public function webUser()
    {
        return $this->hasOne(User::class, 'JID', 'JID');
    }

    public function skSilk()
    {
        return $this->hasOne(SkSilk::class, 'JID', 'JID');
    }

    // دوال للـ UI
    public function getNameAttribute()
    {
        return $this->attributes['Name'] ?: $this->StrUserID;
    }

    public function initials()
    {
        $name = $this->Name ?: $this->StrUserID;
        $words = explode(' ', $name);
        if (count($words) >= 2) {
            return strtoupper(substr($words[0], 0, 1) . substr($words[1], 0, 1));
        }
        return strtoupper(substr($name, 0, 2));
    }
}
