<?php

namespace Plugins\SAMBans\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Player extends Model
{
    protected $connection = 'sambans';
    protected $table = 'sam_players';
    protected $primaryKey = 'steamid';
    public $incrementing = false;
    protected $keyType = 'string';
    public $timestamps = false;

    protected $fillable = [
        'steamid',
        'name',
        'last_seen'
    ];

    protected $casts = [
        'last_seen' => 'timestamp'
    ];

    // Relationships
    public function bans()
    {
        return $this->hasMany(Ban::class, 'steamid', 'steamid');
    }

    public function adminBans()
    {
        return $this->hasMany(Ban::class, 'admin', 'steamid');
    }

    // Scopes
    public function scopeSearch(Builder $query, $search)
    {
        return $query->where(function($q) use ($search) {
            $q->where('name', 'LIKE', "%{$search}%")
              ->orWhere('steamid', 'LIKE', "%{$search}%");
        });
    }

    public function scopeRecentlyActive(Builder $query)
    {
        return $query->orderBy('last_seen', 'desc');
    }

    // Accessors
    public function getSteamid64Attribute()
    {
        return Ban::steamid32To64($this->steamid);
    }

    public function getSteamProfileUrlAttribute()
    {
        $steamid64 = $this->steamid64;
        if ($steamid64) {
            return "https://steamcommunity.com/profiles/{$steamid64}";
        }
        return null;
    }

    public function getLastSeenHumanAttribute()
    {
        return $this->last_seen ? \Carbon\Carbon::createFromTimestamp($this->last_seen)->diffForHumans() : 'Never';
    }

    public function getActiveBansCountAttribute()
    {
        return $this->bans()->active()->count();
    }

    public function getTotalBansCountAttribute()
    {
        return $this->bans()->count();
    }

    public function getIsCurrentlyBannedAttribute()
    {
        return $this->active_bans_count > 0;
    }
}