<?php

namespace App\Repositories\Shop;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

use App\Models\Shop\PriceListValue;
use App\Models\Shop\PriceList;
use App\Models\Shop\Offer;

class PriceListValues
{

    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 getAll()
    {
        return PriceListValue::orderBy('name', 'asc')->get();
    }

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

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

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

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