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

 *  open3A 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.

 *  open3A 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 - 2022, open3A GmbH - Support@open3A.de
 */
class PostenGUI extends Posten implements iGUIHTML2 {
	
	function __construct($ID){
		parent::__construct($ID);
		
		$this->setParser("mwst","Util::CLNumberParserZ");
		$this->setParser("differenzbesteuertMwSt","Util::CLNumberParserZ");
		$this->setParser("rabatt","Util::CLNumberParserZ");
		$this->setParser("PostenLohnkosten","Util::CLNumberParserZ");
		$this->setParser("PostenLohnkostenMwSt","Util::CLNumberParserZ");
	}
	
	function getHTML($id){
		T::load(__DIR__, "Auftraege");
		#if($id != -1) $this->recalcNetto = false;

		$GRLBMID = BPS::getProperty("mPostenGUI","loadGRLBMID");
		$this->loadMeOrEmpty();

		if($this->A->isBrutto == "1")
			$this->A->preis = Util::CLNumberParserZ($this->A->bruttopreis,"load");
	
		$message = "";
		$gui = $this->getGUI();
		if($id == -1) {
			$G = new GRLBM($GRLBMID);
			$this->A = $this->newAttributes($G);
			$gui->autoComplete("artikelnummer", "mArtikel");
		} else {
			$G = new GRLBM($this->A("GRLBMID"));
			
			$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
			if(isset($pSpecData["pluginSpecificRLocksAuftrag"]) AND $G->getMyPrefix() != "R"){
				$AC = anyC::get("GRLBM", "AuftragID", $G->A("AuftragID"));
				$AC->addAssocV3("isR", "=", "1");
				$AC->setLimitV3(1);
				$R = $AC->n();
				if($R)
					$G->changeA("isPayed", "1");
			}
			
			if($G->isLocked() AND ($G->A("isR") == "1" OR $G->A("isA") == "1" OR $G->A("isL") == "1" OR isset($pSpecData["pluginSpecificRLocksAuftrag"]))){
				$message = "<p class=\"highlight\">Dieser Posten kann nicht mehr bearbeitet werden, der Beleg wurde gesperrt!</p>";
				$gui->optionsEdit(false, false);
			}
		}
		
		$gui->addToEvent("onSave", "Auftrag.checkBestand(transport); var scrolled = \$j('#PostenSortableContainer').scrollTop(); contentManager.loadFrame('subframe','GRLBM','".$GRLBMID."', '', '', function(){ \$j('#PostenSortableContainer').scrollTop(scrolled); });");
		
		return $message.$gui->getEditHTML();
	}
	
