<?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 - 2020, open3A GmbH - Support@open3A.de
 */
class AuftraegeGUI extends Auftraege implements iGUIHTMLMP2, iAutoCompleteHTML, icontextMenu, iSearchFilterMulti, iCategoryFilter {
	public static $users = array("" => "unbekannt");
	private static $pSpecData = null;
	public $searchFields = array("firma",/*"nachname",*/"kundennummer", "CONCAT(vorname, ' ', nachname)");
	public static $BelegArten;
	public static $useVersions = false;
	
	function  __construct() {
		parent::__construct();
		
		$this->customize();
	}
	
	function getHTML($id, $page){
		T::load(__DIR__, "Auftraege");
		$Users = Users::getUsers();
		while($U = $Users->getNextEntry())
			self::$users[$U->getID()] = $U->A("name");
		
		$this->addAssocV3("lieferantennummer", "=", "");
		
		self::$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
		
		if(isset(self::$pSpecData["pluginSpecificCanOnlyEditOwn"]))
			$this->addAssocV3("t1.UserID","=",Session::currentUser()->getID(), "AND", "2");
		
		$i = 0;
		foreach(self::$pSpecData as $key => $value) 
			if(strstr($key,"pluginSpecificCanSeeAuftraegeFrom"))
				$this->addAssocV3("t1.UserID","=",str_replace("pluginSpecificCanSeeAuftraegeFrom","",$key),$i++ == 0 ? "AND" : "OR", "2");
			
			
		$this->addJoinV3("Adresse","AdresseID","=","AdresseID");
		if(Session::isPluginLoaded("mProjekt"))
			$this->addJoinV3("Projekt", "ProjektID", "=", "ProjektID");
		
		if(Applications::activeApplication() == "lightCRM"){
			$this->addAssocV3("status", "=", "open", "AND", "3");
			$this->addAssocV3("status", "=", "confirmed", "OR", "3");
		}
		
		if(Applications::activeApplication() == "upFab"){
			$this->addAssocV3("status", "=", "delivered", "AND", "3");
			$this->addAssocV3("status", "=", "commissioned", "OR", "3");
		}
		
		Aspect::joinPoint("queryLoad", $this, __METHOD__, array($this));
		
		$this->filterCategories();
		#$gui->showFilteredCategoriesWarning($this->filterCategories(),$this->getClearClass());
		
		$this->loadMultiPageMode($id, $page, 0);

		
		$oldType = ($_SESSION["BPS"]->isPropertySet("mGRLBMGUI","type") ? $_SESSION["BPS"]->getProperty("mGRLBMGUI","type") : -1);
		$_SESSION["BPS"]->setProperty("mGRLBMGUI","type","-1");
		
		
		
		$this->addOrderV3("auftragDatum","DESC");
		$this->addOrderV3("t1.AuftragID","DESC");
		if(isset(self::$pSpecData["pluginSpecificCanOnlyEditOwn"])) 
			$this->addAssocV3("t1.UserID","=",$_SESSION["S"]->getCurrentUser()->getID(), "AND", "2");
		
		$i = 0;
		foreach(self::$pSpecData as $key => $value) 
			if(strstr($key,"pluginSpecificCanSeeAuftraegeFrom"))
				$this->addAssocV3("t1.UserID","=",str_replace("pluginSpecificCanSeeAuftraegeFrom","",$key),$i++ == 0 ? "AND" : "OR", "2");
		
			
		if(Applications::activeApplication() == "lightCRM"){
			$this->addAssocV3 ("status", "=", "open", "AND", "3");
			$this->addAssocV3 ("status", "=", "confirmed", "OR", "3");
		}
		
		if(Applications::activeApplication() == "upFab"){
			$this->addAssocV3("status", "=", "delivered", "AND", "3");
			$this->addAssocV3("status", "=", "commissioned", "OR", "3");
		}
		
		
		Aspect::joinPoint("queryShow", $this, __METHOD__, array($this));
		
		$this->lCV3($id);

		$gui = new HTMLGUIX($this, "Auftraege");
		$gui->version("Auftraege");
		$gui->screenHeight();
		$gui->options(true, true, false, true);
		$gui->tip();
		
		$gui->attributes(array("firma","bezahlt"));
		
		
		$gui->parser("bezahlt","AuftraegeGUI::getPaidImg");#, array("\$aid",(isset(self::$pSpecData["pluginSpecificCanOnlySeeKalk"]) ? "true" : "false")));
		$gui->parser("firma","AuftraegeGUI::firmaParser");#,array("\$sc->nachname","asd","\$sc->vorname", "\$sc->UserID", "\$ProjektID", "\$ProjektName", "\$AuftragAdresseNiederlassungID", "\$AuftragAdresseNiederlassungData"));



		if(Applications::activeApplication() == "lightCRM"){
			
			$BN = $gui->addSideButton("Neues\nAngebot","angebot");
			$BN->customSelect("contentRight", -1, "mAdresse", "Auftrag.createAngebot");
			
			$gui->addSideRow("&nbsp;");
		} elseif(Applications::activeApplication() == "upFab"){
			
			$BN = $gui->addSideButton("Neuer\nLieferschein","lieferschein");
			$BN->customSelect("contentRight", -1, "mAdresse", "Auftrag.createLieferschein");
			
			$BN = $gui->addSideButton("Neue\nKommission","kommission");
			$BN->customSelect("contentRight", -1, "mAdresse", "Auftrag.createKommission");
			
			$gui->addSideRow("&nbsp;");
		} else {
			if(Aspect::joinPoint("newButton", $this, __METHOD__, array(), true)){
				$BA1x = $gui->addSideButton("Neuen Auftrag\nerstellen", "new");
				$BA1x->customSelect("contentRight", -1, "mAdresse", "Auftrag.createEmpty");

				$gui->addSideRow("&nbsp;");
			}
			
			if(Aspect::joinPoint("1xButton", $this, __METHOD__, array(), true)){
				$BA1x = $gui->addSideButton("Auftrag mit\n1x-Adresse", "1xAddress");
				$BA1x->className("backgroundColor0");
				$BA1x->onclick("Auftrag.create1Time(function(){ contentManager.editInPopup('AuftragAdresse', -1, '1x-Adresse erstellen', 'AuftragAdresseGUI;AuftragID:'+Auftrag.newestID+';displayMode:auftragsAdresse');});");
			}
		}
		
		
		if(Aspect::joinPoint("multiPrintButton", $this, __METHOD__, array(), true)){
			$BP = $gui->addSideButton("multiDruck\nListe anzeigen","liste");
			$BP->onclick("contentManager.editInPopup('multiPrintBasket','','".T::_("multiDruck-Liste")."');");
		}
		#$BP->id("showMultiPrintList");
		#$tab->addRowClass("backgroundColor0");

		
		if(Aspect::joinPoint("filterButton", $this, __METHOD__, array(), true) AND Applications::activeApplication() != "lightCRM" AND Applications::activeApplication() != "upFab")
			$gui->addSideRow($this->getFilterButtons("Auftraege"));
		
		
		$tab = new HTMLSideTable("left");
		Aspect::joinPoint("sideTable", $this, __METHOD__, $tab);
		
		foreach($tab->getContent() AS $row)
			$gui->addSideRow($row[0]);
		
		
		$gui->customize($this->customizer);

		$html = $gui->getBrowserHTML($id);
		$_SESSION["BPS"]->setProperty("mGRLBMGUI","type","$oldType");
		return $html;
	}
	
