<?php

namespace App\Repositories\Shop;

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

class Merchandises
{
    use Basic, Imageable;

    public static function init()
    {
        return [
            'producers_list' => Producers::getOptions(),
            'tags_list' => TagGroups::getTreeTags(),
        ];
    }

    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 getFull($id)
    {
        $merchandise = self::get($id);
        $data = $merchandise->toArray();
        $data['tags'] = self::getTagsByMerchandise($merchandise);

        return $data;
    }

    public static function getTagsByMerchandise($merchandise)
    {
        return Tag::getTagsByModel($merchandise);
    }

    public static function getPrices($id)
    {
        return Merchandise::with(['price_lists.price_list_values', 'price_lists.sale_channel'])->find($id);
    }

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

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

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

    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 getModel()
    {
        return Merchandise::query();
    }
}