	public function getGUI(){
		$userLabels = mUserdata::getRelabels("Artikel");
		$userHiddenFields = mUserdata::getHides("Artikel");
		
		$gui = new HTMLGUIX($this);
		$gui->name("Posten");
		$gui->formID("1xPostenForm");
		$gui->displayMode("popupN");
		
		$gui->attributes(array(
			"name",
			"gebinde",
			"GRLBMID",
			"preis",
			"menge",
			"menge2",
			"mwst",
			"artikelnummer",
			#"rabatt",
			"EK1",
			"EK2",
			"beschreibung",
			"isBrutto",
			"createArtikel",
			"erloeskonto"));
		
		
		$G = new GRLBM($this->A("GRLBMID"));
		if($this->A("oldArtikelID") > 0 AND Session::isPluginLoaded("mStaffelpreis") AND Staffelpreis::useWith($G->getMyPrefix()) AND Staffelpreis::has("Artikel", $this->A("oldArtikelID"))){
			try {
				$c = new CustomizerRabatt();
				$gui->insertAttribute("after", "artikelnummer", "rabatt");
				$gui->label("rabatt", "Rabatt");
			} catch (Exception $ex) {

			}
			
			$gui->addFieldEvent("menge", "onKeyup", OnEvent::rme($this, "findStaffelpreis", array("\$j('#1xPostenForm [name=menge]').val()"), "function(t){ if(t.responseText == '') return; \$j('[name=preis]').val(t.responseData.preis).trigger('change'); \$j('[name=rabatt]').val(t.responseData.rabatt).trigger('change'); }"));
		}
		
		if(Session::isPluginLoaded("mFile")){# AND $this->A("bild")){
			$gui->insertAttribute("after", "preis", "bild");
			$gui->insertAttribute("after", "bild", "bildAction");
			$gui->parser("bild", "parserBild");
			$gui->label("bild", "Bild");
			$gui->type("bildAction", "hidden");
		}
		
		if(Session::isPluginLoaded("mLohngruppe")){
			$gui->insertAttribute("after", "EK2", "PostenLohnkosten");
			$gui->label("PostenLohnkosten", "Lohnkosten");
			$gui->descriptionField("PostenLohnkosten", "Im Nettopreis enthaltene Lohnkosten");
			$gui->parser("PostenLohnkosten", "parserLohnkosten");
		}
		
		if(Session::isPluginLoaded("mLagerbestandWare") AND LagerbestandWare::has($this->A("oldArtikelID"))){
			$gui->insertAttribute("after", "menge", "PostenUsedCharge");
			$gui->label("PostenUsedCharge", "Charge");
			if(Util::CLNumberParserZ($this->A("menge"), "store") != 0){
				$gui->type("PostenUsedCharge", "readonly");
				$L = new Lager($this->A("PostenLagerID"));
				$gui->descriptionField("PostenUsedCharge", "aus ".$L->A("LagerName"));
				#$gui->descriptionField("PostenUsedCharge", "Die Charge kann nur geändert werden, wenn die Menge Null ist.");
			} else
				$gui->parser("PostenUsedCharge", "parserCharge");
		}
		
		$gui->label("gebinde","Einheit");
		$gui->label("artikelnummer","Artikelnummer");
		$gui->label("mwst","MwSt");
		$gui->label("name","Name");
		$gui->label("menge","Menge");
		$gui->label("preis","Preis");
		$gui->label("beschreibung","Beschreibung");
		$gui->label("createArtikel", "Artikel?");
		$gui->label("erloeskonto", "Erlöskonto");
		
		$gui->type("beschreibung","textarea");
		$gui->type("GRLBMID","hidden");
		$gui->type("menge2","hidden");
		$gui->type("createArtikel", "checkbox");

		$B = new Button("Großes Textfeld", "./images/i2/fullscreen.png", "icon");
		$B->onclick("TextEditor.showTextarea(\$j('[name=beschreibung]'), '1xPostenForm');");
		$gui->addFieldButton("beschreibung", $B);
		
		/*$Stammdaten = mStammdaten::getActiveStammdaten();
		try {
			$CurrentVorlage = $Stammdaten->A("ownTemplate");
			$Vorlage = new $CurrentVorlage($Stammdaten);
		} catch (ClassNotFoundException $e){
			$Vorlage = new Vorlage_de_DE_leer($Stammdaten);
		}*/
		
		$G = new GRLBM($this->A("GRLBMID"));
		if($this->A("PostenUsedSerials") != "[]" AND $this->A("PostenUsedSerials") != ""){
			$gui->type("menge", "readonly");
			$gui->descriptionField("menge", Seriennummer::getPostenButton($this, OnEvent::closePopup("Posten"))."Die Menge kann nicht bearbeitet werden, da für diesen Posten Seriennummern eingetragen wurden.");
		}
		elseif(Session::isPluginLoaded("mSeriennummer") AND Seriennummer::has($this->A("oldArtikelID")) AND $G->getMyPrefix() == Lagerbestand::updateOn($this->A("oldArtikelID"))){
			$gui->type("menge", "readonly");
			$gui->descriptionField("menge", Seriennummer::getPostenButton($this, OnEvent::closePopup("Posten"))."Bitte verändern Sie die Menge über die Anzahl der Seriennummern.");
		}
			
		#if($this->A("PostenUsedCharge") != "" OR (Session::isPluginLoaded("mLagerbestandWare") AND LagerbestandWare::has($this->A("oldArtikelID")))){
		#	$gui->type("menge", "readonly");
		#	$gui->descriptionField("menge", "Die Menge kann nicht direkt bearbeitet werden, da der Artikel Chargen verwendet.");
		#}
		if(Session::isPluginLoaded("mLager") AND Lagerbestand::has("LArtikel", $this->A("oldArtikelID"))){
			$gui->type("EK1", "readonly");
			$gui->descriptionField("EK1", "Der EK kann nicht bearbeitet werden, da der Artikel einen Lagerbestand hat.");
		}
		
		$BC = new Button("Brutto- in Nettopreis umrechnen", "./images/i2/calc.png", "icon");
		#$BC->onclick("rme('Artikel','-1','calcBruttoPreis', Array(\$j('#1xPostenForm input[name=preis]').val(), \$j('#1xPostenForm input[name=mwst]').val()),'\$j(\'#1xPostenForm input[name=preis]\').val(transport.responseText);');");
		$BC->contextMenu("Calculator", "#1xPostenForm input[name=preis]", "Rechner");
		
		$gui->addFieldButton("preis", $BC);
		
		$gui->addFieldEvent("preis", "onKeyup", OnEvent::rme($this, "checkArtikelPrice", array("this.value"), "function(t){ \$j('#priceChange').html(t.responseText); }"));
		$gui->addFieldEvent("EK1", "onKeyup", OnEvent::rme($this, "checkArtikelEK1", array("this.value"), "function(t){ \$j('#ek1Change').html(t.responseText); }"));
		$gui->descriptionField("preis", "<div id=\"priceChange\"></div>");
		$gui->descriptionField("EK1", "<div id=\"ek1Change\"></div>");
		$gui->space("menge");
		$gui->space("beschreibung");
		

		$gui->descriptionField("createArtikel","Soll dieser Posten als Artikel angelegt werden?");
		

		if($this->A("oldArtikelID") != "0" AND $this->A("oldArtikelID") != "")
			$gui->type("createArtikel", "hidden");
		else {
			$gui->space("createArtikel");
			
			
			$kat = new Kategorien();
			$kat->addAssocV3("type","=","2");
			$kat->addOrderV3("name", "ASC");
			$cats = $kat->getArrayWithKeysAndValues("bitte auswählen");
			$gui->toggleFields("createArtikel", array("1"), array("KategorieID"));
			$gui->insertAttribute("after", "createArtikel", "KategorieID");
			$gui->type("KategorieID", "select", $cats);
			$gui->label("KategorieID", "Kategorie");
		}

		if(Session::isPluginLoaded("mBrutto")){
			$gui->type("isBrutto","checkbox");
			$gui->label("isBrutto","Bruttopreis?");
			$gui->descriptionField("isBrutto","Ist der angegebene Preis ein Bruttopreis?");
			$gui->label("preis","Preis");
			$gui->activateFeature("addSaveDefaultButton", $this, "isBrutto");
		} else 
			$gui->type("isBrutto", "hidden");

		if(Session::isPluginLoaded("mDifferenzbesteuerung")){
			$gui->insertAttribute ("after", "isBrutto", "differenzbesteuert");
			$gui->insertAttribute ("after", "differenzbesteuert", "differenzbesteuertMwSt");
			$gui->type("differenzbesteuert","checkbox");
			#$gui->type("mwst","hidden");
			$gui->label("differenzbesteuert", "Differenzbesteuert");
			$gui->label("differenzbesteuertMwSt", "Differenzbest. MwSt");
			$gui->toggleFields("differenzbesteuert", "1", array("differenzbesteuertMwSt"), array("mwst"));
			$gui->addFieldEvent("differenzbesteuert", "onchange", "if(this.checked) { \$j('[name=differenzbesteuertMwSt]').val(\$j('[name=mwst]').val()); \$j('[name=mwst]').val('".Util::CLNumberParserZ(0)."'); }");
		}
		
		if(Session::isPluginLoaded("mexportDatev") AND mUserdata::getGlobalSettingValue("DVKappendixKundenKonto", "0"))
			$gui->space("sachkonto");
		else
			$gui->type("sachkonto", "hidden");
		
		
		if(!Session::isPluginLoaded("Provisionen"))
			$gui->type("EK2", "hidden");
		
		foreach($userHiddenFields as $key => $value)
			$gui->type($key, "hidden");
		
		foreach($userLabels as $key => $value)
			$gui->label($key,$value);
			
		if(mUserdata::getPluginSpecificData("Provisionen", "pluginSpecificHideEK"))
			$gui->type("EK2", "hidden");
		
		
		if(mUserdata::getPluginSpecificData("Provisionen", "pluginSpecificHideEK1"))
			$gui->type("EK1", "hidden");
		
		$gui->customize($this->customizer);

		$gui->space("EK1");
		
		return $gui;
	}
	
