<?php

namespace App\Repositories\Shop;

use App\Models\Shop\Variation;
use App\Traits\Model\Basic;
use Illuminate\Support\Str;

class Variations
{
    use Basic;

    public static function init()
    {
        return [
            'packages' => Packages::getOptions(),
            'unities' => Unities::getOptions(),
        ];
    }

    public static function autocomplete($str)
    {
        $data = Variation::where('name', 'LIKE', "%{$str}%")->orderBy('name')->limit(30)->pluck('name', 'id');
        $export = [];
        foreach ($data as $key => $name) {
            $export[] = ['value' => $key, 'text' => $name];
        }

        return $export;
    }

    public static function getOptions()
    {
        $data = [];
        $variations = Variation::with(['package', 'unity'])->get();
        foreach ($variations as $variation) {
            $data[$variation->id] = self::getName($variation);
        }
        natsort($data);

        return $data;
    }

    public static function getNameByID($id)
    {
        return self::getName(self::getFull($id));
    }

    public static function getName($variation)
    {
        return $variation->package->value.' '.
            $variation->quantity.' '.
            ($variation->unity->value ?? null).' '.
            Str::limit(strip_tags($variation->description), 15, ' (...)');
    }

    public static function buildName($data)
    {
        return Packages::getName($data['package_id']).' '.$data['quantity'].' '.Unities::getName($data['unity_id']);
    }

    public static function getFull($id)
    {
        return Variation::with(['package', 'unity'])->findOrFail($id);
    }

    public static function create($data)
    {
        $data['name'] = self::buildName($data);

        return Variation::create($data);
    }

    public static function update($data, $id = false)
    {
        $id = $id ? $id : $data['id'];
        $variation = self::get($id);
        $data['name'] = self::buildName($data);
        $variation->update($data);

        return $variation;
    }

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