<?php

namespace App\Repositories\Shop;

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

class Merchandises
{
    use Imageable;

    public static function autocomplete($str)
    {
        $data = Merchandise::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 getPrices($id)
    {
        return Merchandise::with(['price_lists.price_list_values', 'price_lists.sale_channel'])->find($id);
    }

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

    public static function getStatus($status_id)
    {
        return self::getStatuses()[$status_id];
    }

    public static function getStatuses()
    {
        return ['Actif','Suspendu','Invisible','Obsolete'];
    }

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

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

    public static function getFull($id)
    {
        $data = self::get($id)->toArray();
        return $data;
    }

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

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

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

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

    public static function create($data)
    {
        return Merchandise::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 Merchandise::destroy($id);
    }
}
