<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class GameInfo extends Model
{
    protected $table = 'game_info';

    protected $fillable = [
        'category_name',
        'sort',
        'title',
        'body',
        'image',
        'active'
    ];

    protected $casts = [
        'active' => 'boolean',
    ];

    // Scope for active records
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    // Scope for specific category
    public function scopeByCategory($query, $category)
    {
        return $query->where('category_name', $category);
    }

    // Get distinct categories
    public static function getCategories()
    {
        return static::active()
            ->select('category_name')
            ->distinct()
            ->orderBy('category_name')
            ->pluck('category_name');
    }

    // Get categories with counts
    public static function getCategoriesWithCounts()
    {
        return static::active()
            ->select('category_name')
            ->selectRaw('COUNT(*) as count')
            ->groupBy('category_name')
            ->orderBy('category_name')
            ->get()
            ->pluck('count', 'category_name');
    }

    // Get excerpt from body
    public function getExcerptAttribute($length = 150)
    {
        return Str::limit(strip_tags($this->body), $length);
    }

    // Get image URL
    public function getImageUrlAttribute()
    {
        return $this->image ? asset('storage/' . $this->image) : asset('assets/images/default-game-guide.png');
    }
}