	public static function parserCharge($w, $l, $E){
		$AC = LagerbestandWare::chargen($E->A("oldArtikelID"));

		$chargen = ["##0" => "Keine Charge"];
		while($C = $AC->n())
			$chargen[$C->A("LagerbestandWareCharge")."##".$C->A("LagerbestandWareLagerID")] = $C->A("LagerbestandWareCharge")." (".$C->A("menge")." Stück, ".$C->A("LagerName").")";
		
		#print_r($chargen);
		
		if(trim($E->A("PostenUsedCharge")) != "" AND !isset($chargen[$E->A("PostenUsedCharge")."##".$E->A("PostenLagerID")])){
			#$gui->type("PostenUsedCharge", "select", $chargen);
			$IC = new HTMLInput("PostenUsedCharge", "readonly", $w);
			$L = new Lager($E->A("PostenLagerID"));
			
			#$IL = new HTMLInput("PostenLagerID", "hidden", $E->A("PostenLagerID"));
			return $IC." aus ".$L->A("LagerName");#.$IL;
		}
		
		$IS = new HTMLInput("PostenSelectCharge", "select", ($w != "" ? "$w##".$E->A("PostenLagerID") : "##0"), $chargen);
		$IS->onchange("var ex = \$j(this).val().split('##'); \$j('[name=PostenUsedCharge]').val(ex[0]); \$j('[name=PostenLagerID]').val(ex[1]);");
		
		$IC = new HTMLInput("PostenUsedCharge", "hidden", $w);
		$IL = new HTMLInput("PostenLagerID", "hidden", $E->A("PostenLagerID"));
		
		return $IS.$IC.$IL;
	}
	
	public function checkArtikelPrice($newPrice){
		if(!$this->A("oldArtikelID"))
			return;
		
		$Artikel = new Artikel($this->A("oldArtikelID"), false);
		$oldPrice = $Artikel->A("preis");
		$newPrice = Util::CLNumberParserZ($newPrice, "store");
		
		if($newPrice == $oldPrice)
			return;
		
		echo "<a href=\"#\" style=\"color:grey;\" onclick=\"if(!confirm('Preis im Artikel überschreiben?')) return; ".OnEvent::rme($this, "saveArtikelPrice", array("$newPrice"), "function(){ \$j('#priceChange').html(''); }")."return false;\">Neuen Preis in Artikel übernehmen?</a>";
	}
	
	public function checkArtikelEK1($newEK1){
		if(!$this->A("oldArtikelID"))
			return;
		
		$Artikel = new Artikel($this->A("oldArtikelID"), false);
		$oldEK1 = $Artikel->A("EK1");
		$newEK1 = Util::CLNumberParserZ($newEK1, "store");
		
		if($newEK1 == $oldEK1)
			return;
		
		echo "<a href=\"#\" style=\"color:grey;\" onclick=\"if(!confirm('Preis im Artikel überschreiben?')) return; ".OnEvent::rme($this, "saveArtikelEK1", array("$newEK1"), "function(){ \$j('#ek1Change').html(''); }")."return false;\">Neuen EK1 in Artikel übernehmen?</a>";
	}
	
