<?php

namespace App\Repositories\Shop;

use App\Repositories\Core\Tag;
use App\Models\Shop\Producer;
use App\Traits\Repository\Imageable;

class Producers
{
    use Imageable;

    public static function autocomplete($str)
    {
        $data = Producer::byAutocomplete($str)->orderBy('name')->limit(30)->get()->pluck('name', 'id');
        $export = [];
        foreach ($data as $key => $name) {
            $export[] = ['value' => $key, 'text' => $name];
        }
        return $export;
    }

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

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

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

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

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

    public static function getFull($id)
    {
        $producer = self::get($id);
        $data = $producer->toArray();
        $data['tags'] = self::getTagsByProducer($producer);
        return $data;
    }

    public static function getTagsByProducer($producer)
    {
        return Tag::getTagsByModel($producer);
    }

    public static function storeFull($data)
    {
        $images = $data['images'] ?? false;
        $tags = $data['tags'] ?? false;
        unset($data['images']);
        unset($data['tags']);
        $producer = self::store($data);
        self::storeImages($producer, $images);
        self::storeTags($producer, $tags);
        return $producer;
    }

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

    public static function create($data)
    {
        return Producer::create($data);
    }

    public static function update($data, $id = false)
    {
        $id = $id ? $id : $data['id'];
        $item = self::get($id);
        $item->update($data);
        return $item;
    }

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