<?php

namespace App\Models;

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

class ProductCategory extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'slug',
        'description',
        'image',
        'is_active',
        'sort_order',
        'meta_title',
        'meta_keywords',
        'meta_description',
        'color',
        'text_color',
        'icon',
        'show_in_menu',
        'is_featured',
    ];

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

    public function clientVersions()
    {
        return $this->hasMany(ClientVersion::class, 'category_id');
    }
    
    public function products(): HasMany
    {
        return $this->hasMany(Product::class, 'category_id');
    }

    public function productVersions(): HasMany
    {
        return $this->hasMany(ProductVersion::class, 'category_id');    
    }

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

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

        static::updating(function ($category) {
            if ($category->isDirty('name')) {
                $category->slug = Str::slug($category->name);
            }
        });
    }
}
