<?php
namespace Modules\Seo\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Category extends Model {
    protected $table = "category";
    protected $guarded = ['id'];

    const TYPE_PRODUCT = 'PRODUCT';
    const TYPE_POST = 'POST';

    protected $fillable = [
        'name', 'type', 'is_hidden', 'image_url', 'big_image_url', 'description', 'slug', 'sorder', 'parent_id', 'is_display_home_page'
    ];

    protected $appends = [

    ];

    public function getDescendantsAttribute()
    {
        $descendants = $this->where('_lft', '>', $this->_lft)
            ->where('_rgt', '<', $this->_rgt)
            ->get();

        foreach ($descendants as $descendant) {
            $descendant->append('depth');
        }
        
        return $descendants;
    }

    public function getDepthAttribute()
    {    
        $depth = $this->where('_lft', '<', $this->_lft)
        ->where('_rgt', '>', $this->_rgt)->count();
        return $depth + 1;
    }

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


    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('sort', function (Builder $builder) {
            $builder->orderBy('category.sorder', 'desc')
                    ->orderBy('category.id', 'asc');
        });

    }
}
