<?php
/**
 *  This file is part of openWaWi.

 *  openWaWi is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.

 *  openWaWi is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  2007 - 2020, open3A GmbH - Support@open3A.de
 */

class mLieferant extends anyC {
	function __construct() {
		parent::__construct();
		
		$this->customize();
	}
	
	public static $cache = array();
	
	public static function getCheapest($ArtikelID, $LieferantID = null, $VarianteArtikelID = 0){
		if(isset(self::$cache[$ArtikelID.($LieferantID != null ? $LieferantID : 0).$VarianteArtikelID]))
			return self::$cache[$ArtikelID.($LieferantID != null ? $LieferantID : 0).$VarianteArtikelID];
		
		$AC = anyC::get("LieferantPreis", "LieferantPreisArtikelID", $ArtikelID);
		if($LieferantID != null)
			$AC->addAssocV3 ("LieferantPreisLieferantID", "=", $LieferantID);
		$AC->addAssocV3 ("LieferantPreisVarianteArtikelID", "=", $VarianteArtikelID);

		$minPreis = null;
		$PO = null;
		while($P = $AC->getNextEntry()){
			$preis = $P->getEK();
			if($preis < $minPreis OR $minPreis == null){
				$minPreis = $preis;
				$PO = $P;
			}
		}
		
		if($VarianteArtikelID != 0 AND $AC->numLoaded() == 0) //use Artikelpreis if no Variante price
			return self::getCheapest($ArtikelID, $LieferantID, 0);
		
		
		self::$cache[$ArtikelID.($LieferantID != null ? $LieferantID : 0).$VarianteArtikelID] = $PO;
		
		return $PO;
	}
	
	public static function getCheapestEK($ArtikelID, $LieferantID = null, $VarianteArtikelID = 0){
		$PO = self::getCheapest($ArtikelID, $LieferantID, $VarianteArtikelID);
		
		if($PO === null)
			return null;
		
		return Util::kRound($PO->getEK(), Aspect::joinPoint("stellen", __CLASS__, __METHOD__, array(), 2));
	}
	
	public static function getCheapestLP($ArtikelID, $LieferantID = null, $VarianteArtikelID = 0){
		$PO = self::getCheapest($ArtikelID, $LieferantID, $VarianteArtikelID);
		
		if($PO == null)
			return 0;
		
		return $PO->getLP();
	}
}
?>