	protected function getFilterButtons($target){
		// <editor-fold defaultstate="collapsed" desc="Aspect:jP">
		try {
			$MArgs = func_get_args();
			return Aspect::joinPoint("around", $this, __METHOD__, $MArgs);
		} catch (AOPNoAdviceException $e) {}
		Aspect::joinPoint("before", $this, __METHOD__, $MArgs);
		// </editor-fold>
		
		$currentFilter = mUserdata::getUDValueS("filteredCategoriesInHTMLGUI$target", "");
		
		$statusButtons = "<div style=\"margin-bottom:5px;\"><small style=\"color:grey;\">".T::_("Filtern nach Auftrags&shy;status").":</small></div>";
		$status = self::getStatus();
		$statusIcons = self::getStatusIcons();
		$i = 1;
		foreach($status AS $k => $v){
			$statusSet = "";
			foreach(self::getStatus() AS $ks => $vs)
				$statusSet .= ($statusSet != "" ? ";" : "")."$ks:".($ks == $k ? (strpos($currentFilter, $k) !== false ? "0" : "1") : "0");
			
			
			$BO = new Button($v, $statusIcons[$k], "iconicG");
			$BO->rmePCR("HTML", "", "saveContextMenu", array("'filterCategories'", "'$target--;$statusSet'"), "contentManager.reloadFrame('contentRight');");
			$BO->style($i < count($status) ? "margin-right:12px;" : "");
			if(strpos($currentFilter, $k) !== false)
				$BO->style("color:#222;".($i < count($status) ? "margin-right:12px;" : ""));
			
			$statusButtons .= $BO;
			$i++;
		}
		
		return $statusButtons;
	}

