<?php

namespace App\Models;

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

class Category extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'code',
        'image',
        'description',
        'name_km',
        'description_km',
        'parent_id',
    ];

    /**
     * Get the parent category.
     */
    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    /**
     * Get the subcategories (children).
     */
    public function subcategories()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    /**
     * Get the products for the category (using category_id).
     */
    public function products()
    {
        return $this->hasMany(Product::class, 'category_id');
    }

    /**
     * Get the products for the category (legacy - using category code).
     */
    public function productsByCode()
    {
        return $this->hasMany(Product::class, 'category', 'code');
    }

    /**
     * Check if this is a main category (has no parent).
     */
    public function isMainCategory(): bool
    {
        return $this->parent_id === null;
    }

    /**
     * Check if this is a subcategory (has a parent).
     */
    public function isSubcategory(): bool
    {
        return $this->parent_id !== null;
    }
}
