<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;


    protected $table = 'user';
    public $timestamps = false;
    protected $primaryKey = 'id';

    protected $fillable = [
        'msnv',
        'name',
        'mail',
        'pass',
        'departments',
        'avatar',
        'role',
        'status',
        'card',
        'flag_send',
        'first_login',
    ];

    protected $hidden = [
        'pass',
    ];

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->pass;
    }

    // Disable remember token support in database
    public function getRememberToken()
    {
        return null;
    }

    public function setRememberToken($value)
    {
    }

    public function getRememberTokenName()
    {
        return '';
    }

    public function transactions()
    {
        return $this->hasMany(Administration::class, 'msnv', 'msnv');
    }

    public function cardPurchases()
    {
        return $this->hasMany(AddCard::class, 'buyer', 'msnv');
    }

    /**
     * Get the user's avatar URL.
     * If the user doesn't have an avatar, returns the default avatar.
     *
     * @param  string|null  $value
     * @return string
     */
    public function getAvatarAttribute($value)
    {
        if (!$value || strtolower($value) === 'null') {
            return asset('images/avatar.png');
        }

        // Return direct URL if it's already an absolute URL (for backward compatibility)
        if (filter_var($value, FILTER_VALIDATE_URL)) {
            return $value;
        }

        return asset($value);
    }

    /**
     * Get the user's department name.
     *
     * @return string|null
     */
    public function getDepartmentNameAttribute()
    {
        $deptVal = $this->departments;
        if (is_numeric($deptVal)) {
            $idx = ((int)$deptVal) - 1;
            return config('constants.DEPARTMENTS')[$idx] ?? $deptVal;
        }
        return $deptVal;
    }
}

