<?php
namespace App\Models\Games;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Game extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'title',
        'description',
        'category_id',
        'game_url',
        'thumbnail_url',
        'instructions',
        'is_featured',
        'is_active',
        'plays_count',
        'is_multiplayer',
        'min_age',
        'slug'
    ];

    protected $casts = [
        'is_featured' => 'boolean',
        'is_active' => 'boolean',
        'is_multiplayer' => 'boolean'
    ];

    // Relationships
    public function category()
    {
        return $this->belongsTo(GameCategory::class, 'category_id');
    }

    public function ratings()
    {
        return $this->hasMany(GameRating::class);
    }

    public function playHistory()
    {
        return $this->hasMany(GamePlayHistory::class);
    }

    // Calculate average rating
    public function getAvgRatingAttribute()
    {
        return $this->ratings()->avg('rating') ?: 0;
    }

    // Scopes
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopePopular($query)
    {
        return $query->orderBy('plays_count', 'desc');
    }

    public function scopeNewest($query)
    {
        return $query->orderBy('created_at', 'desc');
    }

    public function scopeTopRated($query)
    {
        return $query->withAvg('ratings', 'rating')
            ->orderBy('ratings_avg_rating', 'desc');
    }
}