	public function findCustomerNumbers(){
		$T = new HTMLTable(3);
		$AC = anyC::get("Auftrag");
		$AC->addAssocV3("kundennummer", "<", "0");
		while($A = $AC->n()){
			$kdnr = "kA";
			$user = "kA";
			
			$Adresse = new Adresse($A->A("AdresseID"));
			
			$ACA = anyC::get("Adresse");
			$ACA->addAssocV3("AuftragID", "=", "-1");
			$ACA->addAssocV3("firma", "=", $Adresse->A("firma"));
			$ACA->addAssocV3("plz", "=", $Adresse->A("plz"));
			$ACA->addAssocV3("strasse", "=", $Adresse->A("strasse"));
			$ACA->addAssocV3("nr", "=", $Adresse->A("nr"));
			
			$AdOrig = $ACA->n();
			
			if($AdOrig != null){
				$K = Kappendix::getKappendixToAdresse($AdOrig->getID());
				if($K != null){
					$A->changeA("kundennummer", $K->A("kundennummer"));
					$A->changeA("UserID", $K->A("KappendixAuftragUserID"));
					
					$kdnr = $K->A("kundennummer");
					$user = $K->A("KappendixAuftragUserID");
					$A->saveMe();
				}
			}
			
			$T->addRow(array($A->getID(), $Adresse->getShortAddress(), $kdnr."/".$user));
		}
		
		echo $T;
	}
	
	protected static $GRLBMAttributes;

	public static function getPaidImg($w, $l, $E){
		$s[0] = $E->getID();
		$s[1] = (isset(self::$pSpecData["pluginSpecificCanOnlySeeKalk"]) ? "true" : "false");
		/*if(!is_array($p))
			$s = HTMLGUI::getArrayFromParametersString($p);
		else
			$s = $p;*/
		
		$s[2] = BPS::getProperty("multiPrintBasketGUI", "ids", "");
		
		if(self::$GRLBMAttributes == null){
			$GRLBM = new GRLBM(-1);
			self::$GRLBMAttributes = PMReflector::getAttributesArray($GRLBM->newAttributes());

			if(self::$BelegArten == null)
				self::$BelegArten = Auftrag::getBelegArten();
			if(!Auftrag::getBelegArten("B") AND Applications::activeApplication() != "openWaWi")
				self::$BelegArten = array_merge(array_slice(self::$BelegArten, 0, array_search("A", self::$BelegArten) + 1), array("B"), array_slice(self::$BelegArten, array_search("A", self::$BelegArten) + 1));
		}
		
		$GRLBMs = anyC::get("GRLBM");
		$GRLBMs->addAssocV3("AuftragID","=",$s[0]);
		$GRLBMs->addAssocV3("isM","=","0");
		$GRLBMs->setFieldsV3(self::$GRLBMAttributes);

		foreach(self::$BelegArten AS $B)
			if(in_array("is".$B, self::$GRLBMAttributes))
				$GRLBMs->addFieldV3("GROUP_CONCAT(is$B) AS is{$B}C");
		
		$GRLBMs->addFieldV3("GROUP_CONCAT(isWhat) AS isWhatC");
		if(self::$useVersions)
			$GRLBMs->addFieldV3("GROUP_CONCAT(prefix, nummer, IF(GRLBMVersion > 0 AND isA = '1', CONCAT('-', GRLBMVersion), '')) AS numbers");
		else
			$GRLBMs->addFieldV3("GROUP_CONCAT(prefix, nummer) AS numbers");
		$GRLBMs->addFieldV3("GROUP_CONCAT(prefix) AS prefixes");
		
		$GRLBMs->addGroupV3("AuftragID");
		if($s[1] == "true") 
			$GRLBMs->addAssocV3("isWhat","=","Kalk");
		#$GRLBMs->addOrderV3("datum", "DESC");
		$t = $GRLBMs->getNextEntry();

		if($t == null) 
			return T::_("keine Belege");

		$g = array();
		foreach(self::$BelegArten AS $B){
			if(!isset($g[$B])) $g[$B] = 0;
			
			if(in_array("is".$B, self::$GRLBMAttributes))
				$g[$B] += substr_count($t->A("is{$B}C"),"1");
			else
				$g[$B] += substr_count($t->A("isWhatC"),$B);
		}
		
		if(array_sum($g) == 1){
			if($s[2] == ",,") $s[2] = "";
			$BA = new Button("zu multiDruck-Liste hinzufügen", "./images/i2/notok.gif", "icon");
			$BA->id("addID".$t->getID()."");
			$BA->style(((!strstr($s[2],",".$t->getID().",") OR $s[2] == "") ? "display:block;":"display:none;")."float:left;");
			$BA->onclick("Auftrag.addToMultiPrint('".$t->getID()."');");
			
			$BR = new Button("von multiDruck-Liste entfernen", "./images/i2/ok.gif", "icon");
			$BR->id("subID".$t->getID()."");
			$BR->style(((!strstr($s[2],",".$t->getID().",") OR $s[2] == "") ? "display:none;":"display:block;")."float:left;");
			$BR->onclick("Auftrag.subFromMultiPrint('".$t->getID()."');");
			
			$text = new stdClass();
			$text->line1 = $t->A("prefix").$t->A("nummer");
			$text->line2 = T::_("vom")." ".Util::CLDateParser($t->A("datum"));
			$text->append = "";
			
			Aspect::joinPoint("single", null, __METHOD__, array($BA, $BR, $text, $t));
			
			return "$BA$BR<strong>$text->line1</strong><br><small style=\"color:grey;\">$text->line2</small>".$text->append;
		}
		
		if(array_sum($g) == 2){
			
			$sex = explode(",", $t->A("numbers"));
			$sxe = explode(",", $t->A("prefixes"));
			foreach($sex AS $k => $number){
				$sex[$k] = str_replace($sxe[$k], "<strong>".$sxe[$k]."</strong>", $number);
			}
			
			$text = new stdClass();
			$text->line1 = implode("<br>", $sex);
			$text->line2 = "";
			$text->append = "";
			
			Aspect::joinPoint("single", null, __METHOD__, array($BA, $BR, $text, $t));
			
			return "$text->line1<br><small style=\"color:grey;\">$text->line2</small>".$text->append;
		}


		$Tab = new HTMLTable(count(self::$BelegArten));
		$Tab->setTableStyle("width:100%;border:0px;");

		foreach(self::$BelegArten AS $k => $v){
			$Tab->setColClass($k + 1, "");

			$Tab->setColWidth($k + 1, round(100 / count(self::$BelegArten))."%");

			self::$BelegArten[$k] = substr($v, 0, 1);
			if($g[$v] == 0) $g[$v] = "";
		}

		$Tab->addRow(self::$BelegArten);
		if(Applications::activeApplication() == "lightCRM" OR Applications::activeApplication() == "upFab")
			$Tab->addRowStyle("font-weight:bold;");
		else
			$Tab->addRowStyle("font-weight:bold;text-align:right;");


		$Tab->addRow(array_values($g));
		if(Applications::activeApplication() != "lightCRM" AND Applications::activeApplication() != "upFab")
			$Tab->addRowStyle("text-align:right;");

		$text = new stdClass();
		$text->tab = $Tab;
		$text->append = "";

		Aspect::joinPoint("multi", null, __METHOD__, array($t, $g, $text));
		
		return $text->tab.$text->append;
			
	}

