<?php

namespace App\Repositories\Botanic;

use App\Models\Botanic\Variety;
use App\Repositories\Core\Tag;
use App\Repositories\Shop\TagGroups;
use App\Traits\Model\Basic;
use App\Traits\Repository\Imageable;

class Varieties
{
    use Basic, Imageable;

    public static function init()
    {
        return [
            'species' => Species::getOptions(),
            'tags_list' => TagGroups::getTreeTags(),
        ];
    }
    
    public static function getOptionsWithSpecie()
    {
        $varieties = Variety::with('specie')->get();
        $data = [];
        foreach ($varieties as $variety) {
            $data[$variety->id] = (isset($variety->specie->name) ? $variety->specie->name.' ' : '').$variety->name;
        }
        asort($data, SORT_NATURAL | SORT_FLAG_CASE);

        return $data;
    }

    public static function getDescription($id)
    {
        return self::get($id)->description;
    }

    public static function getTags($id)
    {
        return self::get($id)->tags;
    }

    public static function get($id)
    {
        return Variety::with('tags.tag_group')->findOrFail($id);
    }

    public static function getFull($id)
    {
        $variety = self::get($id);
        $data = $variety->toArray();
        $data['tags'] = self::getTagsByVariety($variety);

        return $data;
    }

    public static function getTagsByVariety($variety)
    {
        return Tag::getTagsByModel($variety);
    }

    public static function storeFull($data)
    {
        $images = $data['images'] ?? false;
        $tags = $data['tags'] ?? false;
        if (! array_key_exists('plus', $data) || $data['plus'] === null) {
            $data['plus'] = '';
        }
        unset($data['images']);
        unset($data['tags']);
        $variety = self::store($data);
        self::storeImages($variety, $images);
        self::storeTags($variety, $tags);

        return $variety;
    }

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

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