<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Spatie\Permission\Traits\HasRoles;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'type',
        'username',
        'mobile_number',
        'redemption_pin',
        'referral_code',
        'referral_by',
        'chain_type',
        'address',
        'level',
        'last_login'
        
        
    ];

    /**
     * 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',
        'password' => 'hashed',
    ];
    public function currentLanguage()
    {
        return $this->lang;
    }
    public function referrer()
    {
        return $this->belongsTo(User::class, 'referral_by');
    }

    

    public function generateToken()
    {
        $this->api_token = hash('sha256', Str::random(60));
        $this->save();
        return $this->api_token;
    }

    public function apiFormat()
    {
        $data = $this->toArray();
        
        unset($data['type']);
        unset($data['updated_at']);
        unset($data['created_at']);
        $data['avatar'] = Storage::url($data['avatar']);
        
        return array_map(function ($value) {
            return is_null($value) ? '' : $value;
        }, $data);
    }
}
