<?php

namespace App\Repositories\Shop;

use App\Models\Shop\PriceList;

class PriceLists
{
    public static function getByOfferAndSaleChannel($offer_id, $sale_channel_id)
    {
        return PriceList::bySaleChannel($sale_channel_id)->byOffer($offer_id)->get();
    }

    public static function getByOffer($offer_id)
    {
        return PriceList::byOffer($offer_id)->get();
    }

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

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

    public static function getByTariff($id)
    {
        return PriceList::byTariff($id)->get();
    }

    public static function getOptions()
    {
        return PriceList::pluck('name', 'id')->toArray();
    }

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

    public static function edit($id)
    {
        $price_list = self::getFull($id)->toArray();
        $n = count($price_list['price_list_values']);
        if ($n <= 3) {
            $price_list['price_list_values'] += array_fill($n, 3 - $n, '');
        }

        return $price_list;
    }

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

    public static function getPrices($id)
    {
        return PriceList::with('price_list_values')->find($id);
    }

    public static function getFull($id)
    {
        return PriceList::with(['price_list_values'])->find($id);
    }

    public static function store($data)
    {
        $id = $data['id'] ?? false;
        $price_list_values = $data['price_list_values'] ?? false;
        unset($data['price_list_values']);
        $price_list = $id ? self::update($data) : self::create($data);
        PriceListValues::storePrices($price_list->id, $price_list_values);

        return $price_list;
    }

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