	public function getAvailableCategories(){
		return self::getStatus();
	}

	public function getCategoryFieldName(){
		// <editor-fold defaultstate="collapsed" desc="Aspect:jP">
		try {
			$MArgs = func_get_args();
			return Aspect::joinPoint("around", $this, __METHOD__, $MArgs);
		} catch (AOPNoAdviceException $e) {}
		Aspect::joinPoint("before", $this, __METHOD__, $MArgs);
		// </editor-fold>
		
		return "status";
	}

	
	public static function firmaParser($w,$E){
		$s = array();
		$s[0] = $E->A("nachname");
		$s[2] = $E->A("vorname");
		$s[3] = $E->A("UserID");
		$s[4] = $E->A("ProjektID");
		$s[5] = $E->A("ProjektName");
		$s[6] = $E->A("AuftragAdresseNiederlassungID");
		$s[7] = $E->A("AuftragAdresseNiederlassungData");
		
		$name = (trim($w) == "" ? stripslashes($s[2]).($s[2] != "" ? " " : "").stripslashes($s[0]) : stripslashes($w));
		
		if($s[6] > 0){
			$data = json_decode($s[7]);
			$name .= "<br><small style=\"color:grey;\">".$data->AdresseNiederlassungOrt."</small>";
		}
		
		$name .= ((isset($s[3]) AND isset(self::$users[$s[3]])) ? "<br><small style=\"color:grey;\">von ".self::$users[$s[3]]."</small>" : "");
		
		
		if($s[4] > 0)
			$name .= "<br><small style=\"color:grey;\">$s[5]</small>";
		
		$append = Aspect::joinPoint("append", __CLASS__, __METHOD__, array($w, $E), "");
		if(is_array($append))
			foreach($append AS $v)
				$name .= $v;
		else
			$name .= $append;
		
		return $name;
	}
	
	public static function parseRnr($w,$l,$p){
		if($w != "") return $p."$w";
	}
	