	public function saveArtikelPrice($newPrice){
		$A = new Artikel($this->A("oldArtikelID"), false);
		$A->changeA("preis", $newPrice);
		$A->saveMe();
		
		Red::messageSaved();
	}
	
	public function saveArtikelEK1($newEK1){
		$A = new Artikel($this->A("oldArtikelID"), false);
		$A->changeA("EK1", $newEK1);
		$A->saveMe();
		
		Red::messageSaved();
	}
	
	public static function parserLohnkosten($w, $l, $E){
		$I = new HTMLInput("PostenLohnkosten", "text", $w);
		$I->style("width:45%;margin-right:10px;");
		
		$IM = new HTMLInput("PostenLohnkostenMwSt", "text", $E->A("PostenLohnkostenMwSt"));
		$IM->style("width:60px;text-align:right;");
		
		return $I."<span style=\"color:grey;\">MwSt:</span>".$IM."<span style=\"color:grey;\">%</span>";
	}
	
	public static function parserBild($w, $l, $E){
		$BN = new Button("Keine Änderung", "bestaetigung", "icon");
		$BN->onclick("\$j('.bildAction').removeClass('confirm'); \$j('[name=bildAction]').val('').trigger('change'); \$j(this).addClass('confirm');");
		$BN->className("bildAction confirm");
		$BN->style("padding:5px;");
		
		$B = new Button("Bild löschen", "trash", "icon");
		$B->onclick("\$j('.bildAction').removeClass('confirm'); \$j('[name=bildAction]').val('delete').trigger('change'); \$j(this).addClass('confirm');");
		$B->className("bildAction");
		$B->style("padding:5px;");
		
		$BO = new Button("Anderes Bild", "./open3A/Auftraege/changeImage.png", "icon");
		$BO->sidePanel("Posten", $E->getID(), "getPix", array("'bildAction'", "'anotherPic'"));
		$BO->style("padding:5px;");
		$BO->className("bildAction");
		$BO->id("anotherPic");
		
		return $BN.$B.$BO;
	}
	
	public function getPix($updateField = "bildAction", $updateAction = "anotherPic"){
		#$Artikel = new Artikel($this->A("oldArtikelID"));
		$show = mUserdata::getUDValueS("PostenULPixShow", "article");#BPS::getProperty("PostenGUI", "show", "article");
		#BPS::unsetProperty("PostenGUI", "show");
		$useUpload = BPS::getProperty("PostenGUI", "useUpload");
		BPS::unsetProperty("PostenGUI", "useUpload");
		if($useUpload){
			echo OnEvent::script("\$j('.$updateField').removeClass('confirm'); \$j('[name=$updateField]').val('file:".str_replace("\\", "/", $useUpload)."').trigger('change'); \$j('#$updateAction').addClass('confirm');".OnEvent::popupSidePanel("Posten", $this->getID(), "getPix")."");
		}
		
		$T = new HTMLTable(2);
		$T->setTableStyle("width:100%;");
		
		$T->setColWidth(1, "50%");
		$T->setColWidth(2, "50%");
		#$T->setColWidth(3, "33.333%");
		$T->setTableID("picSelection");
		
		$T->addRow(array("Artikel", "Posten"));
		$T->addRowClass("backgroundColor4");
		$T->addCellStyle(1, "padding:10px;cursor:pointer;");
		$T->addCellStyle(2, "padding:10px;cursor:pointer;");
		if($show == "article")
			$T->addCellClass(1, "highlight");
		if($show == "posten")
			$T->addCellClass(2, "highlight");
		
		$T->addCellEvent(2, "click", OnEvent::rme("mUserdata", "setUserdataS", ["'PostenULPixShow'", "'posten'"])."\$j('.picSelectionContent').hide(); \$j('#picSelectionPosten').show(); \$j('#picSelection .highlight').removeClass('highlight'); \$j(this).addClass('highlight');");
		$T->addCellEvent(1, "click", OnEvent::rme("mUserdata", "setUserdataS", ["'PostenULPixShow'", "'article'"])."\$j('.picSelectionContent').hide(); \$j('#picSelectionArticle').show(); \$j('#picSelection .highlight').removeClass('highlight'); \$j(this).addClass('highlight');");
		
		
		$T->addRow(array("Beleg", "Pool"));
		$T->addRowClass("backgroundColor4");
		$T->addCellStyle(1, "padding:10px;cursor:pointer;");
		$T->addCellStyle(2, "padding:10px;cursor:pointer;");
		if($show == "document")
			$T->addCellClass(1, "highlight");
		if($show == "pool")
			$T->addCellClass(2, "highlight");
		
		#$T->addCellStyle(3, "padding:10px;cursor:pointer;");
		
		$T->addCellEvent(1, "click", OnEvent::rme("mUserdata", "setUserdataS", ["'PostenULPixShow'", "'document'"])."\$j('.picSelectionContent').hide(); \$j('#picSelectionDocument').show(); \$j('#picSelection .highlight').removeClass('highlight'); \$j(this).addClass('highlight');");
		$T->addCellEvent(2, "click", OnEvent::rme("mUserdata", "setUserdataS", ["'PostenULPixShow'", "'pool'"])."\$j('.picSelectionContent').hide(); \$j('#picSelectionPool').show(); \$j('#picSelection .highlight').removeClass('highlight'); \$j(this).addClass('highlight');");
		
		echo $T;
		
		$dir = FileStorage::getElementDir("Artikel", $this->A("oldArtikelID"));
		if(file_exists($dir)){
			echo "<div style=\"max-height:500px;overflow:auto;".($show != "article" ? "display:none;" : "")."\" class=\"picSelectionContent\" id=\"picSelectionArticle\">";
			$dir = new DirectoryIterator($dir);
			$i = 0;
			foreach ($dir as $file) {
				if($file->isDot()) 
					continue;
				
				if($file->isDir()) 
					continue;
				
				echo "<div 
						".($i % 2 == 1 ? "class=\"backgroundColor4\"" : "")."
						style=\"padding:5px;margin-bottom:10px;box-sizing:border-box;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width:100%;display:inline-block;vertical-align:top;\">
						<img
							onclick=\"\$j('.$updateField').removeClass('confirm'); \$j('[name=$updateField]').val('file:".str_replace("\\", "/", $file->getPathname())."').trigger('change'); \$j('#$updateAction').addClass('confirm');".OnEvent::popupSidePanel("Posten", $this->getID(), "getPix")."\" 
							style=\"cursor:pointer;max-width:100%;max-height:150px;\" src=\"data:image/".Util::ext($file->getFilename()).";base64,".base64_encode(file_get_contents($file->getPathname()))."\"><br>";
				echo "<small>".$file->getFilename()."</small></div>";
				$i++;
			}
			echo "</div>";
		}
		
		
		echo "<div style=\"max-height:500px;overflow:auto;".($show != "document" ? "display:none;" : "")."\" class=\"picSelectionContent\" id=\"picSelectionDocument\">";
		$docDir = FileStorage::getElementDir("GRLBM", $this->A("GRLBMID"));
		$I = new HTMLInput("filesDocument", "file");
		$I->onchange(OnEvent::rme($this, "processDocumentUpload", array("'". basename($docDir)."'", "fileName"), " ".OnEvent::reloadSidePanel("Posten")));
		
