<?php
// app/Models/Category.php

namespace App\Models;

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

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'name_en',
        'name_ar',
        'slug',
        'description',
        'description_en',
        'description_ar',
        'content_type',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'featured_image',
        'icon',
        'color',
        'order',
        'is_active',
        'is_featured',
        'parent_id'
    ];

    protected $casts = [
        'description' => 'array',
        'meta_title' => 'array',
        'meta_description' => 'array',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
    ];

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

        static::creating(function ($category) {
            if (empty($category->slug)) {
                $category->slug = Str::slug($category->name_en);
            }
        });
    }

    // Helper methods to get localized content
    public function getLocalizedName($locale = null)
    {
        $locale = $locale ?? app()->getLocale();

        switch ($locale) {
            case 'bn':
                return $this->name;
            case 'en':
                return $this->name_en;
            case 'ar':
                return $this->name_ar;
            default:
                return $this->name_en;
        }
    }

    public function getLocalizedDescription($locale = null)
    {
        $locale = $locale ?? app()->getLocale();
        return $this->description[$locale] ?? $this->description['en'] ?? '';
    }

    public function getLocalizedMetaTitle($locale = null)
    {
        $locale = $locale ?? app()->getLocale();
        return $this->meta_title[$locale] ?? $this->meta_title['en'] ?? '';
    }

    public function getLocalizedMetaDescription($locale = null)
    {
        $locale = $locale ?? app()->getLocale();
        return $this->meta_description[$locale] ?? $this->meta_description['en'] ?? '';
    }

    // Relationships
    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function contents()
    {
        return $this->hasMany(Content::class);
    }

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

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

    public function scopeParents($query)
    {
        return $query->whereNull('parent_id');
    }

    public function scopeByContentType($query, $type)
    {
        return $query->where('content_type', $type);
    }
}