	public static $prefixes = array();
	public function getACHTML($attributeName, $query){
		$Users = Users::getUsers();
		while($U = $Users->getNextEntry())
			self::$users[$U->getID()] = $U->A("name");
		
		
		$ASH = new AuftraegeSearchHelper();
		
		$searchByCID = false;
		if(is_numeric($query) AND in_array("kundennummer", $this->searchFields))
			$searchByCID = true;
		
		$gui = new HTMLGUI();
		$searchByNumber = false;
		if($query[0] == "#" AND isset($query[1])/* AND (strpos("RLKAGBWST", strtoupper($query[1])) !== false)*/){
			$searchByNumber = true;
			$isWhat = 1;
			$query = str_replace("#","", $query);
			$what = "is".$query[0];
			if($query[0] == "K"){
				$isWhat = "Kalk";
				$what = "isWhat";
			}
			if(!in_array($query[0], ["G", "R", "L", "B", "A"])){
			#if($query[0] == "W" OR $query[0] == "S"){
				$isWhat = $query[0];
				$what = "isWhat";
			}
			$ASH->addJoinV3("GRLBM",$what,"=",$isWhat);
			
			$gui->setParser("nummer", "AuftraegeGUI::parseRnr", array($query[0]));
		}
		
		$_SESSION["BPS"]->registerClass("HTMLGUI");
		$_SESSION["BPS"]->setACProperty("targetFrame","contentLeft");
		$_SESSION["BPS"]->setACProperty("targetPlugin","Auftrag");
		if($attributeName == "quickSearchmLBestellung")
			$_SESSION["BPS"]->setACProperty("targetPlugin","LBestellung");
					
		$gui->setShowAttributes(array("firma","nummer"));

		$gui->setParser("firma","AuftraegeGUI::firmaParser", array("\$sc->nachname","asd","\$sc->vorname", "\$sc->UserID", "\$ProjektID", "\$ProjektName", "\$AuftragAdresseNiederlassungID", "\$AuftragAdresseNiederlassungData"));
		$gui->setParser("nummer","AuftraegeGUI::nummerParser", array("\$sc->datum", "\$sc->GRLBMID"));

		
		$searchByReference = false;
		if($query[0] == "?"){
			$query = str_replace("?","", $query);
			$searchByReference = true;
		}
		
		$searchByProjekt = false;
		if($query[0] == "*" AND Session::isPluginLoaded("mProjekt")){
			$query = str_replace("*","", $query);
			$searchByProjekt = true;
		}
		
		$searchByArtikel = false;
		if($query[0] == "+"){
			$query = str_replace("+","", $query);
			$searchByArtikel = true;
		}
		
		$searchByDate = false;
		if(Util::CLDateParser($query, "store") != -1)
			$searchByDate = true;
		
		
		
		
		#$ASH->addJoinV3("User","UserID","=","UserID");
		$ASH->addAssocV3("isM","=","0");
		if(Applications::activeApplication() == "lightCRM"){
			$ASH->addAssocV3("isA","=","1", "AND", "100");
			$ASH->addAssocV3("isB","=","1", "OR", "100");
		}
		
		if(Applications::activeApplication() == "openWaWi"){
			$ASH->addAssocV3("isWhat","=","O", "AND", "100");
			$ASH->addAssocV3("isWhat","=","P", "OR", "100");
		}
		
		switch($attributeName){
			case "quickSearchAuftraege":
			case "quickSearchmLBestellung":
				$Users = Users::getUsers();
				while($U = $Users->getNextEntry())
					self::$users[$U->getID()] = $U->A("name");
		
				$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
				#$ud = new mUserdata();
				#$d = $ud->getUDValueCached("auftraegeMinDate");
				#$d2 = $ud->getUDValueCached("auftraegeMaxDate");
				
				if(isset($pSpecData["pluginSpecificCanOnlyEditOwn"]))
					$ASH->addAssocV3("t1.UserID","=", Session::currentUser()->getID());
				
				foreach($pSpecData as $key => $value) 
					if(strstr($key,"pluginSpecificCanSeeAuftraegeFrom")) $ASH->addAssocV3("t1.UserID","=",str_replace("pluginSpecificCanSeeAuftraegeFrom","",$key),"OR");
		
				$html = "";
				/*if(!$searchByArtikel AND !$searchByDate AND !$searchByNumber AND !$searchByCID AND !$searchByReference AND ($d != null OR $d2 != null)) {
					$D = new Datum(time());
					$datum = $D->parseGerDate($d);
					
					$D2 = new Datum(time());
					$datum2 = $D2->parseGerDate($d2);
					
					if($datum != -1 OR $datum2 != -1) {
						if($datum != -1) $ASH->addAssocV3("datum",">=", $datum);
						if($datum2 != -1) $ASH->addAssocV3("datum","<=", $datum2);
						
						$html = "<p style=\"padding:3px;\"><img src=\"./images/i2/note.png\" style=\"float:left;margin-right:3px;\" /> Es werden nur Belege angezeigt, die ".($datum != -1 ? "<strong>ab</strong> dem $d" : "").(($datum != -1 AND $datum2 != -1) ? " und " : "").($datum2 != -1 ? "<strong>vor</strong> dem $d2" : "")." erstellt wurden.</p>";
					}
				}
				
				
				if(!$searchByArtikel AND !$searchByDate AND !$searchByNumber AND !$searchByCID AND !$searchByReference AND $d == null){
					$html = "<p style=\"padding:3px;\"><img src=\"./images/i2/note.png\" style=\"float:left;margin-right:3px;\" /><small>Aus Gründen der Performance werden nur die Aufträge der letzten 3 Monate durchsucht. Bitte stellen Sie manuell ein Datum ein, um dies zu überschreiben.</small></p>";
					$ASH->addAssocV3("datum",">=", time() - 3 * 4 * 7 * 24 * 3600);
				}*/
				
				if($searchByNumber)
					$ASH->addAssocV3("nummer", "LIKE", str_replace("*", "%", substr($query,1)), "AND", "1");
				elseif($searchByArtikel){
					$AC = anyC::get("Posten");
					$AC->addJoinV3("GRLBM", "GRLBMID", "=", "GRLBMID");
					$AC->addJoinV3("Auftrag", "t2.AuftragID", "=", "AuftragID");
					$AC->addJoinV3("Adresse","t3.AdresseID","=","AdresseID");

					$AC->setLimitV3("10");
					$AC->addOrderV3("auftragDatum","DESC");
					
					$fields = array("nachname", "auftragDatum AS datum", "t2.GRLBMID", "nummer", "t3.AuftragID","firma","vorname", "t3.UserID", "AuftragAdresseNiederlassungID", "AuftragAdresseNiederlassungData");
					$AC->setFieldsV3($fields);
					
					$AC->addAssocV3("name", "LIKE", "%$query%", "AND", "1");
					$AC->addAssocV3("beschreibung", "LIKE", "%$query%", "OR", "1");
					try {
						$c = new CustomizerPostenTextGUI();
						$AC->addAssocV3("PostenText", "LIKE", "%$query%", "OR", "1");
					} catch (Exception $ex) {

					}
					$AC->lCV3();
					
					$this->findPrefixes($AC);
					
					$gui->setObject($AC);
					$gui->customize($this->customizer);

					die($gui->getACHTMLBrowser("quickSearchLoadFrame", true, null, "AuftragID"));
				} elseif($searchByCID){
					$ASH->addAssocV3("kundennummer", "LIKE", "%$query%", "AND", "1");
					$ASH->addGroupV3("AuftragID");
					Aspect::joinPoint("isnumeric", $this, __METHOD__, array($ASH, $query));
				}
				elseif($searchByProjekt){ //Findet auch Aufträge ohne Beleg
					$AC = anyC::get("Projekt");
					$AC->addJoinV3("Auftrag", "ProjektID", "=", "ProjektID");
					$AC->addJoinV3("Adresse","t2.AdresseID","=","AdresseID");

					$AC->setLimitV3("10");
					$AC->addOrderV3("auftragDatum","DESC");
					
					$fields = array("nachname", "auftragDatum AS datum", "t2.AuftragID", "t1.ProjektID", "ProjektName","firma","vorname", "t2.UserID", "AuftragAdresseNiederlassungID", "AuftragAdresseNiederlassungData");
					$AC->setFieldsV3($fields);
					
					$AC->addAssocV3("ProjektName", "LIKE", "%$query%", "AND", "1");
					$AC->lCV3();
					
					$this->findPrefixes($AC);
					
					$gui->setObject($AC);
					$gui->customize($this->customizer);

					die($gui->getACHTMLBrowser("quickSearchLoadFrame", true, null, "AuftragID"));
				}
				elseif($searchByReference)
					$ASH->addAssocV3("GRLBMReferenznummer", "=", $query, "AND", "1");
				
				elseif($searchByDate)
					$ASH->addAssocV3("t3.datum", "=", Util::CLDateParser($query, "store"), "AND", "1");
				
				
				else {
					foreach($this->searchFields AS $k => $field)
						$ASH->addAssocV3($field, "LIKE", "%$query%", $k == 0 ? "AND" : "OR", "1");
					
					$ASH->addGroupV3("AuftragID");
				}
					#$q2 = DBStorage::findNonUft8($query); // REMOVED 31.10.2012
					#foreach($this->searchFields AS $k => $field)
					#	$ASH->addAssocV3($field, "LIKE", "%$q2%", "OR", "1");
					
					
				$ASH->addOrderV3("datum","DESC");
				$ASH->lCV3();
				
				$this->findPrefixes($ASH);
				
				$gui->setObject($ASH);
				$gui->customize($this->customizer);

				echo $html.$gui->getACHTMLBrowser("quickSearchLoadFrame");
			break;
		}
	}
	
