<?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;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'username',
        'email',
        'phone',
        'password',
        'seller_id',
        'status'
    ];

    /**
     * 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 = [
        'password' => 'hashed',
    ];

    public function peers()
    {
        return $this->hasMany(Peer::class);
    }
    public function active_peers()
    {
        $peers = $this->peers;
        $active_peers = [];
        foreach ($peers as $peer) {
            if ($peer->is_active()) {
                $active_peers[] = $peer;
            }
        }
        return $active_peers;
    }
    public function seller()
    {
        return $this->belongsTo(Seller::class);
    }

    public function log($log){
        UserLog::create([
            'user_id' => $this->id,
            'log' => $log
        ]);
    }
    public function logs(){
        return $this->hasMany(UserLog::class);
    }

    public function last_activity(){
        $last_log = $this->logs()->orderBy('created_at','desc')->first();
        if($last_log == null){
            return null;
        }
        return $last_log->created_at;
    }
}
