<?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 exportLexwareGUI extends exportDefault implements iExport, iGUIHTML2 {

	private $exportMode;

	public function __construct() {
		$this->lineEnding = "\r\n";
	}
	
	public function getApps(){
		return array("open3A", "openFiBu");
	}
	
	public function isDisabled() {
		$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
		if(isset($pSpecData["pluginSpecificCantCreateR"]))
			return true;
		
		return false;
	}
	
	public function getHTML($id){
		T::load(Util::getRootPath()."open3A/Export", "Exps");
		$T = new HTMLTable(1, $this->getLabel());

		$BKCSV = new Button("Kunden","export");
		$BKCSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "KCSVExport");

		$BRCSV = new Button("Belege","export");
		$BRCSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "RCSVExport");
		$BRCSV->style("float:right;");

		$T->addRow($BRCSV.$BKCSV);

		$ac = new anyC();
		$ac->setFieldsV3(array(
			"MONTH(DATE_ADD(FROM_UNIXTIME(0), INTERVAL datum SECOND)) AS monat",
			"YEAR(DATE_ADD(FROM_UNIXTIME(0), INTERVAL datum SECOND)) AS jahr"));
		$ac->setCollectionOf("GRLBM");
		$ac->addAssocV3("isR", "=", "1");
		$ac->addAssocV3("isG", "=", "1","OR");
		$ac->addGroupV3("CONCAT(YEAR(DATE_ADD(FROM_UNIXTIME(0), INTERVAL datum SECOND)), MONTH(DATE_ADD(FROM_UNIXTIME(0), INTERVAL datum SECOND)))");
		$ac->addOrderV3("datum","DESC");

		$v = mUserdata::getUDValueS("exportLexware", "all");

		$options = array();
		$options["all"] = T::_("alle");
		while($a = $ac->getNextEntry())
			$options[$a->A("jahr").($a->A("monat") < 10 ? "0" : "").$a->A("monat")] = Util::CLMonthName($a->A("monat"))." ".$a->A("jahr");
		$options["manual"] = T::_("Manuell");

		$fields = array("month", "start", "ende");
		#if(Session::isPluginLoaded("mMwSt"))
		$fields[] = "buchungssaetze";
		$fields[] = "extraBrutto";
		$fields[] = "extraUst";
		$fields[] = "UStK1";
		$fields[] = "UStK2";
		
		$F = new HTMLForm("lexEx", $fields, "Export-Einstellungen");
		
		$F->setLabel("month", "Zeitraum");
		$F->setLabel("buchungssaetze", "Buchungssätze");
		$F->setLabel("extraUst", "USt-Zeile");
		$F->setLabel("extraBrutto", "Brutto-Zeile");
		$F->setLabel("UStK1", "USt-Konto 1");
		$F->setLabel("UStK2", "USt-Konto 2");
		
		$F->setDescriptionField("buchungssaetze", "Exportiert die einzelnen Buchungssätze aufgeschlüsselt nach den Erlöskonten im Artikel");
		$F->setDescriptionField("extraUst", "Fügt eine eigene Zeile für die USt hinzu.");
		$F->setDescriptionField("extraBrutto", "Fügt eine eigene Zeile für die Bruttogesamtsumme hinzu.");
			
		$F->setType("month", "select", $v, $options);
		$F->setType("buchungssaetze", "checkbox", mUserdata::getUDValueS("exportLexwareBS", "0"));
		$F->setType("extraUst", "checkbox", mUserdata::getUDValueS("exportLexwareXUSt", "0"));
		$F->setType("extraBrutto", "checkbox", mUserdata::getUDValueS("exportLexwareXBrutto", "0"));
		$F->setType("start", "date", mUserdata::getUDValueS("exportLexwareStart", ""));
		$F->setType("ende", "date", mUserdata::getUDValueS("exportLexwareEnde", ""));
		$F->setType("UStK1", "parser", null, array("exportLexwareGUI::parserUSTK1"));
		$F->setType("UStK2", "parser", null, array("exportLexwareGUI::parserUSTK2"));
		
		$F->hideIf("extraUst", "=", "0", "onChange", array("UStK1", "UStK2"));
		$F->hideIf("buchungssaetze", "=", "0", "onChange", array("extraUst", "extraBrutto"));
		$F->hideIf("month", "!=", "manual", "onChange", array("start", "ende"));
		
		
		$F->setDescriptionField("start", "inklusive dem ausgewählten Tag");
		$F->setDescriptionField("ende", "inklusive dem ausgewählten Tag");
		
		$F->getTable()->addColStyle(1, "width:120px;");
		$F->addJSEvent("start", "onChange", "rmeP('exportLexware','','saveStart',this.value,'checkResponse(transport);')");
		$F->addJSEvent("ende", "onChange", "rmeP('exportLexware','','saveEnde',this.value,'checkResponse(transport);')");
		$F->addJSEvent("month", "onChange", "rmeP('exportLexware','','saveMonth',this.value,'checkResponse(transport);')");
		$F->addJSEvent("buchungssaetze", "onChange", "rmeP('exportLexware','','saveBuchungssaetze',this.checked ? '1' : '0','checkResponse(transport);')");
		$F->addJSEvent("extraUst", "onChange", "rmeP('exportLexware','','saveXUSt',this.checked ? '1' : '0','checkResponse(transport);')");
		$F->addJSEvent("extraBrutto", "onChange", "rmeP('exportLexware','','saveXBrutto',this.checked ? '1' : '0','checkResponse(transport);')");
		
		return $F.$T;
	}

	public static function parserUSTK1(){
		$IU = new HTMLInput("UStK1", "text", mUserdata::getUDValueS("exportLexwareUStK1", ""));
		$IU->style("text-align:right;width:70px;");
		$IU->activateMultiEdit("exportLexware", -1);
		
		$IK = new HTMLInput("UStK1K", "text", mUserdata::getUDValueS("exportLexwareUStK1K", ""));
		$IK->style("width:100px;");
		$IK->activateMultiEdit("exportLexware", -1);
		
		return "$IU %: Konto $IK";
	}
	
	public static function parserUSTK2(){
		$IU = new HTMLInput("UStK2", "text", mUserdata::getUDValueS("exportLexwareUStK2", ""));
		$IU->style("text-align:right;width:70px;");
		$IU->activateMultiEdit("exportLexware", -1);
		
		$IK = new HTMLInput("UStK2K", "text", mUserdata::getUDValueS("exportLexwareUStK2K", ""));
		$IK->style("width:100px;");
		$IK->activateMultiEdit("exportLexware", -1);
		
		return "$IU %: Konto $IK";
	}
	
	public function saveMultiEditField($field, $value){
		mUserdata::setUserdataS("exportLexware".$field, $value);
		Red::messageSaved();
	}
	
	public static function saveStart($start){
		mUserdata::setUserdataS("exportLexwareStart", $start);

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveEnde($ende){
		mUserdata::setUserdataS("exportLexwareEnde", $ende);

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveMonth($month){
		mUserdata::setUserdataS("exportLexware", $month);

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveBuchungssaetze($yesOrNo){
		mUserdata::setUserdataS("exportLexwareBS", $yesOrNo);

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveXUst($yesOrNo){
		mUserdata::setUserdataS("exportLexwareXUSt", $yesOrNo);

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveXBrutto($yesOrNo){
		mUserdata::setUserdataS("exportLexwareXBrutto", $yesOrNo);

		echo "message:'Einstellung gespeichert'";
	}

	public function getExportData($type, $start = null, $count = null, $CK1 = null){
		$this->exportMode = $type[0];

		$type[0] = " ";

		$type = trim($type);

		parent::getExportData($type, $start, $count, $CK1);
	}

	public function getLabel(){
		return "Lexware";
	}

	public function getExportCollection(){
		if($this->exportMode == "R" AND mUserdata::getUDValueS("exportLexwareBS", "0") == "1")# AND Session::isPluginLoaded("mMwSt"))
			$this->exportMode = "RBS";
		
		$v = mUserdata::getUDValueS("exportLexware", "all");
		
		if($v == "manual"){
			$start = mUserdata::getUDValueS("exportLexwareStart", "");
			if($start == "")
				die(Util::getBasicHTMLError ("Bitte geben Sie ein Start-Datum an.", "Lexware Export"));
			
			$ende = mUserdata::getUDValueS("exportLexwareEnde", "");
			if($ende == "")
				die(Util::getBasicHTMLError ("Bitte geben Sie ein End-Datum an.", "Lexware Export"));
			
			$start = Util::CLDateParser($start, "store");
			$ende = Util::CLDateParser($ende, "store");
		}
		
		switch($this->exportMode){
			case "K":
				$ac = new anyC();
				$ac->setCollectionOf("Adresse");
				$ac->addAssocV3("AuftragID", "=", "-1");
				#$ac->addAssocV3("firma", "!=", ""); //dont't know why i did that. removed 20140706
				$ac->addJoinV3("Kappendix", "AdresseID", "=","AdresseID");
				$ac->setFieldsV3(array(
					"kundennummer AS Kontonummer",
					"IF(firma = '', CONCAT(vorname, ' ', nachname), firma) AS Kontobezeichnung",
					"firma AS Firma",
					"strasse AS Strasse",
					"nr AS Hausnummer",
					"plz AS PLZ",
					"ort AS Ort",
					"land AS Land",
					"nachname AS Name",
					"vorname AS Vorname"));
				
				$ac->lCV3();
				
				if($ac->numLoaded() == 0)
					die(Util::getBasicHTMLError("Sie haben keine Adressen in Ihrer Datenbank.", "Export-Fehler"));
				
				$this->filename = "Kunden_".Util::CLFormatDate(time()).".txt";

			break;

			case "R":
				$this->filename = "Buchungsdaten_".Util::CLFormatDate(time()).".txt";
				
				

				$ac = new anyC();
				$ac->setCollectionOf("GRLBM");
				$ac->addAssocV3("isR", "=", "1","AND","1");
				$ac->addAssocV3("isG", "=", "1","OR","1");
				$ac->addJoinV3("Auftrag", "AuftragID","=","AuftragID");
				$ac->addJoinV3("Kappendix", "t2.kundennummer","=","kundennummer");
				$ac->addJoinV3("Adresse", "t3.AdresseID", "=", "AdresseID");
				
				if($v != "all") {
					$monat = substr($v, 4, 2);
					$jahr = substr($v, 0, 4);

					$DStart = new Datum(mktime(0, 1, 0, $monat, 1, $jahr));
					$DEnd = clone $DStart;
					$DEnd->setToMonthLast();

					#$ac->addAssocV3("MONTH(DATE_ADD(FROM_UNIXTIME(0), INTERVAL datum SECOND))", "=", substr($v, 4, 2), "AND", "2");
					#$ac->addAssocV3("YEAR(DATE_ADD(FROM_UNIXTIME(0), INTERVAL datum SECOND))", "=", substr($v, 0, 4), "AND", "2");
					$ac->addAssocV3("datum", ">=", $DStart->time(), "AND", "2");
					$ac->addAssocV3("datum", "<=", $DEnd->time(), "AND", "2");
					
					$this->filename = "Buchungsdaten_$monat.$jahr.txt";
				}

				$ac->setFieldsV3(array(
					"FROM_UNIXTIME(datum,'%d.%m.%Y') AS Belegdatum",
					"nummer AS Belegnummer",
					"IF(isR = '1', 'RA', 'GU') AS Buchungstext",
					"bruttobetrag AS Buchungsbetrag",
					"IF(isR = '1', IF(t2.kundennummer = '-2', '', t2.kundennummer), KappendixErloeskonto) AS Sollkonto",
					"IF(isR = '1', KappendixErloeskonto, IF(t2.kundennummer = '-2', '', t2.kundennummer)) AS Habenkonto",
					#"IF(isR = '1', t2.kundennummer, KappendixErloeskonto) AS Sollkonto",
					#"IF(isR = '1', KappendixErloeskonto, t2.kundennummer) AS Habenkonto",
					"'EUR' AS Waehrung",
					"CONCAT(vorname, ' ', nachname) AS Name",
					"email AS EMail"));
			break;
			
			case "RBS":
				$this->kontoUSt = array(
					Util::CLNumberParserZ(mUserdata::getUDValueS("exportLexwareUStK1", ""), "store") * 1 => mUserdata::getUDValueS("exportLexwareUStK1K", ""),
					Util::CLNumberParserZ(mUserdata::getUDValueS("exportLexwareUStK2", ""), "store") * 1 => mUserdata::getUDValueS("exportLexwareUStK2K", "")
				);
				
				$this->filename = "Buchungsdaten_".Util::CLFormatDate(time()).".txt";
				#$this->hidden[] = "steuern";
				$this->hidden[] = "BelegID";
				$this->hidden[] = "mwst";
				$this->hidden[] = "Bruttobetrag2";
				$this->hidden[] = "isG";
				
				$v = mUserdata::getUDValueS("exportLexware", "all");
				$this->ustline = $x = mUserdata::getUDValueS("exportLexwareXUSt", "0");
				$this->bruttoline = mUserdata::getUDValueS("exportLexwareXBrutto", "0");
				if(!$this->bruttoline)
					$this->hidden[] = "bruttobetrag";
				
				$ac = new anyC();
				$ac->setCollectionOf("GRLBM");
				$ac->addAssocV3("isR", "=", "1","AND","1");
				$ac->addAssocV3("isG", "=", "1","OR","1");
				$ac->addJoinV3("Auftrag", "AuftragID","=","AuftragID");
				$ac->addJoinV3("Kappendix", "t2.kundennummer","=","kundennummer");
				$ac->addJoinV3("Posten", "t1.GRLBMID", "=", "GRLBMID");
				$ac->addJoinV3("Adresse", "t3.AdresseID", "=", "AdresseID");
				$ac->addGroupV3("GRLBMID");
				$ac->addGroupV3("erloeskonto");
				#$ac->addOrderV3("GRLBMID");
				#$ac->addOrderV3("PostenID");
				if($v != "all") {
					if($v == "manual"){
						$DStart = new Datum($start);
						$DEnd = new Datum($ende);
						$monat = date("d_m_Y", $start);
						$jahr = date("d_m_Y", $ende);
					} else {
						$monat = substr($v, 4, 2);
						$jahr = substr($v, 0, 4);

						$DStart = new Datum(mktime(0, 1, 0, $monat, 1, $jahr));
						$DEnd = clone $DStart;
						$DEnd->setToMonthLast();
					}

					$ac->addAssocV3("datum", ">=", $DStart->time(), "AND", "2");
					$ac->addAssocV3("datum", "<=", $DEnd->time(), "AND", "2");
					
					$this->filename = "Buchungsdaten_$monat.$jahr.txt";
				}

				$ac->setFieldsV3(array(
					"FROM_UNIXTIME(datum,'%d.%m.%Y') AS Belegdatum",
					"nummer AS Belegnummer",
					"CONCAT(IF(isR = '1', 'RA', 'GU'), nummer) AS Buchungstext",
					"SUM(ROUND(t4.preis ".($x ? "" : "* (1 + (mwst / 100))")." * menge * ((100 - t1.rabatt) / 100) * ((100 - t4.rabatt) / 100), 2)) AS Buchungsbetrag",
					#"SUM(".($x ? "preis" : "bruttopreis")." * menge * ((100 - t1.rabatt) / 100) * ((100 - t4.rabatt) / 100)) AS Buchungsbetrag",
					"IF(isR = '1', IF(t2.kundennummer = '-2', '', t2.kundennummer), KappendixErloeskonto) AS Sollkonto",
					"erloeskonto AS Habenkonto",
					#"IF(isR = '1', t2.kundennummer, KappendixErloeskonto) AS Sollkonto",
					#"IF(isR = '1', KappendixErloeskonto, t2.kundennummer) AS Habenkonto",
					"'EUR' AS Waehrung",
					"isG",
					"IF(firma != '', firma, CONCAT(vorname, ' ', nachname)) AS Name",
					"email AS EMail",
					"bruttobetrag",
					"bruttobetrag AS Bruttobetrag2",
					#"SUM((bruttopreis - preis) * menge) AS steuern",
					"t1.GRLBMID AS BelegID",
					"mwst"));
			break;
		}
		
		return $ac;
	}

	protected function entryParser(PersistentObject $entry){
		$A = $entry->getA();
		
		if(isset($A->GRLBMID))
			unset($A->GRLBMID);

		$F = Util::getLangCurrencyFormat("de_DE");

		if(isset($A->Buchungsbetrag))
			$A->Buchungsbetrag = str_replace($F[5], "", Util::formatCurrency("de_DE", $A->Buchungsbetrag * ($A->isG ? -1 : 1)));
		
		#$this->bruttobetrag = $A->bruttobetrag;
		
		$A->bruttobetrag = "";
	}
	
	protected function parserAfter($T, $A) {
		if($this->currentI < $this->currentCollection->numLoaded() - 1)
			return "";
		
		#echo $this->currentI."\n";
		#echo $this->currentCollection->numLoaded()."\n";
		
		$this->parserBefore($T, $A, true);
	}
	
	private $bruttoline = "0";
	private $ustline = "0";
	private $kontoUSt = array();
	private $lastA = null;
	private $lastBID = null;
	#private $sumUSt = array();
	protected function parserBefore($T, $A, $force = false){
		if($this->exportMode != "RBS")
			return;
		
		$F = Util::getLangCurrencyFormat("de_DE");
		
		if($this->ustline)
			if(($this->lastBID !== null AND $this->lastBID != $A->BelegID) OR $force){
				$isG = $this->lastA->isG;
				foreach($this->hidden AS $h)
					unset($this->lastA->$h);

				$GRLBM = new GRLBM($this->lastBID);
				$D = $GRLBM->getSumOfPosten(true);


				foreach($D[7] AS $mwst => $betrag){
					$this->lastA->Habenkonto = isset($this->kontoUSt[$mwst * 1]) ? $this->kontoUSt[$mwst * 1] : "";
					$this->lastA->Buchungsbetrag =  str_replace($F[5], "", Util::formatCurrency("de_DE", $betrag * ($isG ? -1 : 1)));
					if($this->bruttoline)
						$this->lastA->bruttobetrag = "";
					$T->addRow($this->lastA);
				}
			}
		
		if($this->bruttoline AND $this->lastBID != $A->BelegID AND !$force){
			$newA = clone $A;
			$brutto = $A->Bruttobetrag2;
			foreach($this->hidden AS $h)
				unset($newA->$h);
			
			#$newA->Buchungstext = "Bruttobetrag";
			$newA->Habenkonto = "";
			$newA->Sollkonto = "";
			#$newA->Buchungsbetrag = "";
			#$newA->bruttobetrag = str_replace($F[5], "", Util::formatCurrency("de_DE", $this->bruttobetrag * 1));
			#$newA->Buchungsbetrag = str_replace($F[5], "", Util::formatCurrency("de_DE", $A->bruttobetrag * 1));
			
			$newA->Buchungsbetrag = str_replace($F[5], "", Util::formatCurrency("de_DE", 0));
			if($this->bruttoline)
				$newA->bruttobetrag = str_replace($F[5], "", Util::formatCurrency("de_DE", $brutto * ($A->isG ? -1 : 1)));
			
			$T->addRow($newA);
		}
		
		$this->lastA = $A;
		$this->lastBID = $A->BelegID;
		#$A->bruttobetrag = "";
	}
}
?>