	private function findPrefixes($ASH){
		if($ASH->numLoaded() > 0){
			$AC = anyC::get("GRLBM");
			while($A = $ASH->getNextEntry())
				$AC->addAssocV3("GRLBMID", "=", $A->A("GRLBMID"), "OR");


			while($GRLBM = $AC->getNextEntry())
				self::$prefixes[$GRLBM->getID()] = $GRLBM->getMyPrefix();
		}

		$ASH->resetPointer();
	}
	
	public static function nummerParser($w, $l, $p){
		$s = HTMLGUI::getArrayFromParametersString($p);
		return self::$prefixes[$s[1]].$w."<br><small>".date("d.m.Y",$s[0]+0)."</small>";
	}
	
	public function searchPopup(){
		$B = new Button("Filter", "./images/i2/searchFilter.png", "icon");
		$B->style("float:left;margin-right:5px;");
		
		echo "
		<p>Es werden folgende Felder durchsucht:<br>
		<br>
		Firma<br>
		Kundennummer<br>
		Vorname und Nachname<br>
		Datum</p>
		
		<p>Um eine Rechnung zu finden, suchen Sie z.B. nach '<strong>#R</strong>070010'.<br>
		Lieferschein: '<strong>#L</strong>…'<br>
		Gutschein: <strong>'#G</strong>…'<br>
		Angebot: '<strong>#A</strong>…'<br>
		Bestätigung: '<strong>#B</strong>…'<br>
		Sie können in der Nummer ein Sternchen (*) als Platzhalter verwenden. '#R20000*' findet die Belege 'R200001', 'R200002' usw.</p>
		
		<p>Für eine Referenznummer beginnen Sie die Suche mit einem '?'. Also zum Beispiel '?300' findet den Beleg mit der Referenznummer 300.</p>";
		
		if(Session::isPluginLoaded("mProjekt"))
			echo "<p>Eine Projektnummer finden Sie mit vorangestelltem *.</p>";
		
		echo "<p>Die Positionen durchsuchen Sie mit vorangestelltem +.</p>";
		
		echo "<p>$B Nach Belegen ab einem Datum filtern Sie mit >. Zum Beispiel '>28.06.2017' findet alle Belege ab dem 28.06.2017.</p>";

		echo "<p>$B Nach Belegen bis zu einem Datum filtern Sie mit <. Zum Beispiel '<28.06.2017' findet alle Belege bis zum 28.06.2017.</p>";
		
		echo "<p>$B Nach Belegen ab einem Lieferdatum filtern Sie mit >L. Zum Beispiel '>L28.06.2017' findet alle Belege ab dem 28.06.2017.</p>";

		echo "<p>$B Nach Belegen bis zu einem Lieferdatum filtern Sie mit <L. Zum Beispiel '<L28.06.2017' findet alle Belege bis zum 28.06.2017.</p>";

		echo "<p>$B bedeutet, diese Suche funktioniert nur mit dem Filter.</p>";
		
		#echo "<p>$B Das Ergebnis der Filterung nach einem Suchbegriff weicht vom Ergebnis der Schnellsuche ab.";

	}
	
