<?php

namespace App\Traits;

use Illuminate\Support\Arr;
use App\Models\Tag;

trait TagsTrait
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable')->withPivot('exclude');
    }

    public function addTag($tag, $exclude = false)
    {
        if (!$tag instanceof Tag) {
            $tag = (new Tag())->findOrCreateTag($tag);
        }

        if (!$this->tags()->get()->contains('id', $tag->id)) {
            $this->tags()->attach($tag, [ 'exclude' => $exclude ]);
        }
    }

    public function addExcludeTag($tag)
    {
        $this->addTag($tag, true);
    }

    public function saveTags($input)
    {
        $this->tags()->detach();

        if (is_array(Arr::get($input, 'tags'))) {
            foreach (Arr::get($input, 'tags') as $tag_data) {
                $this->addTag($tag_data, Arr::get($tag_data, 'pivot.exclude') ? true : false);
            }
        }

        return $this;
    }
}
