<?php

namespace App\Repositories\Shop;

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

class Tags
{
    public static function getTagHtml($tag)
    {
        return '<span class="btn btn-xs btn-secondary pb-2 mr-2 mb-2">'.self::getFullnameByTag($tag).'</span>';
    }

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

    public static function getWithCountOffers()
    {
        return Tag::withCount(['offers'])->get()->toArray();
    }

    public static function getWithCountArticles()
    {
        return Tag::withCount(['articles'])->get()->toArray();
    }

    public static function getOptionsFullName()
    {
        $data = [];
        $tags = Tag::with('tag_group')->get()->toArray();
        foreach ($tags as $tag) {
            $data[$tag['id']] = $tag['tag_group']['name'].'-'.$tag['name'];
        }

        return $data;
    }

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

    public static function getFullname($id)
    {
        $tag = Tag::with('tag_group')->find($id);

        return $tag ? self::getFullnameByTag($tag) : false;
    }

    public static function getFullnameByTag($tag)
    {
        return $tag->tag_group->name.'-'.$tag->name;
    }

    public static function get($id)
    {
        return Tag::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'] = self::buildSlug($data);
        $data['group'] = TagGroups::getName($data['tag_group_id']);
        $data['sort_order'] = self::getNewOrder($data['tag_group_id']);

        return Tag::create($data);
    }

    public static function update($data, $id = false)
    {
        $id = $id ? $id : $data['id'];
        $tag = self::get($id);
        $data['slug'] = self::buildSlug($data);
        $data['group'] = TagGroups::getName($data['tag_group_id']);
        $tag->update($data);

        return $tag;
    }

    public static function updateGroup($tag_group_id, $group)
    {
        return Tag::byGroup($tag_group_id)->update(['group' => $group]);
    }

    public static function buildSlug($data)
    {
        return Str::slug($data['name']);
    }

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

    public static function getNewOrder($tag_group_id)
    {
        $tag = Tag::byGroup($tag_group_id)->orderBy('sort_order', 'desc')->first();

        return $tag ? (int) $tag->sort_order + 1 : 1;
    }
}
