<?php

namespace Hilco\Models;
use Illuminate\Support\Collection;

/**
 * Hilco\Models\PriceList
 *
 * @property mixed $id
 * @property string $price_list
 * @property string $part_no
 * @property mixed $part_id
 * @property boolean $contract_flag
 * @property float $price
 * @property integer $quantity_level
 * @property string $currency
 * @property string $date_created
 * @property string $date_modified
 * @property string $deleted_at
 * @property-read mixed $id_string
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList wherePriceList($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList wherePartNo($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList wherePartId($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereContractFlag($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList wherePrice($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereQuantityLevel($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereCurrency($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereDateCreated($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereDateModified($value)
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereDeletedAt($value)
 * @mixin \Eloquent
 * @property string $date_uploaded
 * @method static \Illuminate\Database\Query\Builder|\Hilco\Models\PriceList whereDateUploaded($value)
 */
class PriceList extends WebModel {
	protected $table = 'PriceLists';

	public function scopeFor($query, $list, $currency, $partNumber, $quantity) {
		return $query
			->wherePriceList($list)
			->whereCurrency($currency)
			->wherePartNo($partNumber)
			->whereQuantityLevel('>=', $quantity)
		;
	}

	public static function distinctLists() {
	    return self::distinct()
            ->orderBy('price_list')
            ->orderBy('currency')
            ->select(['price_list', 'currency'])
            ->withTrashed()
            ->get();
    }

    /**
     * Finds the price in a Collection of PriceList models for a given part and quantity.
     *
     * @param Collection $priceLists
     * @param $webPartId
     * @param $quantity
     * @return mixed
     */
    public static function filterForPartQuantity(Collection $priceLists, $webPartId, $quantity) {
        return $priceLists
            ->filter(function ($item, $key) use ($webPartId, $quantity) {
                return $item['part_id'] == $webPartId && $item['quantity_level'] <= $quantity;
            })
            ->sortByDesc('quantity_level')
            ->first()
        ;
    }
}
