<?php
namespace App\Models;

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

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 
        'name_ar',
        'status',
        'parent_id',
        'icon',
        'sort_order',
    ];

    public function getIconAttribute($icon){

        return get_uploaded_image_url( $icon, 'category_image_upload_dir', 'camera_placeholder.png' );
        
    }

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

    function getParentCategoryNameAttribute()
    {
        $category = $this;
        $names = [];

        while ($category->parent_id !== null) {
            $names[] = $category->parent->name;
            $category = $category->parent;
        }

        return implode(' > ', array_reverse($names));
    }

    function getNameWithParentCategoryNameAttribute()
    {
        $category = $this;
        $names[] = $category->name;

        while ($category->parent_id !== null) {
            $names[] = $category->parent->name;
            $category = $category->parent;
        }

        return implode(' > ', array_reverse($names));
    }

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

    function ads()
    {
        return $this->hasMany(Ad::class, 'category_id', 'id');
    }
    
}
