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

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

 *  lightCRM 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 mWAdresseGUI extends AdressenGUI implements iCategoryFilter {
	function __construct(){
		parent::__construct();
		
		$this->gui = new HTMLGUIX();
	}

	public function getCollectionOf(){
		return "WAdresse";
	}

	function getHTML($id, $page){
		$this->addJoinV3("Kappendix", "t1.AdresseID", "=", "AdresseID");
		$spec = mUserdata::getPluginSpecificData("Adressen");
		if(isset($spec["pluginSpecificCanUseProvision"]))
			$this->addAssocV3("KappendixProvisionUserID", "=", Session::currentUser()->getID());
		
		
		if(Session::isPluginLoaded("mAkquise")){
			$spec = mUserdata::getPluginSpecificData("mAkquise");
			$joined = false;
			$i = 0;
			if(isset($spec["pluginSpecificCanSeeOnlyOwn"])){
				$this->addJoinV3("AkquiseLead", "AdresseID", "=", "AkquiseLeadAdresseID");
				$joined = true;
				
				$this->addAssocV3("AkquiseLeadUserID", "=", Session::currentUser()->getID(), "AND", "10");
				$i++; //to force OR
			}
			
			
			foreach($spec AS $key => $value) 
				if(strstr($key, "pluginSpecificCanSeeFrom")){
					if(!$joined){
						$this->addJoinV3("AkquiseLead", "AdresseID", "=", "AkquiseLeadAdresseID");
						$joined = true;
					}
					$this->addAssocV3("AkquiseLeadUserID", "=", str_replace("pluginSpecificCanSeeFrom", "", $key), $i++ == 0 ? "AND" : "OR", "10");
				}
		}
		
		$bps = $this->getMyBPSData();
		if($bps != -1 AND isset($bps["tag"]) AND $bps["tag"] != ""){
			$this->addJoinV3("Tag", "AdresseID", "=", "TagOwnerClassID");
			$this->addJoinV3("Tag", "TagOwnerClass", "=", "Adresse");
			$this->addJoinV3("Tag", "TagName", "=", $bps["tag"]);
			$this->addGroupV3("t1.AdresseID");
			$this->addAssocV3("TagID", "IS NOT", "NULL");
		}
		
		$this->filterCategories();
		
		
		$ST = new HTMLSideTable("left");
		#$ST->setTableStyle("float:left;margin-left:-60px;width:50px;");
		
		
		if(Session::isPluginLoaded("mTag")){
			$AC = anyC::get("Tag", "TagOwnerClass", "Adresse");
			$AC->addGroupV3("TagName");
			$tags = array("" => "Kein Filter");
			while($T = $AC->n())
				$tags[$T->A("TagName")] = $T->A("TagName");
			
			$I = new HTMLInput("tagFilter", "select", isset($bps["tag"]) ? $bps["tag"] : "", $tags);
			$I->onchange(OnEvent::reload("Right", "_mWAdresseGUI;tag:'+this.value+'"));
			
			$ST->addRow("Tag-Filter:<br>".$I);
		}
		
		$letters = array();
		$AC1 = clone $this;
		$AC1->addGroupV3("substr(nachname,1,1)");
		$AC1->setFieldsV3(array("substr(nachname,1,1) AS letter"));
		
		while($A = $AC1->getNextEntry()){
			if($A->A("letter") == "")
				continue;
			
			$letters[strtoupper($A->A("letter"))] = true;
		}
		
		$AC2 = clone $this;
		$AC2->addGroupV3("substr(firma,1,1)");
		$AC2->setFieldsV3(array("substr(firma,1,1) AS letter"));
		
		while($A = $AC2->getNextEntry()){
			if($A->A("letter") == "")
				continue;
			
			$letters[strtoupper($A->A("letter"))] = true;
		}
		
		ksort($letters);
		$letters = Aspect::joinPoint("letters", $this, __METHOD__, $letters, $letters);
		
		$letterFilter = "";
		
		foreach($letters AS $L => $n){
			$class = "";
			$click = OnEvent::reload("Right", "_mWAdresseGUI;letter:$L");
			if($bps != -1 AND $bps["letter"] == $L){
				$class = "backgroundColor1";
				$click = OnEvent::reload("Right", "_mWAdresseGUI;letter:all");
			}
			$letterFilter .= "<div 
				onmouseover=\"\$j(this).addClass('backgroundColor2');\" 
				onmouseout=\"\$j(this).removeClass('backgroundColor2');\" 
				onclick=\"$click\"
				style=\"cursor:pointer;padding:4px;box-sizing:border-box;width:33.333%;text-align:center;display:inline-block;\"
				class=\"$class\"
			>
				$L
			</div>";
			
			/*$ST->addRow($L);
			$ST->addCellEvent(1, "mouseover", "\$j(this).addClass('backgroundColor2');");
			$ST->addCellEvent(1, "mouseout", "\$j(this).removeClass('backgroundColor2');");
			$ST->addCellStyle(1, "padding:4px;padding-left:7px;cursor:pointer;");
			
			if($bps != -1 AND $bps["letter"] == $L){
				$ST->addRowClass ("backgroundColor1");
				$ST->addCellEvent(1, "click", OnEvent::reload("Right", "_mWAdresseGUI;letter:all"));
			}
			else
				$ST->addCellEvent(1, "click", OnEvent::reload("Right", "_mWAdresseGUI;letter:$L"));*/
		}
		
		$ST->addRow($letterFilter);
		
		$buttons = "";
		$newWindow = new Button("Adressen in neuem Fenster öffnen", "new_window", "iconicL");
		$newWindow->style("margin-right:10px;");
		$newWindow->newSession("Adressen", Applications::activeApplication(), "mWAdresse", "Adressen");
		if(!Session::physion())
			$buttons .= $newWindow;
			#$ST->addRow($newWindow);
		
		if(Session::isPluginLoaded("mReminder")){
			$B = Reminder::getButton();
			$B->style("margin-right:10px;");
			#$ST->addRow($B);
			$buttons .= $B;
		}
		
		if($buttons)
			$ST->addRow($buttons);
		
		#$B = $ST->addButton("Neuer Anruf");
		#$B->popup("", "Neuer Anruf", "mWAdresse", "-1", "newCall", ["'+492103334710'", time()]);
		
		if($bps != -1 AND isset($bps["letter"]) AND $bps["letter"] != "all"){
			$this->addAssocV3("substr(firma, 1, 1)", "=", $bps["letter"], "AND", "letters");
			$this->addAssocV3("substr(firma, 1, 1)", "=", strtolower($bps["letter"]), "OR", "letters");
			$this->addAssocV3("substr(nachname, 1, 1)", "=", $bps["letter"], "OR", "letters");
			$this->addAssocV3("substr(nachname, 1, 1)", "=", strtolower($bps["letter"]), "OR", "letters");
		}
		
		$this->loadMultiPageMode($id, $page, 0);

		$gui = $this->gui = new HTMLGUIX($this);
		$gui->options(true, true, true, true);
		$gui->name("Adresse");

		$gui->attributes(array("firma"));
		$gui->activateFeature("reloadOnNew", $this);

		$gui->screenHeight();

		$gui->displayGroup("KategorieID", "mWAdresseGUI::DGParser2");

		$gui->parser("firma","mWAdresseGUI::firmaParser2");

		$tab = "";
		if(Session::isPluginLoaded("mAdressBuch") AND $id == -1)
			$tab = mAdressBuchGUI::getSelectionMenu($this, "contentRight", false, true);
		
		$gui->customize($this->customizer);
		$gui->prepend($ST.$tab);
		
		$js = "if(typeof Util.querySt('number') != 'undefined'){
			".OnEvent::rme(new mWAdresse(-1), "findByPhone", array("decodeURIComponent(Util.querySt('number'))"), "function(t){ if(t.responseText == '') return; var ex = t.responseText.split(':'); if(ex[0] != 'WAdresse') contentManager.loadPlugin('contentRight', 'm'+ex[0], '', ex[1], {single: false}); else contentManager.loadFrame('contentLeft',ex[0], ex[1], '0'); }")."
		};";
		
		$load = "";
		if(Session::physion() AND Session::isPluginLoaded("msipgate") AND Session::isPluginLoaded("mWebsocket")){
			$S = anyC::getFirst("Websocket", "WebsocketUseFor", "phim");
			
			$inst = Util::eK();
			#$inst = "343782f6ad6739c2238e10e3beb4623392f683991da4a19435835a96736bdc823e35fdf389210797";
			
			$load = '<script type="text/javascript" src="./plugins/Websocket/autobahn.min.js"></script>';
			
			$js .= "
		var connection = new autobahn.Connection({
			url: 'ws".($S->A("WebsocketSecure") ? "s" : "").'://'.$S->A("WebsocketServer").":".$S->A("WebsocketServerPort")."/',
			realm: '".$S->A("WebsocketRealm")."',
			authmethods: ['wampcra'],
			authid: 'client',
			onchallenge: function(session, method, extra){
				if (method === 'wampcra')
					return autobahn.auth_cra.sign('".$S->A("WebsocketToken")."', extra.challenge);
			}
		});

		connection.onopen = function (session, details) {
			//console.log(details);
			//console.log('connected!');
			
			function onevent(args) {
				var data = args[0];
				console.log(data);
				".OnEvent::popup("Neuer Anruf", "mWAdresse", "-1", "newCall", array("data.from", "data.time"))."
	
			}

			session.subscribe('it.furtmeier.".$inst.".phone', onevent);
		
		};

		connection.onclose = function(reason){
			
		}

		connection.open();";
			
		}
		
		return $gui->getBrowserHTML($id).$load.OnEvent::script($js);
	}
	
	public function newCall($rufnummer, $time){
		$target =  parent::findByPhone($rufnummer);
		if($target === null){
			echo "<p>Anruf von <em>$rufnummer</em><br>
				<span style=\"color:grey;\">Uhrzeit: ".Util::CLDateTimeParser($time)."</span></p>";
			echo "<p>Nummer nicht in Adressbuch gefunden!</p>";
			
			$found = false;
			
			foreach(get_headers("https://www.dasoertliche.de/?form_name=search_inv&page=5&context=4&action=43&ph=".urlencode($rufnummer)) AS $header){
				#echo "<pre>";
				#print_r($header);
				#echo "</pre>";
				if(stripos($header, "HTTP/1.1 200 OK") === false)
					continue;
				
				$found = "https://www.dasoertliche.de/?form_name=search_inv&page=5&context=4&action=43&ph=".urlencode($rufnummer);#"https:".trim(str_replace("Location:", "", $header));
			}
			#var_dump($found);
			if($found !== false){
				$data = file_get_contents($found);
				if(!$data)
					return;
				
				if(strpos($data, "wir konnten keine Treffer finden") !== false)
					echo "<p class=\"error\">Rückwärtssuche 'Das Örtliche':<br><strong>Kein Ergebnis!</strong></p>";
				
				$dom = new domDocument(); 
				$dom->loadHTML($data); 
				$dom->preserveWhiteSpace = false; 

				$box = $dom->getElementById('detail_box1'); 
				if($box){
					$name = $box->getElementsByTagName("h1");
				} else {
					$box = $dom->getElementById('entry_1'); 
					if($box)
						$name = $box->getElementsByTagName("a");
				}
				if($name)
					echo "<p class=\"confirm\">Rückwärtssuche 'Das Örtliche':<br><strong>".$name[0]->nodeValue."</strong></p>";
			} else {
				echo "<p class=\"error\">Rückwärtssuche 'Das Örtliche':<br><strong>Kein Ergebnis!</strong></p>";
			}
			
			$B = new Button("Fenster\nschließen", "stop");
			$B->onclick(OnEvent::closePopup("mWAdresse"));
			$B->style("float:right;margin:5px;");
			echo $B;
				
			return;
		}
		
		$ex = explode(":", $target);
		
		switch($ex[0]){
			case "Lieferant":
				$L = new Lieferant($ex[1]);
			break;
		
			case "WAdresse":
				$L = new WAdresse($ex[1]);
				
				echo "<p>Anruf von</p>
					<p class=\"prettySubtitle\" style=\"padding-left:5px;margin-left:0;\">".$L->getShortAddress()."</p>
				<p><span style=\"color:grey;\">Uhrzeit: ".Util::CLDateTimeParser($time)."</span></p>";
				
				if(Session::isPluginLoaded("mHistorie")){
					mHistorie::logCall($rufnummer, "in", "calling");
				}
				
				$B = new Button("Fenster\nschließen", "stop");
				$B->onclick(OnEvent::closePopup("mWAdresse"));
				$B->style("float:right;margin:5px;");
				$B->className("backgroundColor0");
				echo $B;
				
				$B = new Button("Adresse\nöffnen", "address");
				$B->doBefore(OnEvent::closePopup("mWAdresse")." %AFTER");
				$B->loadFrame("contentLeft", "WAdresse", $ex[1]);
				$B->style("margin:5px;");
				echo $B;
				
			break;
		}
	}
	
	public function findByKundennummer($cid){
		if(!Session::isPluginLoaded("mKappendix"))
			return;
		
		echo Kappendix::getAdresseIDToKundennummer($cid);
	}
	
	public function findByPhone($number){
		$r = parent::findByPhone($number);
		echo $r;
	}
	
	public static function firmaParser2($w, $E){
		$symbols = "";
		
		if(Session::isPluginLoaded("mSync")){
			$B = mSync::getSmallButton("Adresse", $E->getID());
			$B->style("float:right;margin-left:4px;");
			
			$symbols .= $B;
		}
		
		if($E->A("homepage") != "")	{
			$B = new Button($E->A("homepage"), "./images/i2/flowers.gif", "icon");
			$B->style("float:right;margin-left:4px;");
			$B->windowRme("Adressen", "-1", "openHP", $E->A("homepage"), "", "tab");
			
			$symbols .= $B;
		}
		
		if($E->A("mobil") != ""){
			$B = new Button($E->A("mobil"), "./images/i2/mobile.png", "icon");
			$B->style("float:right;margin-left:4px;");
			
			$symbols .= $B;
		}
		
		if($E->A("email") != ""){
			$B = new Button($E->A("email"), "./images/i2/email.png", "icon");
			$B->style("float:right;margin-left:4px;");
			$B->onclick("document.location.href='mailto:".$E->A("email")."';");
			
			if(Session::isPluginLoaded("mMail")){
				$B = Mail::writeMailButton($E);
				$B->style("float:right;margin-left:4px;");
			}
			
			$symbols .= $B;
		}
		
		if($E->A("fax") != ""){
			$B = new Button($E->A("fax"), "./images/i2/fax.png", "icon");
			$B->style("float:right;margin-left:4px;");
			$symbols .= $B;
		}
		
		if($E->A("tel") != ""){
			$B = new Button($E->A("tel"), "./images/i2/telephone.png", "icon");
			$B->style("float:right;margin-left:4px;");
			
			$symbols .= $B;
		}

		return $symbols
		.($w != "" ? stripslashes($w).(($E->A("nachname") != "" OR $E->A("vorname") != "") ? "<br /><small>".trim(trim($E->A("nachname").", ".$E->A("vorname")), ",")."</small>" : "") : trim(trim($E->A("nachname").", ".$E->A("vorname")), ","));
	}

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

	function getCategoryFieldName(){
		return "KategorieID";
	}
	
	public function getContextMenuHTML($identifier){
		echo "<p style=\"padding:5px;\">Es werden folgende Felder durchsucht:<br /><br />Kundennummer<br />Firma<br />Vorname<br />Nachname<br />Straße<br />Ort<br />E-Mail<br />Telefonnummer</p><p>Sie können Ihre Suchanfrage mit UND verknüpfen.<br />Also z.B. \"Firmenname UND Ort\"</p>";

	}
	
	public function getACHTML($attributeName, $query){
		$this->inAC = true;
		$gui = new HTMLGUI2();#$this->gui;
		
		switch($attributeName){
			/*case "TodoClassID":
				$this->setSearchStringV3($query);
				$this->setSearchFieldsV3(array("firma"));
				
				#$this->setFieldsV3(array("plz","ort"));
				$this->setLimitV3("10");
				$this->lCV3();

				$gui->setObject($this);
				$gui->setShowAttributes(array("firma"));
				echo $gui->getACHTMLBrowser();
			break;*/
			
			case "plz":
				$this->addAssocV3("plz","LIKE", $query."%");
				$this->addGroupV3("plz");
				$this->setFieldsV3(array("plz","ort"));
				$this->setLimitV3("10");
				$this->lCV3();

				$gui->setObject($this);
				$gui->setShowAttributes(array("plz","ort"));
				echo $gui->getACHTMLBrowser();
			break;
/*			case "quickSearchmWAdresse":
				$mode = "quickSearchLoadFrame";

				$this->setSearchStringV3($query);
				$this->setSearchFieldsV3($this->searchFields);
				$this->addJoinV3("Kappendix","AdresseID","=","AdresseID");
				$this->setLimitV3($this->searchLimit);
				$this->lCV3();
				
				$gui->setObject($this);
				$gui->setShowAttributes(array("kundennummer","firma"));

				$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","WAdresse");
				$gui->autoCheckSelectionMode(get_class($this));
				$gui->customize($this->customizer);
				echo $gui->getACHTMLBrowser($mode);
			break;*/
			case "quickSearchmWAdresse":
				
				foreach($this->searchFields AS $k => $v){
					if($v == "VornameNachname")
						$this->searchFields[$k] = "CONCAT(vorname, ' ', nachname)";
					if($v == "NachnameVorname")
						$this->searchFields[$k] = "CONCAT(nachname, ' ', vorname)";
				}
		
				$spec = mUserdata::getPluginSpecificData("mAkquise");
				if(isset($spec["pluginSpecificCanSeeOnlyOwn"])){
					$this->addJoinV3("AkquiseLead", "AdresseID", "=", "AkquiseLeadAdresseID");
					$this->addAssocV3("AkquiseLeadUserID", "=", Session::currentUser()->getID(), "AND", "10");
				}
		
				$mode = "quickSearchLoadFrame";
				if(is_numeric($query)){
					$AC = anyC::get("Kappendix", "kundennummer", $query);
					$i = 0;
					while($K = $AC->n())
						$this->addAssocV3("AdresseID", "=", $K->A("AdresseID"), $i++ == 0 ? "AND" : "OR");
					
					$this->addAssocV3("REPLACE(REPLACE(REPLACE(tel, ' ', ''), '/', ''), '-', '')", "LIKE", "%".str_replace(array(" ", "/", "-"), array("", "", ""), $query)."%", $i > 0 ? "OR" : "AND");
					Aspect::joinPoint("alterNumeric", $this, __METHOD__, array($this, $query));
				} else {
					unset($this->searchFields[array_search("kundennummer", $this->searchFields)]);
					$this->searchFields[] = "email";
					$this->setSearchStringV3($query);
					$this->setSearchFieldsV3($this->searchFields);
				}
				
				$this->setLimitV3($this->searchLimit);
				
				Aspect::joinPoint("query", $this, __METHOD__, array($attributeName, $query));
				
				$this->lCV3();

				if($this->numLoaded() > 0){
					$AC = anyC::get("Kappendix");
					while($A = $this->getNextEntry())
						$AC->addAssocV3("AdresseID", "=", $A->getID(), "OR");
					
					$this->resetPointer();
					
					$kundennummern = array();
					while($K = $AC->getNextEntry())
						$kundennummern[$K->A("AdresseID")] = $K->A("kundennummer");
					
					
					while($A = $this->getNextEntry()){
						if(!isset($kundennummern[$A->getID()]))
							continue;
						
						$A->changeA("kundennummer", $kundennummern[$A->getID()]);
					}
					
					$this->resetPointer();
				}
				
				$gui->setObject($this);
				$gui->setShowAttributes(array("kundennummer","firma"));
				
				$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","WAdresse");
				$gui->autoCheckSelectionMode(get_class($this));
				$gui->customize($this->customizer);
				echo "<div style=\"max-height:550px;overflow:auto;\">".$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", "=", "Adresse");
					$AC->addAssocV3("t2.AdresseID", "IS NOT", "NULL");
					$AC->setFieldsV3(array("AnsprechpartnerOwnerClassID"));
					$AC->setLimitV3(10);
					$AC->addJoinV3("Adresse", "AnsprechpartnerOwnerClassID", "=", "AdresseID");
					$AC->addJoinV3("Kappendix", "AnsprechpartnerOwnerClassID", "=", "AdresseID");
					$AC->setFieldsV3(array("t2.AdresseID", "kundennummer","firma", "AnsprechpartnerNachname AS nachname", "AnsprechpartnerVorname AS vorname", "ort", "plz", "strasse"));
					$AC->addGroupV3("t2.AdresseID");
					Aspect::joinPoint("alterAnsprechpartner", $this, __METHOD__, array($AC, $query));
					$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", "AdresseID");
				}
				echo "</div>";
			break;
		}
	}

	function getClearClass(){
		return "mWAdresse";
	}

	public static function doSomethingElse(){
		try {
			$k = new Kategorien();
			$k->addKategorie("Adressen","1");
		} catch (ClassNotFoundException $e){
			
		}
	}

	public static function DGParser2($w){
		if($w == 0)
			return "-";

		$k = new Kategorie($w);
		return $k->getA() != null ? $k->getA()->name : "Kategorie unbekannt";
	}
}
?>