<?php

namespace App\Repositories\Shop;

use App\Repositories\Core\Tag;

class ArticleTags
{
    public static function getTagsByArticle($article)
    {
        return $article->tags->pluck('id')->toArray();
    }

    public static function getTagsNameByArticle($article)
    {
        return $article->tags->pluck('name', 'id')->toArray();
    }

    public static function getTagsSlugByArticle($article)
    {
        return $article->tags->pluck('slug', 'id')->toArray();
    }

    public static function getFullTagsSlugByArticle($article)
    {
        $data = [];

        switch ($article->product_type) {
            case 'App\Models\Botanic\Variety':
                $variety = $article->product;
                if ($variety && $variety->tags) {
                    $data = array_merge($data, $variety->tags->toArray());
                }
                if ($variety && $variety->specie && $variety->specie->tags) {
                    $data = array_merge($data, $variety->specie->tags->toArray());
                }
                break;
            case 'App\Models\Botanic\Specie':
                $specie = $article->product;
                if ($specie && $specie->tags) {
                    $data = array_merge($data, $specie->tags->toArray());
                }
                break;
            case 'App\Models\Shop\Merchandise':
                $merchandise = $article->product;
                if ($merchandise && $merchandise->tags) {
                    $data = array_merge($data, $merchandise->tags->toArray());
                }
                if ($merchandise && $merchandise->producer && $merchandise->producer->tags) {
                    $data = array_merge($data, $merchandise->producer->tags->toArray());
                }
                break;
            default:
        }
        if ($article->tags) {
            $data = array_merge($data, $article->tags->toArray());
        }

        foreach ($data as $tag) {
            if (! isset($tags[$tag['group']][$tag['name']])) {
                $tags[$tag['group']][] = $tag['name'];
            }
        }

        return $tags ?? null;
    }

    public static function storeTags($article, $tags)
    {
        return Tag::storeTags($article, $tags);
    }
}