	public function getContextMenuHTML($identifier){
		Red::redirect(OnEvent::popup("Suchoptionen Aufträge", "Auftraege", "-1", "searchPopup"));
		#$ud = new mUserdata();
		#$d = $ud->getUDValueCached("auftraegeMinDate");
		#$d2 = $ud->getUDValueCached("auftraegeMaxDate");
		/*echo "
		<p style=\"padding:5px;\">
			Nur Einträge <strong>ab</strong> Datum: <input id=\"auftraegeMinDate\" value=\"$d\" type=\"text\" style=\"width:100px;\" /> 
			<input src=\"./images/i2/save.gif\" style=\"width:18px;border:0px;\" onclick=\"rme('mUserdata','','setUserdata',new Array('auftraegeMinDate',$('auftraegeMinDate').value),'showMessage(\'gespeichert\')');\" type=\"image\" />
			<input src=\"./images/i2/delete.gif\" style=\"width:18px;border:0px;\" onclick=\"rme('mUserdata','','delUserdata',new Array('auftraegeMinDate'),'showMessage(\'gelöscht\');$(\'auftraegeMinDate\').value = \'\';');\" type=\"image\" />
		</p>
		<p style=\"padding:5px;\">
			Nur Einträge <strong>bis</strong> Datum: <input id=\"auftraegeMaxDate\" value=\"$d2\" type=\"text\" style=\"width:100px;\" /> 
			<input src=\"./images/i2/save.gif\" style=\"width:18px;border:0px;\" onclick=\"rme('mUserdata','','setUserdata',new Array('auftraegeMaxDate',$('auftraegeMaxDate').value),'showMessage(\'gespeichert\')');\" type=\"image\" />
			<input src=\"./images/i2/delete.gif\" style=\"width:18px;border:0px;\" onclick=\"rme('mUserdata','','delUserdata',new Array('auftraegeMaxDate'),'showMessage(\'gelöscht\');$(\'auftraegeMaxDate\').value = \'\';');\" type=\"image\" />
		</p>*/
	}
	
