<?php

namespace App\Repositories\Shop;

use App\Models\Botanic\Variety;
use App\Models\Shop\Tag;
use App\Models\Shop\TagGroup;
use App\Traits\Model\Basic;
use Illuminate\Support\Str;

class TagGroups
{
    use Basic;

    public static function getWithTagsAndCountOffers($category_id = false)
    {
        $data = [];
        $tagsDirect = Tag::withCountDirectArticlesByCategory($category_id)->get()->toArray();
        $tagsIndirect = Tag::withCountIndirectArticlesByCategory($category_id)->get()->toArray();
        foreach ($tagsDirect as $tag) {
            $data[$tag['tag_group_id']]['name'] = $tag['group'];
            $data[$tag['tag_group_id']]['tags'][$tag['id']] = [
                'id' => $tag['id'],
                'name' => $tag['name'],
                'count' => $tag['direct_article_count'],
            ];
        }

        foreach ($tagsIndirect as $tag) {
            $data[$tag['tag_group_id']]['name'] = $tag['group'];
            $data[$tag['tag_group_id']]['tags'][$tag['id']] = [
                'id' => $tag['id'],
                'name' => $tag['name'],
                'count' => ($data[$tag['tag_group_id']]['tags'][$tag['id']]['count'] ?? 0) + $tag['indirect_article_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 getSlug($id)
    {
        return self::get($id)->slug ?? '';
    }

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

    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 toggleVisible($id, $visible)
    {
        return self::update(['visible' => $visible], $id);
    }

    public static function getModel()
    {
        return TagGroup::query();
    }
}
