<?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 mLieferantGUI extends mLieferant implements iGUIHTMLMP2, iAutoCompleteHTML, icontextMenu, iCategoryFilter {
	public $searchFields = array("LieferantFirma","LieferantOrt","LieferantStrasse");
	
	public function getHTML($id, $page){
		T::load(__DIR__, "mLieferant");
		
		$this->addJoinV3("Kategorie", "LieferantKategorieID", "=", "KategorieID");
		$this->addOrderV3("t1.LieferantKategorieID");
		
		if(Applications::activeApplication() == "openFiBu"){
			$this->addOrderV3("LieferantKonto");
		} else
			$this->addOrderV3("LieferantFirma");
		$this->filterCategories();
		$this->loadMultiPageMode($id, $page, 0);

		$gui = new HTMLGUIX($this);
		$gui->version("mLieferant");
		$gui->screenHeight();
		
		$gui->name("Lieferant");
		
		$gui->displayGroup("LieferantKategorieID", "mLieferantGUI::parserDG");
		
		$gui->attributes(array("LieferantFirma"));
		if(Applications::activeApplication() == "openFiBu"){
			$gui->attributes(array("LieferantKonto", "LieferantFirma"));
			$gui->colWidth("LieferantKonto", 80);
			$gui->colStyle("LieferantKonto", "text-align:right;");
		}
		
		$gui->options(true, true, true, true);
		
		$gui->parser("LieferantFirma", "parserFirma");
		
		#$B = $gui->addSideButton("Rabattgruppen\nbearbeiten", "./openWaWi/Lieferanten/Rabattgruppe.png");
		#$B->loadFrame("contentRight", "mRabattgruppe");
		
		return $gui->getBrowserHTML($id);
	}
	
	public static function parserDG($w){
		if($w == "0") return "-";
		
		$K = new Kategorie($w);
		return $K->A("name");
	}
	
	public function getACData($attributeName, $query, $options = null){
		#if($options !== null AND $options[0] == "{" AND mb_substr($options, -1) == "}")
		#	$options = json_decode($options);
		
		$this->setSearchStringV3($query);
		$this->setSearchFieldsV3($this->searchFields);
		
		$this->setFieldsV3(array("LieferantFirma AS label", "t1.LieferantID AS value", "'' AS description"));
		
		$this->setLimitV3("10");
		#$this->setParser("label", "AdressenGUI::parserACLabel");
		
		Aspect::joinPoint("query", $this, __METHOD__, $this);
		
		#$append = null;
		#if(isset($options->createNew)){
		#	$sex = explode("::", $options->createNew);
		#	$append = array("label" => "Neue Adresse erstellen", "script" => OnEvent::popup("Adresse erstellen", $sex[0], "-1", $sex[1]));
		#}
		
		echo $this->asJSON();
	}
	
	public function getACHTML($attributeName, $query){
		$gui = new HTMLGUI2();
		
		switch($attributeName){
			case "quickSearchmLieferant":
				$mode = "quickSearchLoadFrame";

				#unset($this->searchFields[array_search("kundennummer", $this->searchFields)]);
				#unset($this->searchFields[array_search("tel", $this->searchFields)]);
				$this->setSearchFieldsV3($this->searchFields);
				$this->setSearchStringV3($query);

				
				$this->setLimitV3(10);
				
				Aspect::joinPoint("query", $this, __METHOD__, array($attributeName, $query));
				
				$this->setFieldsV3(array("LieferantID", "LieferantFirma", "'' AS nachname", "'' AS vorname", "LieferantOrt", "LieferantPLZ", "LieferantStrasse"));
				$this->lCV3();

				
				$gui->setObject($this);
				#$gui->setAttributes($this->collector);
				$gui->setShowAttributes(array("LieferantFirma"));
				
				$gui->setParser("LieferantFirma","mLieferantGUI::parserACFirma",array("\$sc->vorname","\$sc->nachname","\$sc->LieferantPLZ","\$sc->LieferantOrt","\$sc->LieferantStrasse"));
				#$gui->setParser("firma","AdressenGUI::ACFirmaParser",array("\$sc->nachname","\$sc->vorname","\$sc->plz","\$sc->ort","\$sc->strasse"));
				
				$_SESSION["BPS"]->registerClass(get_class($gui));
				$_SESSION["BPS"]->setACProperty("targetFrame","contentLeft");
				$_SESSION["BPS"]->setACProperty("targetPlugin","Lieferant");
				$gui->autoCheckSelectionMode(get_class($this));
				$gui->customize($this->customizer);
				echo $gui->getACHTMLBrowser($mode, true, Session::isPluginLoaded("mAnsprechpartner") ? "Adressen" : null);
				
					
				if(Session::isPluginLoaded("mAnsprechpartner")){
					$AC = anyC::get("Ansprechpartner");
					$AC->addAssocV3("CONCAT(AnsprechpartnerVorname, ' ', AnsprechpartnerNachname)", "LIKE", "%$query%");
					$AC->addAssocV3("AnsprechpartnerOwnerClass", "=", "Lieferant");
					$AC->addAssocV3("t2.LieferantID", "IS NOT", "NULL");
					#$AC->setFieldsV3(array("AnsprechpartnerOwnerClassID"));
					$AC->setLimitV3(10);
					$AC->addJoinV3("Lieferant", "AnsprechpartnerOwnerClassID", "=", "LieferantID");
					#$AC->addJoinV3("Kappendix", "AnsprechpartnerOwnerClassID", "=", "AdresseID");
					$AC->setFieldsV3(array("t2.LieferantID","LieferantFirma", "AnsprechpartnerNachname AS nachname", "AnsprechpartnerVorname AS vorname", "LieferantOrt", "LieferantPLZ", "LieferantStrasse"));
					#$AC->addGroupV3("t2.LieferantID");
					$AC->lCV3();
					#while($AP = $AC->n())
					#	$this->addAssocV3 ("AdresseID", "=", $AP->A("AnsprechpartnerOwnerClassID"), "OR");
					
					$gui->setObject($AC);
					if($AC->numLoaded() > 0)
						echo $gui->getACHTMLBrowser($mode, false, "Ansprechpartner", "LieferantID");
				}
				
			break;

		}
	}
	
	public static function parserACFirma($w,$l,$p){
		$s = HTMLGUI::getArrayFromParametersString($p);
		return ($w != "" ? $w.(trim($s[0].$s[1]) != "" ? "<br /><small>$s[1] $s[0]</small>" : "") : "$s[1] $s[0]")."<br><small style=\"color:grey;\">$s[2] $s[3]".($s[4] != "" ? ", $s[4]" : "")."</small>";
	}
	
	public static function parserFirma($w, $E){
		return $w."<br /><small style=\"color:grey;\">".$E->A("LieferantBemerkung")."</small>";
	}

	public function getLieferantenPopup($ArtikelID){
		T::load(__DIR__, "mLieferant");
		
		$AC = anyC::get("LieferantPreis");
		$AC->addAssocV3("LieferantPreisArtikelID", "=", $ArtikelID);
		$AC->addAssocV3("LieferantPreisVarianteArtikelID", "=", 0);
		$AC->addJoinV3("Lieferant", "LieferantPreisLieferantID", "=", "LieferantID");

		$hideEK = mUserdata::getPluginSpecificData("Provisionen", "pluginSpecificHideEK");
		
		#$Artikel = new Artikel($ArtikelID);
		
		$B = new Button("Lieferant\nhinzufügen", "./openWaWi/Lieferanten/Lieferant.png");
		$B->style("margin:10px;");
		$B->customSelect("contentRight", $ArtikelID, "mLieferant", "Lieferant.addLieferant");
		
		echo $B."<div id=\"lieferantenFrame\" style=\"max-height:450px;overflow:auto;\">";
		
		while($P = $AC->getNextEntry()){
			$BD = new Button("", "./images/i2/delete.gif", "icon");
			$BD->onclick("deleteClass('LieferantPreis','".$P->getID()."', function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant');  contentManager.reloadFrame('contentLeft'); },'Eintrag wirklich löschen?');");
			$BD->style("float:right;");
			
			$T = new HTMLTable(1, $BD.$P->A("LieferantFirma")."&nbsp;");
			$T->setTableStyle("width:100%;");
			$C = $this->rows($P, $hideEK);
			
			if(Session::isPluginLoaded("mVariante") AND Variante::has($ArtikelID)){
				$AC2 = Variante::get($ArtikelID);
				while($V = $AC2->n()){
					$AC3 = anyC::get("LieferantPreis", "LieferantPreisVarianteArtikelID", $V->getID());
					$AC3->addAssocV3("LieferantPreisLieferantID", "=", $P->A("LieferantPreisLieferantID"));
					$P2 = $AC3->n();
					
					if($P2 != null)
						$C .= $this->rows($P2, $hideEK, $V);
				}
				

			}
			
			$V = "";
			if(Session::isPluginLoaded("mVariante") AND Variante::has($ArtikelID)){
				$B = new Button("Variante hinzufügen", "./images/i2/add.png", "icon");
				$B->style("vertical-align:bottom;");
				
				$V = "<div><a href=\"#\" onclick=\"".OnEvent::context("mLieferant", "variants:$ArtikelID:".$P->A("LieferantPreisLieferantID"), "Varianten")."return false;\">$B Variante hinzufügen</a></div>";
			}
			
			$T->addRow($C.$V);
			$T->addRowClass("backgroundColor4");
			
			$T->addRow(array("&nbsp;"));
			$T->addRowClass("backgroundColor0");
			
			echo $T;
		}
		echo "</div>".OnEvent::script("\$j('#lieferantenFrame').scrollTop(Lieferant.lastScroll); ");

	}
	
	private function rows($P, $hideEK, $Variante = null){
		
		$T = new HTMLTable(2);
		$T->setColWidth(1, 120);
		
		$class = "LP_".$P->A("LieferantPreisArtikelID")."_".$P->A("LieferantPreisVarianteArtikelID");
		$I = new HTMLInput("LieferantPreisHaupt", "checkbox", $P->A("LieferantPreisHaupt"));
		$I->title("Hauptlieferant?");
		$I->setClass($class);
		$I->id("LP_".$P->getID());
		$I->onchange("\$j('.$class:not(#LP_".$P->getID().")').prop('checked', false); ".OnEvent::rme($P, "unsetHaupt", array(), OnEvent::rme($P, "saveMultiEditField", array("'LieferantPreisHaupt'", "\$j('#LP_".$P->getID()."').prop('checked') ? 1 : 0"))));
		#$I->activateMultiEdit("LieferantPreis", $P->getID());
		$I->style("float:right;vertical-align:top;margin-right:10px;margin-top:0;");
		if($P->A("LieferantPreisVarianteArtikelID") > 0)
			$I = "";
		
		if($Variante == null){
			$BD = new Button("", "./images/i2/empty.png", "icon");
			$BD->style("float:right;");
			
			$T->addRow(array($BD.$I.T::_("Hauptartikel"), ""));
		} else {
			$BD = new Button("", "./images/i2/delete.gif", "icon");
			$BD->onclick("deleteClass('LieferantPreis','".$P->getID()."', function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant');  contentManager.reloadFrame('contentLeft'); },'Eintrag wirklich löschen?');");
			$BD->style("float:right;");
			
			$T->addRow(array($BD.$I.$Variante->A("VarianteArtikelName")));
		}
		
		$T->addRowColspan(1, 2);
		$T->addRowClass("backgroundColor4");
		
		$ILP = new HTMLInput("LieferantPreisListenPreis", "text", Aspect::joinPoint("price", $this, __METHOD__, array($P->A("LieferantPreisListenPreis")), Util::CLFormatCurrency($P->A("LieferantPreisListenPreis") * 1)));
		$ILP->activateMultiEdit("LieferantPreis", $P->getID(), "function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant'); contentManager.reloadFrame('contentLeft'); contentManager.reloadFrame('contentRight'); }");
		$ILP->hasFocusEvent(true);
		$ILP->style("width:70px;text-align:right;margin-right:15px;");

		$IRG = new HTMLInput("LieferantPreisRabattgruppe", "text", $P->A("LieferantPreisRabattgruppe"));
		$IRG->activateMultiEdit("LieferantPreis", $P->getID(), "function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop();  Popup.refresh('mLieferant'); contentManager.reloadFrame('contentLeft'); contentManager.reloadFrame('contentRight'); }");
		$IRG->autocomplete("mRabattgruppe", "function(selection){ }", false, $P->A("LieferantPreisLieferantID"));
		$IRG->hasFocusEvent(true);
		$IRG->style("width:90px;text-align:right;");

		$ILAN = new HTMLInput("LieferantPreisArtikelnummer", "text", $P->A("LieferantPreisArtikelnummer"));
		$ILAN->activateMultiEdit("LieferantPreis", $P->getID(), "");
		$ILAN->hasFocusEvent(true);

		$ILN = new HTMLInput("LieferantPreisArtikelname", "text", $P->A("LieferantPreisArtikelname"));
		$ILN->activateMultiEdit("LieferantPreis", $P->getID(), "");
		$ILN->hasFocusEvent(true);

		if(!$hideEK){
			$BE = new Button("Erweiterte Preise anzeigen", "./images/i2/add.png", "icon");
			$BE->style("float:right;");
			$BE->onclick("\$j('.extendedPrice".$P->getID()."').toggle();");
			
			$T->addRow($BE.T::_("LP").": ".$ILP." <div style=\"display:inline-block;width:140px;margin-right:15px;\">".T::_("RG").": $IRG</div> ".T::_("EK").": ".Util::CLFormatCurrency($P->getEK()));
			$T->addRowColspan(1, 2);
			
			$ILS1 = new HTMLInput("LieferantPreisSonstiges1", "text", Aspect::joinPoint("sonstiges1", $this, __METHOD__, array($P->A("LieferantPreisSonstiges1")), Util::CLFormatCurrency($P->A("LieferantPreisSonstiges1") * 1)));
			$ILS1->activateMultiEdit("LieferantPreis", $P->getID(), "function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant'); contentManager.reloadFrame('contentLeft'); contentManager.reloadFrame('contentRight'); }");
			$ILS1->hasFocusEvent(true);
			
			$ILF = new HTMLInput("LieferantPreisFracht", "text", Aspect::joinPoint("fracht", $this, __METHOD__, array($P->A("LieferantPreisFracht")), Util::CLFormatCurrency($P->A("LieferantPreisFracht") * 1)));
			$ILF->activateMultiEdit("LieferantPreis", $P->getID(), "function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant'); contentManager.reloadFrame('contentLeft'); contentManager.reloadFrame('contentRight'); }");
			$ILF->hasFocusEvent(true);
			$ILF->style("width:calc(100% - 28px - 45px);");
			
			$ILFM = new HTMLInput("LieferantPreisFrachtMode", "select", Aspect::joinPoint("frachtMode", $this, __METHOD__, array($P->A("LieferantPreisFrachtMode")), $P->A("LieferantPreisFrachtMode")), array(0 => "€", 1 => "%"));
			$ILFM->activateMultiEdit("LieferantPreis", $P->getID(), "function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant'); contentManager.reloadFrame('contentLeft'); contentManager.reloadFrame('contentRight'); }");
			$ILFM->hasFocusEvent(true);
			$ILFM->style("margin-left:10px;width:35px;");
			
			$ILV = new HTMLInput("LieferantPreisVerpackung", "text", Aspect::joinPoint("verpackung", $this, __METHOD__, array($P->A("LieferantPreisVerpackung")), Util::CLFormatCurrency($P->A("LieferantPreisVerpackung") * 1)));
			$ILV->activateMultiEdit("LieferantPreis", $P->getID(), "function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant'); contentManager.reloadFrame('contentLeft'); contentManager.reloadFrame('contentRight'); }");
			$ILV->hasFocusEvent(true);
			
			$ILS = new HTMLInput("LieferantPreisSonstiges", "text", Aspect::joinPoint("sonstiges", $this, __METHOD__, array($P->A("LieferantPreisSonstiges")), Util::CLFormatCurrency($P->A("LieferantPreisSonstiges") * 1)));
			$ILS->activateMultiEdit("LieferantPreis", $P->getID(), "function() { Lieferant.lastScroll = \$j('#lieferantenFrame').scrollTop(); Popup.refresh('mLieferant'); contentManager.reloadFrame('contentLeft'); contentManager.reloadFrame('contentRight'); }");
			$ILS->hasFocusEvent(true);
		
			
			$hideExtended = ($P->A("LieferantPreisSonstiges1") + $P->A("LieferantPreisFracht") + $P->A("LieferantPreisVerpackung") + $P->A("LieferantPreisSonstiges") == 0);
			
			
			$T->addLV(T::_(Aspect::joinPoint("labelSonstiges1", $this, __METHOD__, array(), "Preis Sonstiges")).":", $ILS1);
			if($hideExtended)
				$T->addRowStyle ("display:none;");
			$T->addRowClass("extendedPrice".$P->getID());
			
			$T->addLV(T::_(Aspect::joinPoint("labelFracht", $this, __METHOD__, array(), "Preis Fracht")).":", $ILF.$ILFM);
			if($hideExtended)
				$T->addRowStyle ("display:none;");
			$T->addRowClass("extendedPrice".$P->getID());
			
			$T->addLV(T::_(Aspect::joinPoint("labelVerpackung", $this, __METHOD__, array(), "Preis Verpackung")).":", $ILV);
			if($hideExtended)
				$T->addRowStyle ("display:none;");
			$T->addRowClass("extendedPrice".$P->getID());
			
			$T->addLV(T::_(Aspect::joinPoint("labelSonstiges", $this, __METHOD__, array(), "Preis Sonstiges")).":", $ILS);
			if($hideExtended)
				$T->addRowStyle ("display:none;");
			$T->addRowClass("extendedPrice".$P->getID());
		}

		if($P->A("LieferantPreisLagerbestand") > 0)
			$T->addLV(T::_("Lagerbestand").":", Util::CLNumberParserZ($P->A("LieferantPreisLagerbestand")));
		
		$T->addLV(T::_("Artikelnummer").":", $ILAN);
		$T->addLV(T::_("Artikelname").":", $ILN);
		
		Aspect::joinPoint("alter", $this, __METHOD__, array($T, $P));
		
		return "<div style=\"width:50%;vertical-align:top;display:inline-block;margin-bottom:15px;\">".$T."</div>";
	}
	
	public function addVariantLieferant($ArtikelID, $LieferantID, $ArtikelVarianteID){
		$F = new Factory("LieferantPreis");
		
		$F->sA("LieferantPreisArtikelID", $ArtikelID);
		$F->sA("LieferantPreisLieferantID", $LieferantID);
		$F->sA("LieferantPreisVarianteArtikelID", $ArtikelVarianteID);
		
		if($F->exists())
			Red::alertD("Dieser Lieferant wurde bereits angelegt");
		
		$F->store(true, true);
	}
	
	public function addLieferant($ArtikelID, $LieferantID){
		$F = new Factory("LieferantPreis");
		
		$F->sA("LieferantPreisArtikelID", $ArtikelID);
		$F->sA("LieferantPreisLieferantID", $LieferantID);
		
		if($F->exists())
			Red::alertD("Dieser Lieferant wurde bereits angelegt");
		
		$F->store(true, true);
	}

	public function getContextMenuHTML($identifier){
		if($identifier == "searchHelp")
			echo "<p style=\"padding:5px;\">Es werden folgende Felder durchsucht:<br><br>Firma<br>Straße<br>Ort</p><p>Sie können Ihre Suchanfrage mit UND verknüpfen.<br />Also z.B. \"Firmenname UND Ort\"</p>";
		#echo $identifier;
		if(strpos($identifier, "variants") === 0){
			$ex = explode(":", $identifier);
			$ArtikelID = $ex[1];
			
			$T = new HTMLTable(1);
			$T->useForSelection(false);
			$AC = Variante::get($ArtikelID);
			while($V = $AC->n()){
				$T->addRow(array($V->A("VarianteArtikelName")));
				$T->addRowEvent("click", OnEvent::rme($this, "addVariantLieferant", array($ArtikelID, $ex[2], $V->getID()), OnEvent::closeContext().OnEvent::reloadPopup("mLieferant")));
			}
			
			echo $T;
		}

	}

	public static function getCategories(){
		return array("Lieferanten" => "lieferant");
	}

	public function getAvailableCategories() {
		$kat = new Kategorien();
		$kat->addAssocV3("type","=","lieferant");
		$kat->addOrderV3("name");
		
		return $kat->getArrayWithKeysAndValues();
	}

	public function getCategoryFieldName() {
		return "t1.LieferantKategorieID";
	}

	/*public function lieferantSelectionPopup($ArtikelID, $GRLBMID){
		$AC = Lieferant::getLieferanten($ArtikelID);
		
		#$Artikel = new Artikel($ArtikelID);
		
		$T = new HTMLTable(2);
		$T->maxHeight(400);
		$T->useForSelection(false);
		$T->setColWidth(1, 20);
		
		while($L = $AC->getNextEntry()){
			$BS = new Button("Lieferant auswählen", "./images/i2/cart.png", "icon");
			
			$T->addRow(array($BS, $L->A("LieferantFirma")));
			$T->addRowEvent("click", OnEvent::rme($L, "addToBeleg", array("'$ArtikelID'", "'$GRLBMID'"), "function(){ contentManager.loadFrame('subframe', 'GRLBM', $GRLBMID); ".OnEvent::closePopup("mLieferant")." }"));
		}
		
		echo "<p class=\"prettyTitle\">Lieferanten</p>".$T;
	}*/

}
?>