		echo "<div style=\"padding:5px;height:50px;\" class=\"backgroundColor2\">".$I."</div>";
		
		if(file_exists($docDir)){
			$dir = new DirectoryIterator($docDir);
			$i = 0;
			foreach ($dir as $file) {
				if($file->isDot()) 
					continue;

				if($file->isDir()) 
					continue;

				if($file->getExtension() == "pdf")
					continue;
				
				echo "<div 
						".($i % 2 == 1 ? "class=\"backgroundColor4\"" : "")."
						style=\"padding:5px;margin-bottom:10px;box-sizing:border-box;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width:100%;display:inline-block;vertical-align:top;\">
						<img
							onclick=\"\$j('.$updateField').removeClass('confirm'); \$j('[name=$updateField]').val('file:".str_replace("\\", "/", $file->getPathname())."').trigger('change'); \$j('#$updateAction').addClass('confirm');".OnEvent::popupSidePanel("Posten", $this->getID(), "getPix")."\" 
							style=\"cursor:pointer;max-width:100%;max-height:150px;\" src=\"data:image/".Util::ext($file->getFilename()).";base64,".base64_encode(file_get_contents($file->getPathname()))."\"><br>";
				echo "<small>".$file->getFilename()."</small></div>";
				$i++;
			}
		}
		echo "</div>";
		
		echo "<div style=\"max-height:500px;overflow:auto;".($show != "posten" ? "display:none;" : "")."\" class=\"picSelectionContent\" id=\"picSelectionPosten\">";
		
		
		$dir = "PostenID". str_pad($this->getID(), 4, "0", STR_PAD_LEFT);
		$I = new HTMLInput("filesPool", "file");
		$I->onchange(OnEvent::rme($this, "processUpload", array("'$dir'", "fileName"), " ".OnEvent::reloadSidePanel("Posten")));
		
		echo "<div style=\"padding:5px;height:50px;\" class=\"backgroundColor2\">".$I."</div>";
		
		if(file_exists(FileStorage::getFilesDir()."$dir")){
			$Idir = new DirectoryIterator(FileStorage::getFilesDir()."$dir");
			$i = 0;
			foreach ($Idir as $file) {
				if($file->isDot()) 
					continue;

				if($file->isDir()) 
					continue;

				$BD = new Button("Datei löschen", "./images/i2/delete.gif", "icon");
				$BD->style("float:right;margin-left:5px;");
				$BD->rmePCR("Posten", -1, "deleteFile", array("'$dir'", "'".$file->getFilename()."'"), OnEvent::reloadSidePanel("Posten"));
			
				echo "<div 
						".($i % 2 == 1 ? "class=\"backgroundColor4\"" : "")."
						style=\"padding:5px;margin-bottom:10px;box-sizing:border-box;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width:100%;display:inline-block;vertical-align:top;\">
						<img
							onclick=\"\$j('.$updateField').removeClass('confirm'); \$j('[name=$updateField]').val('changeToPosten:".str_replace("\\", "/", $file->getPathname())."').trigger('change'); \$j('#$updateAction').addClass('confirm');".OnEvent::popupSidePanel("Posten", $this->getID(), "getPix")."\" 
							style=\"cursor:pointer;max-width:100%;max-height:150px;\" src=\"data:image/".Util::ext($file->getFilename()).";base64,".base64_encode(file_get_contents($file->getPathname()))."\"><br>";
				echo $BD."<small>".$file->getFilename()."</small></div>";
				
				$i++;
			}
		}
		
		echo "</div>";
		
		echo "<div style=\"max-height:500px;overflow:auto;".($show != "pool" ? "display:none;" : "")."\" class=\"picSelectionContent\" id=\"picSelectionPool\">";
		
		$dir = "PostenPool";
		$I = new HTMLInput("filesPool", "file");
		$I->onchange(OnEvent::rme($this, "processUpload", array("'$dir'", "fileName"), " ".OnEvent::reloadSidePanel("Posten")));
		
		echo "<div style=\"padding:5px;height:50px;\" class=\"backgroundColor2\">".$I."</div>";
		
		if(file_exists(FileStorage::getFilesDir()."$dir")){
			$Idir = new DirectoryIterator(FileStorage::getFilesDir()."$dir");
			$i = 0;
			foreach ($Idir as $file) {
				if($file->isDot()) 
					continue;

				if($file->isDir()) 
					continue;

				$BD = new Button("Datei löschen", "./images/i2/delete.gif", "icon");
				$BD->style("float:right;margin-left:5px;");
				$BD->rmePCR("Posten", -1, "deleteFile", array("'$dir'", "'".$file->getFilename()."'"), OnEvent::reloadSidePanel("Posten"));
			
				echo "<div 
						".($i % 2 == 1 ? "class=\"backgroundColor4\"" : "")."
						style=\"padding:5px;margin-bottom:10px;box-sizing:border-box;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width:100%;display:inline-block;vertical-align:top;\">
						<img
							onclick=\"\$j('.$updateField').removeClass('confirm'); \$j('[name=$updateField]').val('file:".str_replace("\\", "/", $file->getPathname())."').trigger('change'); \$j('#$updateAction').addClass('confirm');".OnEvent::popupSidePanel("Posten", $this->getID(), "getPix")."\" 
							style=\"cursor:pointer;max-width:100%;max-height:150px;\" src=\"data:image/".Util::ext($file->getFilename()).";base64,".base64_encode(file_get_contents($file->getPathname()))."\"><br>";
				echo $BD."<small>".$file->getFilename()."</small></div>";
				
				$i++;
			}
		}
		
		echo "</div>";
	}
	
	public function deleteFile($dir, $fileName){
		$F = new mFileGUI();
		$F->deletePoolFile($dir, $fileName);
	}
	
	public function processUpload($dir, $fileName){
		$F = new mFileGUI();
		$newName = $F->processPoolUpload($dir, $fileName);
		
		BPS::setProperty("PostenGUI", "useUpload", $newName);
	}
	
	public function processDocumentUpload($dir, $fileName){
		$F = new mFileGUI();
		$newName = $F->processPoolUpload($dir, $fileName);
		
		BPS::setProperty("PostenGUI", "useUpload", $newName);
		
		if(Util::ext($newName) == "pdf" AND extension_loaded("imagick")){
			$imagick = new Imagick();
			$imagick->setBackgroundColor("white");
			$imagick->setColorspace(Imagick::COLORSPACE_SRGB);
			$imagick->setResolution(400, 400);
			$imagick->readImage($newName."[0]");
			$imagick->setImageCompression(Imagick::COMPRESSION_JPEG); 
			$imagick->setImageCompressionQuality(70);
			$imagick->setImageFormat("jpeg");
			$imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
			$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
			$imageData = $imagick->getImageBlob();
			$imagick->destroy();
			
			$image = DBImageGUI::resizeMax($imageData, 800, 800, "jpg");
			file_put_contents(str_replace(".pdf", ".jpg", $newName), $image);
			
			BPS::setProperty("PostenGUI", "useUpload", str_replace(".pdf", ".jpg", $newName));
		}
	}
	
	public function findStaffelpreis($menge){
		$menge = Util::CLNumberParserZ($menge, "store");
		
		if($this->A("oldArtikelID") != "0" AND Session::isPluginLoaded("mStaffelpreis")){
			$SP = Staffelpreis::get("Artikel", $this->A("oldArtikelID"), $menge);
			
			$A = new Artikel($this->A("oldArtikelID"));
			$preis = Util::CLNumberParserZ($A->getGesamtNettoVK());
			$rabatt = Util::CLNumberParserZ(0);
			
			if($SP != null) {

				if($SP->A("StaffelpreisModus") == 0)
					$rabatt = Util::CLNumberParserZ($SP->A("StaffelpreisPercent"));
				elseif($SP->A("StaffelpreisModus") == 1) 
					$preis = Util::CLNumberParserZ($SP->A("StaffelpreisPercent"));
				}
			
			die(json_encode(array("preis" => $preis, "rabatt" => $rabatt)));
		}
	}
	
	/*public static function preisInputParser($w, $l, $p){
		return "<img src=\"./images/i2/calc.png\" onclick=\"rme('Artikel','-1','calcBruttoPreis',Array(\$j('#1xPostenForm input[name=preis]').val(), \$j('#1xPostenForm select[name=mwst]').val()),'\$j(\'#1xPostenForm input[name=preis]\').val(transport.responseText);');\" style=\"float:right;\" class=\"mouseoverFade\" title=\"Brutto- in Nettopreis umrechnen\" />
			<input type=\"text\" value=\"$w\" id=\"preis\" style=\"width: 85%;\" name=\"preis\" onblur=\"blurMe(this);\" onfocus=\"focusMe(this);\"/>";
	}*/
	
	public function saveMultiEditField($field, $value){
		parent::saveMultiEditField($field, $value);
		#print_r($this->getA());
		Red::messageD("Änderung gespeichert", array("bestand" => $this->messageBestand));
	}
	
	public function popupOptions($ArtikelID, $GRLBMID){
		T::load(__DIR__, "Auftraege");
		$GRLBM = new GRLBM($GRLBMID);
		$Artikel = new Artikel($ArtikelID);
		
		#$B = new Button("Beenden", "stop");
		#$B->style("float:right;margin:5px;");
		#$B->onclick(OnEvent::closePopup("Posten"));
		
		$html = "<p class=\"prettySubtitle\">".$Artikel->A("name")."</p><div style=\"clear:both;\"></div>";
		
		$showMenge = true;
		$i = 0;
		if(Session::isPluginLoaded("mLieferant")){
			$c = LieferantGUI::popupSelection($GRLBM, $ArtikelID);
			if($c != "")
				$html .= "<div class=\"sub\" style=\"width:250px;display:inline-block;vertical-align:top;\">$c</div>";
		}
		
		if(Session::isPluginLoaded("mVariante")){
			$c = VarianteArtikelGUI::popupSelection($GRLBM, $ArtikelID);
			if($c != "")
				$html .= "<div class=\"sub\" style=\"width:250px;display:inline-block;vertical-align:top;\">$c</div>";
		}
		
		if(Session::isPluginLoaded("mSeriennummer")){
			$c = SeriennummerGUI::popupSelection($GRLBM, $ArtikelID);
			if($c != ""){
				$html .= "<div class=\"sub\" style=\"width:250px;display:inline-block;vertical-align:top;\">$c</div>";
				$showMenge = false;
			}
		}
		
		if(Session::isPluginLoaded("mLagerbestandWare")){
			$c = LagerbestandWareGUI::popupSelection($GRLBM, $ArtikelID);
			if($c != ""){
				$html .= "<div class=\"sub\" style=\"width:250px;display:inline-block;vertical-align:top;\">$c</div>";	
				$showMenge = false;
			}
		}
		
		
		$aspect = Aspect::joinPoint("selections", $this, __METHOD__, array($ArtikelID, $GRLBMID), array());
		if(is_array($aspect))
			$html .= implode("", $aspect);
		else
			$html .= $aspect;
		
		if($showMenge){
			$T = new HTMLTable(1, "Menge");
			$T->weight("light");
			$T->setColClass(1, "backgroundColor2");
			$T->maxHeight(400);
		
			$IM = new HTMLInput("postenMenge", "text", Util::CLNumberParserZ(1));
			$IM->style("width:70px;text-align:right;");

			$T->addRow(array(
				"Menge: $IM"
			));
			$T->addRowClass("backgroundColor2");
			
			$html .= "<div class=\"sub\" style=\"width:250px;display:inline-block;vertical-align:top;\">$T</div>";	
		}
		
		$IAID = new HTMLInput("ArtikelID", "hidden", $ArtikelID);
		$IGID = new HTMLInput("GRLBMID", "hidden", $GRLBMID);
		
		$BOK = new Button("Posten erstellen\nund beenden", "bestaetigung");
		$BOK->style("float:right;margin:10px;");
		$BOK->rmePCR("Posten", "-1", "popupOptionsDo", array("joinFormFields('newPostenForm')")/*array($ArtikelID, $GRLBMID, "\$j('[name=lieferantSelection]').length ? \$j('[name=lieferantSelection]:checked').val() : 0", "\$j('[name=variantSelection]').length ? \$j('[name=variantSelection]:checked').val() : 0", "\$j('[name=seriennummerSelection]').length ? \$j('[name=seriennummerSelection]').val() : ''")*/, "function(t){ Auftrag.checkBestand(t); contentManager.loadFrame('subframe', 'GRLBM', $GRLBMID); ".OnEvent::closePopup("Posten")." }");
		
		$BOK2 = new Button("Posten erstellen\nund nochmal", "navigation");
		$BOK2->style("float:right;margin:10px;");
		$BOK2->rmePCR("Posten", "-1", "popupOptionsDo", array("joinFormFields('newPostenForm')"), "function(t){ Auftrag.checkBestand(t); Auftrag.reloadBeleg($GRLBMID);/*contentManager.loadFrame('subframe', 'GRLBM', $GRLBMID);*/  }");
		$BOK2->className("backgroundColor4");
		
		echo "<form id=\"newPostenForm\">".$html.$IAID.$IGID."</form>".$BOK.$BOK2.OnEvent::script("\$j('#editDetailsPosten').css('width', \$j('#editDetailsPosten .sub').length * 250);");
	}
	
	public function popupOptionsDo($data){
		T::load(__DIR__, "Auftraege");
		parse_str($data, $pdata);
		
		$ArtikelID = $pdata["ArtikelID"];
		$GRLBMID = $pdata["GRLBMID"];
		$LieferantID = null;
		$VarianteArtikelID = 0;
		$Seriennummern = "";
		$ChargeID = 0;
		$options = array();
		
		$G = new GRLBM($GRLBMID);
		
		if(isset($pdata["lieferantSelection"]))
			$LieferantID = $pdata["lieferantSelection"];
		
		if(isset($pdata["variantSelection"]))
			$VarianteArtikelID = $pdata["variantSelection"];
		
		if(isset($pdata["seriennummerSelection"]))
			$Seriennummern = $pdata["seriennummerSelection"];
		
		$menge = 1;
		if(isset($pdata["postenMenge"]))
			$menge = Util::CLNumberParserZ($pdata["postenMenge"], "store");
		
		if(Session::isPluginLoaded("mSeriennummer") AND Seriennummer::has($ArtikelID) AND $G->getMyPrefix() == Lagerbestand::updateOn($ArtikelID)){
			if(trim($Seriennummern) == "")
				Red::alertD ("Bitte tragen Sie mindestens eine Seriennummer ein");
			
			$S = new mSeriennummer();
			if($VarianteArtikelID == 0)
				$data = $S->checkNew("Artikel", $ArtikelID, explode("\n", trim($Seriennummern)), "sell", new stdClass());
			else
				$data = $S->checkNew("VarianteArtikel", $VarianteArtikelID, explode("\n", trim($Seriennummern)), "sell", new stdClass());
			
			if($data[2])
				Red::alertD($data[2]." Seriennummer".($data[2] == 1 ? "" : "n")." befinde".($data[2] == 1 ? "t" : "n")." sich nicht im Lager.");
			
			$options["serials"] = trim($Seriennummern);
			
			$menge = $data[1];
		}
		
		if(Session::isPluginLoaded("mLagerbestandWare") AND LagerbestandWare::has($ArtikelID) AND $G->getMyPrefix() == Lagerbestand::updateOn($ArtikelID)){
			$menge = Util::CLNumberParserZ($pdata["chargeMenge"], "store");
			if($menge <= 0)
				Red::alertD ("Bitte geben Sie eine Menge ein");
			
			if(!isset($pdata["chargeSelection"]) OR $pdata["chargeSelection"] == "")
				Red::alertD ("Bitte wählen Sie eine Charge aus");
			
			$ex = explode("_", $pdata["chargeSelection"]);
			
			$ChargeID = $ex[0];
			$lagerID = $ex[1];
			
			$LBW = new LagerbestandWare($ChargeID);
			$charge = $LBW->A("LagerbestandWareCharge");
			
			$bestand = LagerbestandWare::bestand($ArtikelID, $lagerID, $charge);
			if($bestand < $menge)
				Red::alertD ("Diese Menge ist nicht verfügbar (max. $bestand Stück).");
			
			$options["charge"] = $charge;
			$options["lagerID"] = $lagerID;
		}
		
		Aspect::joinPoint("before", $this, __METHOD__, array($ArtikelID, $GRLBMID, $pdata));
		
		$P = new Posten(-1);
		$P->skipVariantTest = true;
		$P->skipLieferantTest = true;
		$P->skipSeriennummernTest = true;
		$P->skipChargenTest = true;
		try {
			$PostenID = $P->newFromArtikel($ArtikelID, $GRLBMID, $menge, null, null, null, $VarianteArtikelID, $LieferantID, null, null, $options);
		} catch (LagerException $e){
			Red::errorD($e->getMessage());
		}
				
		if($ChargeID > 0){
			$P = new Posten($PostenID, false);
			#$P->changeA("PostenUsedLagerbestandWareID", $ChargeID);
			$P->changeA("PostenUsedCharge", $options["charge"]);
			$P->saveMe();
		}
		
		#if($VarianteArtikelID != 0){
		#	$V = new VarianteArtikel($VarianteArtikelID);
		#	$V->fixPosten($ArtikelID, $PostenID);
		#}
		
		if(isset($S) AND Session::isPluginLoaded("mSeriennummer") AND trim($Seriennummern) != "")
			$S->doSell(explode("\n", trim($Seriennummern)), ($VarianteArtikelID == 0 ? "Artikel" : "VarianteArtikel"), $VarianteArtikelID == 0 ? $ArtikelID : $VarianteArtikelID, $GRLBMID, $PostenID);
		
		Aspect::joinPoint("after", $this, __METHOD__, array($ArtikelID, $GRLBMID, $PostenID, $pdata));
		
		Red::messageD("Posten erstellt", array("PostenID" => $PostenID, "bestand" => $P->messageBestand));
	}
	
	public function clearMessage(){
		$this->changeA("message", "");
		$this->saveMe();
	}
}
?>