<?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 WAdresseGUI extends AdresseGUI {
	public $GUITabFactory;

	public function __construct($ID){
		parent::__construct($ID);
		#$this->setEchoIDOnNew(true);
		#$this->gui = new CRMHTMLGUI();
		$this->setParser("geb", "Util::CLDateParserE");
	}

	function getHTML($id){
		$this->loadMeOrEmpty();
		$bps = $this->getMyBPSData();
		$akquise = BPS::getProperty("mWAdresseGUI", "Akquise", false);
		BPS::unsetProperty("mWAdresseGUI", "AufgabeID");
				
		if($id * 1 == -1) {
			if(Session::isPluginLoaded("mAdressBuch")){
				$AB = BPS::getProperty("mWAdresseGUI", "AdressBuch", null);
				if($AB)
					$this->A->type = "AB$AB";
			}
			
			$id = $this->newMe(true, false);
			$this->forceReload();

			$pSpecAkquise = mUserdata::getPluginSpecificData("mAkquise");
			if(isset($pSpecAkquise["pluginSpecificCanSeeOnlyOwn"])){
				$F = new Factory("AkquiseLead");
				$F->sA("AkquiseLeadAdresseID", $id);
				$F->sA("AkquiseLeadUserID", Session::currentUser()->getID());
				
				$F->store();
			}
			/*try {
				$K = new Kunden();
				if($this->A->type == "default")
					$K->createKundeToAdresse($id,false);
			} catch(ClassNotFoundException $e) {}*/
		}

		$gui = new CRMHTMLGUI();

		$gui->object($this);
		$gui->type("anrede", "select", array("2" => "Herr", "1" => "Frau","3" => "keine/Firma","4" => "Familie"));
		$gui->type("geb", "date");
		$gui->type("gebRemMail", "hidden");
		$gui->type("gebRem", "hidden");
		$gui->type("bemerkung", "textarea");

		$countries = ISO3166::getCountries();
		$laender = array("" => "keine Angabe");
		foreach($countries AS $v)
			$laender[$v] = $v;
		
		$gui->type("land","select", $laender);
		
		$gui->label("ort","PLZ/Ort");
		$gui->label("strasse","Straße/Hausnr.");
		$gui->label("tel","Telefon");
		$gui->label("email","E-Mail");
		$gui->label("KategorieID","Kategorie");
		#$gui->label("plz","PLZ");
		#$gui->label("strasse","Straße");
		$gui->label("geb","Jahrestag");
		$gui->label("type","Adressbuch");

		$Tab = new HTMLTable(2);
		$Tab->setColWidth(1, 120);
		$Tab->setColClass(1, "");
		$Tab->setColClass(2, "");
		$Tab->addRow(array("Entscheider"));
		$Tab->addRowClass("backgroundColor2");
		$Tab->addRowColspan(1, 2);
		
		$L = "";
		if(!isset($bps["edit"]) AND $this->A("logo") != ""){
			$L = new Button("Logo", DBImageGUI::imageLink("Adresse", $this->getID(), "logo")."&_r=".  rand(0, 9999999), "icon");
			$L->style("float:right;max-height:90px;");
		}
		
		$gui->space("logo", "Logo", false, "<div>$L</div>");
		$gui->space("ansprechpartner", "Entscheider", false, $Tab);
		$gui->space("tel", "Kontakt", true);
		$gui->space("strasse", "Adresse");
		$gui->space("homepage", "Sonstiges");

		
		$gui->name("Adresse");

		$fields = array(
			"firma",
			"anrede",
			"vorname",
			"nachname",
			"strasse",
			#"nr",
			#"plz",
			"ort",
			"land");
		
		if(!isset($bps["edit"]) AND $this->A("logo") != "")
			$fields[] = "logo";
		
		
		if(!isset($bps["edit"]) AND Session::isPluginLoaded("mAnsprechpartner")){
			$fields[] = "ansprechpartner";
			$AC = Ansprechpartner::getAllAnsprechpartnerToAdresse($this->getID());
			$AC->addAssocV3("AnsprechpartnerIsDecisionMaker", "=", "1");
			while($A = $AC->getNextEntry()){
				$B = new Button("Ansprechpartner", "user", "iconicL");
				$B->style("float:left;margin-right:5px;");
				
				$html = "";
				$html .= $A->A("AnsprechpartnerVorname")." ".$A->A("AnsprechpartnerNachname");
				if($A->A("AnsprechpartnerPosition") != "")
					$html .= "<br /><small style=\"color:grey;\">".$A->A("AnsprechpartnerPosition")."</small>";
				
				
				
				$Tab->addRow(array($B.$html));
				$Tab->addRowColspan(1, 2);
				if($A->A("AnsprechpartnerTel") != ""){
						$B = AdresseGUI::getCallButton($A->A("AnsprechpartnerTel"), "telephone");
						$B->style("float:right;");
					$Tab->addLV("Telefon:", $B.$A->A("AnsprechpartnerTel"));
				}
				
				if($A->A("AnsprechpartnerEmail") != "")
					$Tab->addLV("E-Mail:", $A->A("AnsprechpartnerEmail"), "", $this);
				
				$Tab->addRow(array("&nbsp;"));
				
			}
			if($AC->numLoaded() == 0)
				$Tab->setTableStyle ("display:none;");
				
		}
		
		$fields[] = "tel";
		$fields[] = "fax";
		$fields[] = "mobil";
		$fields[] = "email";
		$fields[] = "homepage";
		$fields[] = "gebRem";
		$fields[] = "gebRemMail";
		$fields[] = "KategorieID";
		$fields[] = "geb";
		$fields[] = "bemerkung";
		
		
		if(!isset($bps["edit"]) AND Session::isPluginLoaded("mAdressBuch")) {
			$fields[] = "type";
			
			$gui->parser("type", "WAdresseGUI::parserType");
		}
		
		if(!isset($bps["edit"])){
			$gui->parser("tel", "parserTel");
			$gui->parser("mobil", "parserTel");
		}
		
		$gui->attributes($fields);

		
		if(Session::isPluginLoaded("mSprache")) {
			$gui->insertAttribute("after", "land", "AdresseSpracheID");
			$gui->label("AdresseSpracheID","Sprache (Land)");
			
			$AC = new mSprache();
			$sprachen = array_merge(array(0 => "keine Auswahl"), $AC->toArray("SpracheLandSprache"));
			$gui->type("AdresseSpracheID", "select", $sprachen);
		}
		
		$kat = new Kategorien();
		$kat->addAssocV3("type","=","1");
		$gui->type("KategorieID","select", $kat->getArrayWithKeysAndValues());

		$GUIF = $this->GUITabFactory = new GUITabFactory("WAdresse");

		
		$hidden = mUserdata::getHiddenPlugins();
		
		$tabs = array(
			"mTodo" => true,
			"Auftraege" => true,
			"mFile" => true,
			"mVertrag" => true,
			"mDokument" => true,
			"mTag" => true,
			"mAnsprechpartner" => true,
			"mKappendix" => true,
			"mHistorie" => true,
			"mProjekt" => true,
			"mAufgabe" => true,
			"mWVertrag" => true,
			"Analyse" => true
		);
		
		$tabs = Aspect::joinPoint("tabs", $this, __METHOD__, array($tabs), $tabs);
		
		if(!isset($bps["edit"]) AND $id != -1) {
			if($akquise){
				$from = BPS::getProperty("mWAdresseGUI", "from", "mAkquise");
				if($from != "none"){
				$B = $gui->addTopButton("Akquise\nbeenden", "stop");
				if($from == "mAkquise"){
					$B->loadPlugin("contentScreen", $from, "_mAkquiseGUI;akquiseScroll:1;akquiseLastEdit:$id;akquiseLastPage:".BPS::getProperty("mWAdresseGUI", "akquiseLastPage", false));
					$BC = clone $B;
					
					$gui->addToEvent("onDelete", $BC->getAction());
				}
				
				if($from == "mAufgabe" AND BPS::getProperty("mWAdresseGUI", "sub") == "mWVertrag")
					$B->loadPlugin("contentScreen", $from, "_AufgabeGUI;WVertragLastEdit:".BPS::getProperty("mWAdresseGUI", "subId"));
				
				if($from == "mAufgabe" AND BPS::getProperty("mWAdresseGUI", "sub") == "Aufgabe")
					$B->loadPlugin("contentScreen", $from, "_AufgabeGUI;mAufgabeLastEdit:".BPS::getProperty("mWAdresseGUI", "subId"));
				$B->id("buttonQuitAkquise");
				#print_r(BPS::getAllProperties("mWAdresseGUI"));
				}
			}
			
			if(Session::isPluginLoaded("mSync"))
				$gui->addTopButton(mSync::getButton("Adresse", $this->getID()));
			
			
			if($tabs["mTodo"] AND Session::isPluginLoaded("mTodo") AND Applications::activeApplication() == "lightCRM"){
				$Aufgaben = new mTodoGUI();
				$Aufgaben->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Aufgaben, " Termine", "./ubiquitous/Todo/Todo.png");
			}

			/*if(Session::isPluginLoaded("Auftraege")){
				$GRLBMS = new KundeGRLBMGUI();
				$GRLBMS->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($GRLBMS, "Belege", "rechnung");
			}*/
			
			if($tabs["Auftraege"] AND !isset($hidden["Auftraege"]) AND Session::isPluginLoaded("Auftraege")){
				$Auftraege = new AuftraegeCRMGUI(-1);
				$Auftraege->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Auftraege, "Aufträge", "edit");
			}

			if($tabs["mFile"] AND !isset($hidden["mFile"]) AND Session::isPluginLoaded("mFile")){
				$Files = new FileManagerGUI();
				$Files->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Files, "Dateien", "computer");
			}

			if($tabs["mVertrag"] AND !isset($hidden["mVertrag"]) AND Session::isPluginLoaded("mVertrag") AND Applications::activeApplication() == "lightCRM"){
				$Vertraege = new mVertragCRMGUI();
				$Vertraege->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Vertraege, "Verträge", "./open3A/Vertrag/vertrag.png");
			}

			if($tabs["mDokument"] AND Session::isPluginLoaded("mDokument")){
				$Dokumente = new mDokumentGUI();
				$Dokumente->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Dokumente, "Dokumente", "./images/navi/angebot.png");
			}

			if($tabs["mTag"] AND Session::isPluginLoaded("mTag") AND Applications::activeApplication() == "lightCRM"){
				$Tags = new mTagGUI();
				$Tags->setOwner("Adresse", $this->ID);
				$GUIF->addTab($Tags, "Tags", "./ubiquitous/Tag/Tag.png");
			}
			

			if($tabs["mAnsprechpartner"] AND Session::isPluginLoaded("mAnsprechpartner"))
				$GUIF->addCustomTab(OnEvent::popup("Ansprechpartner", "mAnsprechpartner", "-1", "getPopup", array("'Adresse'", $this->getID())), "Ansprechp.", "./ubiquitous/Ansprechpartner/Ansprechpartner.png");


			if($tabs["mKappendix"] AND Session::isPluginLoaded("mKappendix") AND Applications::activeApplication() == "lightCRM"){
				$Kappendix = new KappendixCRMGUI(-1);
				$Kappendix->setOwner("Adresse", $this->ID);
				$GUIF->addTab($Kappendix, "Kunde", "kunden");
			}
			

			if($tabs["mHistorie"] AND Session::isPluginLoaded("mHistorie") AND Applications::activeApplication() == "lightCRM"){
				$Historie = new mHistorieGUI();
				$Historie->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Historie, "Historie", "./lightCRM/Historie/Historie.png");
			}
			

			if($tabs["mProjekt"] AND Session::isPluginLoaded("mProjekt")){
				$Projekte = new mProjektCRMGUI();
				$Projekte->setOwner("Adresse", $this->ID);
				$GUIF->addTab($Projekte, "Projekte", "./lightCRM/Projekt/projekt32.png");
			}

			if($tabs["mAufgabe"] AND Session::isPluginLoaded("mAufgabe") AND Applications::activeApplication() == "lightCRM"){
				$Aufgaben = new mAufgabeCRMGUI();
				$Aufgaben->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Aufgaben, "Aufgaben", "./ubiquitous/Aufgaben/Aufgabe.png");
			}
			
			if($tabs["mWVertrag"] AND Session::isPluginLoaded("mWVertrag") AND Applications::activeApplication() == "lightCRM"){
				$Vertraege = new mWVertragGUI();
				$Vertraege->setOwner("Adresse", $this->ID);
				$GUIF->addTab($Vertraege, "Vertr. ext.", "./lightCRM/WVertrag/WVertrag.png");
			}
			
			if($tabs["Analyse"] AND Applications::activeApplication() == "lightCRM"){
				$Analyse = new WAdresseAnalyse();
				$Analyse->setOwner("Adresse", $this->ID);
				$GUIF->addTab($Analyse, "Analyse", "./lightCRM/WAdressen/analyse.png");
			}
			
			$akquisePopup = "";
			if(Session::isPluginLoaded("mAkquise") AND Applications::activeApplication() == "lightCRM"){
				$akquisePopup = Akquise::getWindowAction($this->getID(), BPS::getProperty("mWAdresseGUI", "AufgabeID", 0));
				$GUIF->addCustomTab($akquisePopup, "Akquise", "./lightCRM/Akquise/telephone.png");
			}

			if(Session::isPluginLoaded("mMail")){# AND !Session::isPluginLoaded("mHistorie")){
				$Mails = new mDBMailCRMGUI();
				$Mails->setOwner("WAdresse", $this->ID);
				$GUIF->addTab($Mails, "Mails", "./lightCRM/Mail/Mail.png");
			}

			$Notizen = new WAdresseCRMGUI($this->getID());
			$GUIF->addTab($Notizen, "Notizen", "editor");
		}
		
		Aspect::joinPoint("appendTab", $this, __METHOD__, array($GUIF));
		
		$ST = new HTMLSideTable("right");
		$js = "";
		if($akquise)
			$js .= $akquisePopup;
		
		if(!isset($bps["edit"])){
			$gui->type("bemerkung", "hidden");
			
			$gui->parser("firma", "WAdresseGUI::parserFirma");
			$gui->parser("email", "WAdresseGUI::parserEMail");
			$gui->removeAttribute("vorname");
			$gui->removeAttribute("nachname");
			$gui->removeAttribute("anrede");
			$gui->removeAttribute("strasse");
			$gui->parser("homepage", "WAdresseGUI::parserHomepage");
			#$gui->removeAttribute("nr");
			#$gui->removeAttribute("plz");
			$gui->removeAttribute("ort");
			$gui->removeAttribute("land");
			$gui->label("firma", "Adresse");
		} else {
			$gui->parser("strasse", "WAdresseGUI::parserStrasse2");
			$gui->parser("ort", "WAdresseGUI::parserOrt2");
			
			$ST->addRow(array("&nbsp;"));
			$ST->addCellID(1, "dubletten");
			
			
			$IIL = new HTMLInput("uploadLogo", "file");
			$IIL->onchange(OnEvent::rme($this, "processUpload", array("fileName", "'logo'"), OnEvent::rme($this, "getPic", array("'logo'", "1"), "function(t){ \$j('#picLogo').html(t.responseText); }")));

			$IIF = new HTMLInput("uploadFoto", "file");
			$IIF->onchange(OnEvent::rme($this, "processUpload", array("fileName", "'foto'"), OnEvent::rme($this, "getPic", array("'foto'", "1"), "function(t){ \$j('#picFoto').html(t.responseText); }")));


			$BL = new Button("Logo hochladen", "upload", "iconicG");
			$BL->onclick("\$j('#uploadLogo').toggle();");

			#$BF = new Button("Foto hochladen", "upload", "iconicG");
			#$BF->onclick("\$j('#uploadFoto').toggle();");

			#$pics = "<div class=\"sideTableRight\" style=\"float:right;margin-right:-350px;\">
			#	<div id=\"picLogo\">".$this->getPic("logo")."</div>$BL<div style=\"display:none;\" id=\"uploadLogo\">$IIL</div>
			#	<div id=\"picFoto\">".$this->getPic("foto")."</div>$BF<div style=\"display:none;\" id=\"uploadFoto\">$IIF</div>
			#</div>";
			
			$ST->addRow(array($this->getPic("logo")));
			$ST->addCellID(1, "picLogo");
			
			$ST->addRow(array("<label style=\"float:none;text-align:left;\">Logo hochladen:</label>".$IIL));
			
			$js = "\$j('[name=strasse], [name=nr], [name=plz]').keyup(function(){
				".OnEvent::rme(new mWAdresseGUI(-1), "checkDoubles", array("\$j('[name=strasse]').val()", "\$j('[name=nr]').val()", "\$j('[name=plz]').val()"), "function(t){ \$j('#dubletten').html(t.responseText); }")."
			})";
		}

		$gui->addToEvent("onDelete", "Popup.close('','notes');");

		#if(!isset($bps["edit"])) $JS = "<script type=\"text/javascript\">if(Overlay.getPageSize(true)[0] > 1124) $openWindow</script>";
		#else $JS = "<script type=\"text/javascript\">if($('notesDetails')) Popup.close('', 'notes');</script>";
		
		$gui->customize($this->customizer);
		
		return $ST.$gui->getEditHTML().($id != -1 ? $GUIF->buildTabBar() : "").OnEvent::script($js);
	}
	
	public static function parserTel($w){
		if(trim($w) == "")
			return "";
		$B = new Button("$w anrufen", "./images/i2/telephone.png", "icon");
		$B->style("float:right;");
		
		return "<a href=\"tel:$w\">".$B."</a>".$w;
	}
	
	public static function parserEMail($w, $l, $E){
		$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;");
		}
		
		if(trim($w) == "")
			$B = "";

		#$gui->addFieldButton("email", $B);
		
		if($E->A("emailInvalid") > 0)
			return "<a href=\"#\" onclick=\"".OnEvent::rme($E, "reactivate", "", OnEvent::reload("Left"))." return false;\" style=\"text-decoration:none;\" title=\"Diese E-Mail-Adresse wurde als ungültig markiert\"><span style=\"text-decoration:line-through;\">".$w."</span></a>";
		
		
		return $B.$w;
	}
	
	public static function parserHomepage($w, $l, $E){
		$B = new Button($w, "./images/i2/flowers.gif", "icon");
		$B->style("float:right;margin-left:4px;");
		if(trim($w) == "")
			return "";
		
		return "<a href=\"".(strpos($w, "http") === false ? "http://" : "")."$w\" target=\"_blank\">$B$w</a>";
	}
	
	public static function parserStrasse2($w, $l, $E){
		$I1 = new HTMLInput("strasse", "text", $w);
		$I1->style("width:195px;margin-right:10px;");
		
		$I2 = new HTMLInput("nr", "text", $E->A("nr"));
		$I2->style("width:50px;text-align:right;");
		
		return $I1.$I2;
	}

	public static function parserOrt2($w, $l, $E){
		$I1 = new HTMLInput("ort", "text", $w);
		$I1->style("width:195px;");
		
		$I2 = new HTMLInput("plz", "text", $E->A("plz"));
		$I2->style("width:50px;text-align:right;margin-right:10px;");
		
		return $I2.$I1;
	}

	public static function parserFirma($w, $E){
		return $E->getFormattedAddress();
	}
	
	public function getClearClass($mode = "default"){
		if($mode == "GUI")
			return "WAdresse";
	
		return parent::getClearClass();
	}

	public function ACLabel(){
		return $this->getShortAddress();
	}
	
	public function saveNote($note){
		$this->changeA("bemerkung", $note);

		$this->saveMe(true, true);
	}
	
	public static function parserType($w, $E){
		
		$I = new HTMLInput("type", "select", $w, mAdressBuchGUI::getABs(true));
		$I->style("font-size: 12px;border:0px;");
		$I->onchange(OnEvent::rme($E, "changeAB", array("this.value"), OnEvent::reload("Right")));
		
		return $I;
	}
	
	public function reactivate(){
		$this->changeA("emailInvalid", "0");
		$this->saveMe();
	}

	public function changeAB($newAB){
		/*if($newAB == "0")
			$value = "default";
		else
			$value = "AB$newAB";*/
		
		$this->changeA("type", $newAB);
		$this->saveMe(true, true);
	}
	
	/*public function deleteMe(){
		die("TEST");
	}*/
}
?>
