<?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 AdresseGUI extends Adresse implements /*iFPDF, */iGUIHTML2 {
	
	protected $gui;
	
	public function __construct($ID){
		parent::__construct($ID);

		$this->gui = new HTMLGUIX($this);
	}
	
	function getHTML($id){
		T::load(__DIR__, "Adressen");
		
		$spec = mUserdata::getPluginSpecificData("Adressen");
		if(isset($spec["pluginSpecificCanUseProvision"]) AND Session::isPluginLoaded("Kunden")){
			$K = Kappendix::getKappendixToAdresse($this->getID());
			if($K AND $K->A("KappendixProvisionUserID") != Session::currentUser()->getID())
				Red::alertD ("Diese Adresse ist nicht Ihrem Benutzer zugeordnet!");
		}
				
		$forReload = "";
		
		BPS::unsetProperty("AdresseGUI", "AuftragID");
		BPS::unsetProperty("AdresseGUI", "displayMode");
		
		
		$this->loadMeOrEmpty();
		
		if($id * 1 == -1) {
			$this->A = $this->newAttributes();

			if(Session::isPluginLoaded("mAdressBuch")){
				$AB = BPS::getProperty("AdressenGUI", "AdressBuch", null);
				if($AB)
					$this->A->type = "AB$AB";
			}
			
			$id = $this->newMe(true, false);
			$this->forceReload();

			try {
				$K = new Kunden();
				#if($this->A("type") == "default") //Or else a lieferAdresse will get a Kundennummer
				$K->createKundeToAdresse($id,false);
			} catch(ClassNotFoundException $e) {}

			$forReload = "<script type=\"text/javascript\">lastLoadedLeft = $id; lastLoadedLeftPlugin = 'Adresse';</script>";

		}
		
		$OptTab = new HTMLSideTable("right");
		
		
		#$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); }")));
		
		
		#if($this->A("logo") != "")
		$OptTab->addRow($this->getPic("logo"));
		$OptTab->addCellID(1, "picLogo");
		#$OptTab->addRow($pics);
		
		#<div id=\"picFoto\">".$this->getPic("foto")."</div>$BF<div style=\"display:none;\" id=\"uploadFoto\">$IIF</div>
		
		
		if(Session::isPluginLoaded("Kunden")){
			$B = new Button("Kundendaten","kunden");
			$B->loadFrame("contentLeft", "Kunde", "-1", "0", "KundeGUI;AdresseID:{$this->getID()};action:Kappendix");
			
			$Nr = "";
			$K = Kappendix::getKappendixToAdresse($this->getID());
			if($K != null)
				$Nr = "<br><small style=\"color:grey;\">".T::_("Kundennr.").": ".$K->A("kundennummer")."</small>";
			
			$OptTab->addRow($B.$Nr);
		}
		
		if(Session::isPluginLoaded("mAdresseNiederlassung")){
			$B = new Button("Filialen","./open3A/Niederlassungen/AdresseNiederlassung.png");
			$B->popup("", "Filialen", "mAdresseNiederlassung", "-1", "getPopup", $this->getID(), "", "{position: 'left'}");
			if(AdresseNiederlassung::has($this->getID()))
				$B->className ("confirm");
			$OptTab->addRow($B);
		}
		
		if(Applications::activeApplication() == "open3A" OR Applications::activeApplication() == "lightAd"){
			if(($id == -1 OR $forReload != "") AND Session::isPluginLoaded("mImport")) {
				$OTBV = new Button("Schnell-\nImport","import");
				$OTBV->onclick("Import.openSchnellImportAdresse('Adresse importieren:');");
				$OTBV->id("ButtonAdresseSchnellImport");

				$OptTab->addRow($OTBV);

			}

			if($id != -1 AND Session::isPluginLoaded("Kundenpreise")){
				$ButtonKundenpreise = new Button("Kundenpreise","package");
				$ButtonKundenpreise->onclick("contentManager.loadFrame('contentLeft','Kunde', -1, 0, 'KundeGUI;AdresseID:$this->ID;action:Kundenpreise');");

				$K = Kappendix::getKappendixToAdresse($this->getID());
				if($K != null AND anyC::getFirst("Kundenpreis", "kundennummer", $K->A("kundennummer")))
					$ButtonKundenpreise->className("confirm");
				
				$OptTab->addRow($ButtonKundenpreise);
			}
		
			
			$B = $OptTab->addButton("Erweitert", "navigation");
			$B->popup("", "Erweitert", "Adresse", $this->getID(), "popupExtended", "", "", "{position: 'left'}");
			Aspect::joinPoint("erweitertButton", $this, __METHOD__, array($B));
			
			if(Session::isPluginLoaded("mHinweis"))
				$OptTab->addRow(Hinweis::getButton("Adresse", $this->getID()));
			
			if(Session::isPluginLoaded("mAnsprechpartner") OR Session::isPluginLoaded("mOSM")){
				$OptTab->addRow("");
				$OptTab->addCellStyle(1, "height:30px;");
			}
			
			if($id != -1 AND Session::isPluginLoaded("mAnsprechpartner"))
				$OptTab->addRow(Ansprechpartner::getButton("Adresse", $this->getID(), "{position: 'left'}"));
			
			if(Session::isPluginLoaded("mDokument"))
				$OptTab->addRow(Dokument::getButton("WAdresse", $this->getID()));
			
			if($id != -1 AND Session::isPluginLoaded("mKundenzugang"))
				$OptTab->addRow(Kundenzugang::getButton($this));
			
			
			if($id != -1 AND Session::isPluginLoaded("mOSM"))
				$OptTab->addRow(OpenLayers::getButton("Adresse", $this->getID()));
			
			if(Session::isPluginLoaded("mFile"))
				$OptTab->addRow(mFileGUI::getManagerButton("WAdresse", $this->getID(), false, "", null, true, "{position: 'left'}"));
			
		}
		
		#if(Session::isPluginLoaded("mklickTel"))
		#	$OptTab->addRow(klickTel::getButton($this->getID()));
		
		if(Session::isPluginLoaded("mNextcloudUser"))
			$OptTab->addRow (NextcloudUser::getButtonManager("Adresse", $this->getID()));

		$this->loadMeOrEmpty();

		$gui = $this->getGUI();
		
		Aspect::joinPoint("buttons", $this, __METHOD__, $OptTab);
		

		return $forReload.$OptTab.$gui->getEditHTML();
	}
	
	/**
	 * @return HTMLGUIX
	 */
	public function getGUI($reduced = false, $includeKappendix = false){
		$gui = $this->gui;
		$gui->formID("AdresseForm");

		$fields = array(
			"firma",
			"anrede",
			"vorname",
			"nachname",
			"AdresseSpracheID",
			"strasse",
			"ort",
			"land",
			"tel",
			"fax",
			"mobil",
			"email",
			"lieferantennr",
			"homepage",
			"gebRem",
			"gebRemMail",
			"AuftragID",
			"KategorieID",
			"type",
			"geb",
			"bemerkung");
		
		if($reduced)
			$fields = array(
			"firma",
			"anrede",
			"vorname",
			"nachname",
			"AdresseSpracheID",
			"strasse",
			"ort",
			"land",
			"tel",
			"email",
			"KategorieID");
		
		if($includeKappendix){
			$K = Kappendix::getKappendixToAdresse($this->getID());
			if($K){
				$fields[] = "KappendixIBAN";
				$fields[] = "KappendixSWIFTBIC";
			
				$this->changeA("KappendixIBAN", $K->A("KappendixIBAN"));
				$this->changeA("KappendixSWIFTBIC", $K->A("KappendixSWIFTBIC"));
			}
			
		}
		
		$gui->attributes($fields);
		
		#$gui->setObject($this);
		$gui->name("Adresse");
		
		#$gui->setOptions("anrede", array_keys(self::getAnreden()), array_values(self::getAnreden()));
		$gui->type("anrede", "select", self::getAnreden());

		$gui->space("tel", "Kontakt");
		$gui->space("strasse", "Adresse");
		$gui->space("lieferantennr", "Sonstiges");
		$gui->space("KappendixIBAN", "Kundendaten");
		
		$gui->descriptionField("exportToLDAP", "Soll die Adresse auf einen LDAP-Server exportiert werden?");
		$gui->descriptionField("lieferantennr", "Ihre Lieferantennummer bei diesem Kunden. Wird auf den Belegen angezeigt.");
		if($includeKappendix AND $K){
			$BIBAN = new Button("IBAN-Prüfung", "./images/i2/".($K->checkIBAN($this->A("KappendixIBAN")) ? "okCatch" : "note").".png", "icon");
			$BIBAN->id("IBANCheck");
			if(trim($this->A("KappendixIBAN")) == "")
				$BIBAN->image("./images/i2/empty.png");
			$gui->addFieldButton("KappendixIBAN", $BIBAN);
			
			$gui->addFieldEvent("KappendixIBAN", "onkeyup", "if(this.value == '') { \$j('#IBANCheck').css('display', 'none'); return; } ".OnEvent::rme($K, "findBIC", array("\$j(this).val()"), "function(t){ if(t.responseText == '') return; \$j('[name=KappendixSWIFTBIC]').val(t.responseText).trigger('change'); }").OnEvent::rme($K, "checkIBAN", array("this.value"), "function(t){ \$j('#IBANCheck').css('display', ''); if(t.responseText == '1') \$j('#IBANCheck').prop('src', './images/i2/okCatch.png'); else \$j('#IBANCheck').prop('src', './images/i2/note.png'); }"));
		}
		
		$gui->type("geb","hidden");
		$gui->type("gebRemMail","hidden");
		$gui->type("gebRem","hidden");
		$gui->type("exportToLDAP","checkbox");
		$gui->type("AuftragID","hidden");
		$gui->type("type","hidden");
		if(Session::isPluginLoaded("mAdressBuch")){
			$gui->type("type","select", mAdressBuchGUI::getABs(true));
		}
		$gui->type("bemerkung","textarea");

		$gui->label("type", "Adressbuch");
		$gui->label("firma", "Firma");
		$gui->label("anrede", "Anrede");
		$gui->label("vorname", "Vorname");
		$gui->label("nachname", "Nachname");
		$gui->label("fax", "Fax");
		$gui->label("mobil", "Mobil");
		$gui->label("bemerkung", "Notizen");
		$gui->label("ort","PLZ/Ort");
		$gui->label("strasse","Straße/Hausnr.");
		$gui->label("tel","Telefon");
		$gui->label("email","E-Mail");
		$gui->label("exportToLDAP","LDAP-Export?");
		$gui->label("lieferantennr", "Lieferantennr.");
		$gui->label("homepage", "Homepage");
		$gui->label("KappendixSWIFTBIC","BIC");
		$gui->label("KappendixIBAN","IBAN");
		
		$gui->parser("strasse", "AdresseGUI::parserStrasse");#, array($this->A("nr")));
		$gui->parser("ort", "AdresseGUI::parserOrt");#, array($this->A("plz")));
		
		
		if(Session::isPluginLoaded("Kategorien")){
			$kat = new Kategorien();
			$kat->addAssocV3("type","=","1");
			$gui->type("KategorieID", "select", $kat->getArrayWithKeysAndValues(T::_("bitte auswählen")));
			
			$gui->label("KategorieID","Kategorie");
		} else
			$gui->type("KategorieID","hidden");
		
		
		if(Session::isPluginLoaded("mSprache")) {
			$gui->label("AdresseSpracheID","Sprache");
			$gui->descriptionField("AdresseSpracheID", "und Währung");
			$gui->type("AdresseSpracheID", "select", new mSprache(), "SpracheName", "Bitte auswählen...");

			$gui->activateFeature("addSaveDefaultButton", $this, "AdresseSpracheID");
		} else
			$gui->type("AdresseSpracheID","hidden");
		
		
		if(Session::isPluginLoaded("mStammdaten") OR Applications::activeApplication() == "MMDB"){
			$countries = ISO3166::getCountriesDE();
			$countries2 = ISO3166::getCountries();
			
			$c = array("" => T::_("keine Angabe"));
			foreach($countries2 AS $k => $v)
				$c[$countries[$k]] = $v;

			$gui->label("land", "Land");
			$gui->type("land","select", $c);
		}

		
		#if(Session::isPluginLoaded("mTelefonanlage")){
		#	$gui->addFieldButton("tel", Telefonanlage::getCallButton("\$j('input[name=tel]').val()", "telephone", true));
		#	$gui->addFieldButton("mobil", Telefonanlage::getCallButton("\$j('input[name=mobil]').val()", "telephone", true));
		#} else {
		$gui->addFieldButton("tel", self::getCallButton("\$j('input[name=tel]').val()", "telephone", true));
		$gui->addFieldButton("mobil", self::getCallButton("\$j('input[name=mobil]').val()", "mobile", true));
		#}
		#$gui->optionsEdit(false, false);
		$gui->customize($this->customizer);
		
		return $gui;
	}
	
	public static function getCallButton($number, $icon = "telephone", $isJS = false){
		$B = new Button("Diese Nummer wählen", "./images/i2/$icon.png", "icon");
		if($isJS)
			$B->onclick("document.location.href='tel:'+$number;");
		else
			$B->onclick("document.location.href='tel:$number';");
		return $B;
	}
	
	public function findOrt($plz){
		try {
			$uri = "https://soapi.io/soap/plz";
			$S = new SoapClient(null, array("location" => $uri,"uri" => $uri));
			$r = $S->requestOrtByPLZ($plz);
			if(!isset($r[0]))
				return;

			echo $r[0]["ort"];
		} catch (Exception $e){
			
		}
	}
	
	public function getPic($target, $echo = false){
		$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); }")));
		
		$BL = new Button("Logo hochladen", "upload", "iconicG");
		$BL->onclick("\$j('#uploadLogo').toggle();");
		$pics = "$BL<div style=\"display:none;\" id=\"uploadLogo\">$IIL</div>";
		
		if($this->A($target) == ""){
			if(Applications::activeApplication() != "lightAd")
				return "";
			
			if($echo)
				echo $pics;
			
			return $pics;
		}
		
		$B = new Button("Bild löschen", "trash_stroke", "iconic");
		$B->style("position:absolute;z-index:10;");
		$B->rmePCR("Adresse", $this->getID(), "removeLogo", "", OnEvent::rme($this, "getPic", array("'logo'", "1"), "function(t){ \$j('#picLogo').html(t.responseText); }"));
		
		$Image = new Button("", DBImageGUI::imageLink("Adresse", $this->getID(), $target, false, true), "icon");
		$Image->style("max-width:150px;");
		
		if($echo)
			echo $B.$Image.$pics;
		
		return $B.$Image.$pics;
	}
	
	public function removeLogo(){
		$this->changeA("logo", "");
		$this->saveMe();
	}
	
	public function processUpload($fileName, $target = false){
		$ex = Util::ext($fileName);
		
		if($ex != "jpg" AND $ex != "jpeg" AND $ex != "png")
			Red::alertD("Bildtyp unbekannt. Bitte verwenden Sie jpg oder png-Dateien.");
		
		$tempDir = Util::getTempDir();
		
		
		$imgPath = $tempDir."/".$fileName.".tmp";
		
		$this->changeA($target, DBImageGUI::stringifyS("png", $imgPath, 250));
		$this->saveMe(true, false, false);
		
		unlink($imgPath);
		
		return true;
	}
	
	function popupExtended(){
		T::load(__DIR__, "Adressen");
		echo "<p id=\"currentAddress\">".$this->getHTMLFormattedAddress()."</p>";
		$fields = array(
			"abteilung",
			"titelPrefix",
			"titelSuffix");
		$fields[] = "position";
		
		if(
			$this->A("land") == ISO3166::getCountryToCode("GB") 
			OR $this->A("land") == ISO3166::getCountryToCode("US") 
			OR $this->A("land") == ISO3166::getCountryToCode("CH")){
			$fields[] = "zusatz1";
		}
		
		if($this->A("land") == ISO3166::getCountryToCode("DK") OR $this->A("land") == ISO3166::getCountryToCode("ES")){
			$fields[] = "bezirk";
		}
		if(
			$this->A("land") == ISO3166::getCountryToCode("DE") 
			OR $this->A("land") == ISO3166::getCountryToCode("FR")
			OR $this->A("land") == ISO3166::getCountryToCode("GB")
			OR $this->A("land") == ISO3166::getCountryToCode("US") )
			$fields[] = "zusatz2";
		
		
		$F = new HTMLForm("extended", $fields);
		
		#if($this->A("land") != ISO3166::getCountryToCode("GB") AND $this->A("land") != ISO3166::getCountryToCode("US") AND $this->A("land") != ISO3166::getCountryToCode("CH")) {
		#	$gui->setLineStyle("zusatz1", "display:none;");
		#	$gui->setLineStyle("position", "display:none;");
		#}

		#if($this->A("land") != ISO3166::getCountryToCode("DK") AND $this->A("land") != ISO3166::getCountryToCode("ES"))
		#	$gui->setLineStyle("bezirk", "display:none;");

		foreach ($fields AS $field){
			$F->addJSEvent($field, "onkeyup", OnEvent::rme($this, "buildPreview", array("JSON.stringify(contentManager.formContent('extended'))"), "function(t){ \$j('#currentAddress').html(t.responseText); }"));
		}
			
		$F->getTable()->setColWidth(1, 120);
		
		$F->setValues($this);
		
		$F->insertSpaceAbove("abteilung", "Firma");
		$F->insertSpaceAbove("titelPrefix", "Person");
		$F->insertSpaceAbove("zusatz1", "Anschrift");
		if(!in_array("zusatz1", $fields) AND in_array("zusatz2", $fields))
			$F->insertSpaceAbove("zusatz2", "Anschrift");
		
		$F->setLabel("zusatz1", "Zusatz");
		$F->setLabel("zusatz2", "Zusatz");
		$F->setDescriptionField("zusatz1", "Wird in der Adresse unterhalb des Namens der Person angezeigt");
		$F->setDescriptionField("zusatz2", "Wird in der Adresse unterhalb der Straße angezeigt");
		$F->setDescriptionField("abteilung", "Wird in der Adresse unterhalb des Firmennamens angezeigt");
		
		$F->setLabel("titelPrefix","Titel Präfix");
		$F->setLabel("titelSuffix","Titel Suffix");
		
		$F->setSaveClass("Adresse", $this->getID(), "function(){ ".OnEvent::closePopup("Adresse")." }");
		$F->useRecentlyChanged();
		
		echo $F;
	}
	
	public function buildPreview($data){
		$json = json_decode($data);
		foreach($json AS $field)
			$this->changeA($field->name, $field->value);
		
		
		echo $this->getHTMLFormattedAddress();
	}

	public static function parserStrasse($w, $l, $p, $GUI){
		$I1 = new HTMLInput("strasse", "text", $w);
		$I1->style("width:185px;margin-right:10px;");
		$I1->id("strasse");
		
		if(is_object($p)){
			if($p instanceof AkquiseGUI)
				$I1->style("width:170px;margin-right:10px;");
			
			$p = $p->A("nr");
		}
		
		$I2 = new HTMLInput("nr", "text", $p);
		$I2->style("width:50px;text-align:right;");
		$I2->id("nr");
		
		if($GUI AND !$GUI->showInputs())
			return $w." ".$p;
		
		return $I1.$I2;
	}

	public static function parserOrt($w, $l, $p, $GUI){

		$I1 = new HTMLInput("ort", "text", $w);
		$I1->style("width:185px;");
		$I1->id("ort");
		$oldp = null;
		if(is_object($p)){
			if($p instanceof AkquiseGUI)
				$I1->style("width:170px;");
			
			$oldp = $p;
			$p = $p->A("plz");
		}
		
		$I2 = new HTMLInput("plz", "text", $p);
		$I2->style("width:50px;text-align:right;margin-right:10px;");
		$I2->id("plz");
		#$gui->setInputJSEvent("plz", "onkeyup", "if(this.value == '') { return; } ".OnEvent::rme($this, "findOrt", array("\$j(this).val()"), "function(t){ if(t.responseText == '') return; \$j('[name=ort]').val(t.responseText).trigger('change'); }"));
		if(is_object($oldp))
			$I2->onkeyup("if(this.value == '') { return; } ".OnEvent::rme(new AdresseGUI(-1), "findOrt", array("\$j(this).val()"), "function(t){ if(t.responseText == '') return; \$j('[name=ort]').val(t.responseText).trigger('change'); }"));
		
		if($GUI AND !$GUI->showInputs())
			return $p." ".$w;
					
		return $I2.$I1;
	}
	
	public function saveMe($checkUserData = true, $output = false, $deleteBPS = true){
		if($deleteBPS){
			$_SESSION["BPS"]->setActualClass(get_class($this));
			$_SESSION["BPS"]->unsetACProperty("edit");
		}
			
		parent::saveMe($checkUserData, $output);
	}
	
	/*public function getXML(){
		$xml = parent::getXML();
		$lines = explode("\n",$xml);
		foreach($lines as $k => $v)
			$lines[$k] = str_pad(($k + 1),5, " ", STR_PAD_LEFT).": ";
			
		echo Util::getBasicHTML("<pre class=\"backgroundColor2\" style=\"font-size:9px;float:left;\">".implode("\n",$lines)."</pre><pre class=\"backgroundColor0\" style=\"font-size:9px;margin-left:40px;\">".htmlentities(utf8_decode($xml))."</pre>","XML-Export");
	}*/

        #EE ab hier
    public static function testAusgabe($p1, $p2){
		Red::alertD("IDNr1: $p1; IDNr2: $p2");
	}
	
	public function getHTMLFormattedAddress($echo = false) {
		$A = parent::getHTMLFormattedAddress();
		
		if($echo)
			echo $A;
		
		return $A;
	}
	
	public function ACLabel(){
		return $this->getShortAddress();
	}
}
?>
