<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    protected $fillable = [
        'title',
        'excerpt',
        'image',
        'slug',
        'parent_id',
        'featured',
        'order',
        'active'
    ];

    public function posts()
    {
        return $this->belongsToMany('App\Post')->withPivot('category_id');
    }

    public function products()
    {
        return $this->hasManyDeep(
            'App\Product',
            ['category_post', 'App\Post'],
            ['category_id', 'id', 'id' ],
            ['id', 'post_id', 'postable_id']
        )->withPivot('category_post', ['category_id'])->where('postable_type', 'App\\Product');
    }

    public function setTypeAttribute($value)
    {
        $this->attributes['type'] = json_encode($value);
    }

    public function getTypeAttribute($value)
    {
        return json_decode($value);
    }

    public function parent()
    {
        return $this->belongsTo(self::class);
    }

    public function setSlugAttribute($value)
    {
        $this->attributes['slug'] = $value ?? slug($this->attributes['title']);
    }

    public function getType()
    {
        if($this->type) {
            $types = [];
            foreach($this->type as $type) {
                if(in_array($type, array_keys(config('cms.types')))) {
                    $types[] = config('cms.types')[$type];
                }
            }

            $types = implode('<br>', $types);

            return $types;
        }
    }

    public function getTaxonomies($taxonomy)
    {
        $output = [];
        foreach($this->products()->pluck($taxonomy) as $object) {
            if($object) {
                foreach($object as $taxonomy) {
                    $output[] = $taxonomy;
                }
            }
        }

        return $output;
    }

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

    public function getParentName()
    {
        $parent = $this->parent;

        return $parent ? $parent->title : null;
    }

    public function tree() {
        $glue = ' - ';
        if($this->parent) {
            $tree[] = $this->parent->tree().$glue. $this->title;
        } else {
            $tree = $this->title;
        }
        return $tree;
    }
}
