<?php

namespace App\Models;

use App\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class TestCategory extends Model
{
    use HasFactory, HasTranslations;

    protected $fillable = [
        'name',
        'name_translations',
        'slug',
        'description',
        'description_translations',
        'icon',
        'sort_order',
        'is_active',
    ];

    protected $casts = [
        'name' => 'array',
        'name_translations' => 'array',
        'description' => 'array',
        'description_translations' => 'array',
        'is_active' => 'boolean',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($category) {
            if (empty($category->slug)) {
                $name = is_array($category->name)
                    ? ($category->name['en'] ?? $category->name['ar'] ?? '')
                    : $category->name;
                $category->slug = Str::slug($name);
            }
        });
    }

    /**
     * Get the translated name, handling both JSON column formats.
     * The 'name' column itself is JSON {"ar": "...", "en": "..."}.
     */
    public function getTranslatedNameAttribute(): string
    {
        $locale = app()->getLocale();
        $name = $this->getAttribute('name');

        if (is_array($name)) {
            return $name[$locale] ?? $name['ar'] ?? $name['en'] ?? '';
        }

        return $name ?? '';
    }

    /**
     * Get the translated description.
     */
    public function getTranslatedDescriptionAttribute(): ?string
    {
        $locale = app()->getLocale();
        $desc = $this->getAttribute('description');

        if (is_array($desc)) {
            return $desc[$locale] ?? $desc['ar'] ?? $desc['en'] ?? null;
        }

        return $desc;
    }

    public function tests()
    {
        return $this->hasMany(Test::class, 'test_category_id')
            ->orderBy('name');
    }

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

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }
}