	#public function getSearchedFields(){
	#	return array("firma", "CONCAT(vorname, ' ', nachname)", "kundennummer");
	#}
	
	public function saveContextMenu($identifier, $key){}

	public function createEmpty($addBeleg = null, $AdresseID = null){
		echo parent::createEmpty($addBeleg, $AdresseID);
	}
	
	public function searchFilterMulti(array $query){
		$fields = array("firma", "CONCAT(t2.vorname, ' ', t2.nachname)", "kundennummer");
		$onlyIDs = array();
		$grlbmjoin = false;
		$group = false;
		
		foreach($query AS $n => $K){
			if(strpos($K, "#") === 0){
				$type = mb_substr($K, 1, 1);
				$K = mb_substr($K, 2);
				
				$AC = anyC::get("GRLBM");
				$AC->addAssocV3("nummer", "LIKE", str_replace("*", "%", $K));
				
				if(strpos("RLGBMA", $type) !== false)
					$AC->addAssocV3("is$type", "=", "1");
				else
					$AC->addAssocV3("isWhat", "=", $type);
				
				$AC->setLimitV3(300);
				$AC->setFieldsV3(array("AuftragID"));
				
				while($G = $AC->n())
					$onlyIDs[] = $G->A("AuftragID");
				
				continue;
			}
			
			if(strpos($K, "+") === 0){
				$K = mb_substr($K, 1);
				$AC = anyC::get("Posten");
				$AC->addJoinV3("GRLBM", "GRLBMID", "=", "GRLBMID");
				
				$AC->setLimitV3(300);
				$AC->setFieldsV3(array("AuftragID"));

				$AC->addAssocV3("name", "LIKE", "%$K%", "AND", "1");
				$AC->addAssocV3("beschreibung", "LIKE", "%$K%", "OR", "1");
				try {
					$c = new CustomizerPostenTextGUI();
					$AC->addAssocV3("PostenText", "LIKE", "%$K%", "OR", "1");
				} catch (Exception $ex) {

				}
				
				while($G = $AC->n())
					$onlyIDs[] = $G->A("AuftragID");
				
				continue;
			}
			
			if(($K * 1)."" == $K){
				$this->addAssocV3("kundennummer", "=", $K);
				
				continue;
			}
			
			if(strpos($K, ">") === 0){
				$s = 1;
				$field = "datum";
				if($K[1] == "L"){
					$s = 2;
					$field = "lieferDatum";
				}
				
				$D = Util::CLDateParser(mb_substr($K, $s), "store");
				if(!$grlbmjoin)
					$this->addJoinV3("GRLBM", "AuftragID", "=", "AuftragID");
				$this->addAssocV3($field, ">=", $D);
				
				$group = true;
				$grlbmjoin = true;
				continue;
			}
			
			if(strpos($K, "<") === 0){
				$s = 1;
				$field = "datum";
				if($K[1] == "L"){
					$s = 2;
					$field = "lieferDatum";
				}
				
				$D = Util::CLDateParser(mb_substr($K, $s), "store");
				if(!$grlbmjoin)
					$this->addJoinV3("GRLBM", "AuftragID", "=", "AuftragID");
				$this->addAssocV3($field, "<=", $D);
				
				$group = true;
				$grlbmjoin = true;
				continue;
			}
			
			foreach($fields as $k => $v)
				$this->addAssocV3("$v","LIKE",'%'.$K.'%',($k == 0 ? "AND" : "OR"),"sfm$n");
		}
		
		foreach($query AS $n => $K){
			
			
			/*if(strpos($K, "<") === 0){
				$D = Util::CLDateParser(mb_substr($K, 2), "store");
				
				$AC = anyC::get("GRLBM");
				$AC->addAssocV3("datum", "<", $D);
				
				$AC->setLimitV3(300);
				$AC->setFieldsV3(array("AuftragID"));
				
				while($G = $AC->n())
					$onlyIDs[] = $G->A("AuftragID");
				
				continue;
			}*/
		}
		
		if($group)
			$this->setGroupV3("t1.AuftragID");
		
		
		if(count($onlyIDs)){
			$onlyIDs = array_filter(array_unique($onlyIDs));
			$this->addAssocV3 ("t1.AuftragID", "IN", "(".  implode(",", $onlyIDs).")", "AND", "ext");
		}
	}
}
?>
