<?php

namespace App\Repositories\Shop;

use App\Models\Shop\Tag;
use App\Models\Shop\TagGroup;
use Illuminate\Support\Str;

class TagGroups
{
    public static function getOptions()
    {
        return TagGroup::get()->SortBy('name')->pluck('name', 'id')->toArray();
    }

    public static function getWithTagsAndCountOffers($category_id = false)
    {
        $data = [];
        $tags = Tag::withCountArticlesByCategory($category_id)->get()->toArray();
        $tagGroups = TagGroup::pluck('name', 'id')->toArray();
        foreach ($tags as $tag) {
            if (! $tag['articles_count']) {
                continue;
            }
            $data[$tag['tag_group_id']]['name'] = $tagGroups[$tag['tag_group_id']];
            $data[$tag['tag_group_id']]['tags'][] = [
                'id' => $tag['id'],
                'name' => $tag['name'],
                'count' => $tag['articles_count'],
            ];
        }

        return $data;
    }

    public static function isTagGroupHaveSelected($tagsSelected, $tags)
    {
        foreach ($tags as $tag) {
            if (in_array($tag['id'], $tagsSelected)) {
                return false;
            }
        }

        return true;
    }

    public static function getTreeTags()
    {
        $items = TagGroup::with('tags')->get();
        $tags = [];
        foreach ($items as $group) {
            $group_tags = [];
            foreach ($group->tags as $tag) {
                $group_tags[$tag->id] = $group->name.' - '.$tag->name;
            }
            $tags[] = [
                'label' => $group->name,
                'options' => $group_tags,
            ];
        }

        return $tags;
    }

    public static function getAll()
    {
        return TagGroup::orderBy('name', 'asc')->get();
    }

    public static function getSlug($id)
    {
        return self::get($id)->slug ?? '';
    }

    public static function getName($id)
    {
        return self::get($id)->name ?? '';
    }

    public static function get($id)
    {
        return TagGroup::find($id);
    }

    public static function store($data)
    {
        $item = ($data['id'] ?? false) ? self::update($data) : self::create($data);

        return $item->id;
    }

    public static function create($data)
    {
        $data['slug'] = Str::slug($data['name']);

        return TagGroup::create($data);
    }

    public static function update($data, $id = false)
    {
        $id = $id ? $id : $data['id'];
        $model = self::get($id);
        if ($data['name'] ?? false) {
            $data['slug'] = Str::slug($data['name']);
        }
        $model->update($data);
        Tags::updateGroup($id, $data['name']);

        return $model;
    }

    public static function destroy($id)
    {
        return TagGroup::destroy($id);
    }

    public static function toggleVisible($id, $visible)
    {
        return self::update(['visible' => $visible], $id);
    }
}
