<?php

namespace App\Repositories\Shop;

use App\Models\Shop\Offer;
use App\Models\Shop\PriceListValue;
use App\Traits\Model\Basic;

class PriceListValues
{
    use Basic;

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

    public static function getPriceByOffer($offer_id, $quantity = 1, $sale_channel_id = false)
    {
        $prices = self::getPricesByOffer($offer_id, $sale_channel_id);
        $price = $prices ? $prices->where('quantity', '<=', $quantity)->sortByDesc('quantity')->first() : false;

        return $price ? $price->price_taxed : false;
    }

    public static function getPricesByOffer($offer_id, $sale_channel_id = false)
    {
        $price_list = Offer::with([
            'price_lists' => function ($query) use ($sale_channel_id) {
                $sale_channel_id ? $query->bySaleChannel($sale_channel_id) : $query;
            },
        ])->find($offer_id)->price_lists->first();

        return $price_list ? $price_list->price_list_values : false;
    }

    public static function getByPriceList($id)
    {
        return PriceListValue::byPriceList($id)->get();
    }

    public static function storePrices($price_list_id, $values)
    {
        foreach ($values as $value) {
            $value['price_list_id'] = $price_list_id;
            if (self::hasPrice($value)) {
                self::store($value);
            }
        }
    }

    public static function purgeRemovedValues($price_list_id, array $ids)
    {
        if (! count($ids)) {
            return;
        }

        PriceListValue::byPriceList($price_list_id)
            ->whereIn('id', $ids)
            ->delete();
    }

    protected static function hasPrice($value): bool
    {
        if (! array_key_exists('price', $value)) {
            return false;
        }

        $price = $value['price'];

        return $price !== null && $price !== '';
    }

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