<?php

namespace App\Repositories\Shop;

use Illuminate\Support\Str;

use App\Models\Shop\TagGroup;
use App\Models\Shop\Tag;

class TagGroups
{

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

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

    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)
    {
        $id = isset($data['id']) ? $data['id'] : false;
        $item = $id ? 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);
    }
}
