<?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 exportDatevGUI extends exportDefault implements iExport, iGUIHTML2 {
	private $exportMode;
	private $exportFile = "Belege";
	
	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("Rechnungen","export");
		$BRCSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "RCSVExport");
		$BRCSV->style("float:right;");
		
		$BGCSV = new Button("Gutschriften","export");
		$BGCSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "GCSVExport");
		
		$BTCSV = new Button("Stornorechnungen","export");
		$BTCSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "TCSVExport");
		$BTCSV->style("float:right;");
		$A = new Auftrag(-1); //for Customizers to load!
		if(!in_array("T", Auftrag::getBelegArten()))
			$BTCSV = "";
		
		
		$BKCSV = new Button("Kunden","export");
		$BKCSV->windowRme("exportAdressen", "", "getExportData", "CSVExport");

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

		$BACSV = new Button("Alle Ausgangs-\nbelegarten","export");
		$BACSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "ACSVExport");
		#$BACSV->style("float:right;");
		$T->addRow($BACSV);
		
		
		if(Session::isPluginLoaded("mEingangsbeleg")){
			
			$BECSV = new Button("Eingangs-\nrechnungen","export");
			$BECSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "ECSVExport");
			$BECSV->style("float:right;");

			$T->addRow($BECSV);
		}
		
		if(Session::isPluginLoaded("mKassenbuch")){
			
			$BECSV = new Button("Kassenbuch","export");
			$BECSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", "KCSVExport");
			$BECSV->style("float:right;");

			$T->addRow($BECSV);
		}
		
		$T2 = new HTMLTable(1, "Datev Kanzlei-ReWe");
		
		$B = new Button("Rechnungen","export");
		$B->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", array("'RCSVExport'", 0, 0, 1));
		$B->style("float:right;");
		
		$BG = new Button("Gutschriften","export");
		$BG->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", array("'GCSVExport'", 0, 0, 1));

		$T2->addRow($BG.$B);
		
		$BTCSV = new Button("Stornorechnungen","export");
		$BTCSV->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", array("'TCSVExport'", 0, 0, 1));
		
		if(in_array("T", Auftrag::getBelegArten()))
			$T2->addRow($BTCSV);
		
		$T3 = new HTMLTable(1, "Datev Online XML (EXPERIMENTELL!)");
		
		$B = new Button("ZIP","export");
		$B->windowRme(str_replace("GUI", "",get_class($this)), "", "getExportData", array("'RCSVExport'", 0, 0, 2));
		$B->style("float:right;");
		$T3->addRow($B);
		
		$ac = new anyC();
		$ac->setFieldsV3(array(
			"MONTH(FROM_UNIXTIME(datum)) AS monat",
			"YEAR(FROM_UNIXTIME(datum)) AS jahr"));
		$ac->setCollectionOf("GRLBM");
		$ac->addAssocV3("isR", "=", "1");
		$ac->addAssocV3("isG", "=", "1","OR");
		$ac->addAssocV3("isWhat", "=", "T","OR");
		$ac->addGroupV3("CONCAT(YEAR(FROM_UNIXTIME(datum)), MONTH(FROM_UNIXTIME(datum)))");
		$ac->addOrderV3("datum","DESC");

		$v = mUserdata::getUDValueS("exportDatev", "all");
		$datum = mUserdata::getUDValueS("exportDatevStichtag", "datum");

		$options = array();
		$options["all"] = T::_("alle");
		$options["last"] = T::_("Seit letztem Export");
		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");
		$fields[] = "start";
		$fields[] = "ende";
		
		if(Session::isPluginLoaded("Uebersicht"))
			$fields[] = "stichtag";
		
		$fields[] = "buchungssaetze";
		$fields[] = "defaultErloes";
		$fields[] = "defaultKundenkonto";
		$fields[] = "profil";
		
		$F = new HTMLForm("lexEx", $fields, "Export-Einstellungen");
		$F->setLabel("month", "Zeitraum");
		if(Session::isPluginLoaded("Uebersicht")){
			#$F->setLabel("month", "Zahlungseingang");
			$F->setType("stichtag", "select", $datum,  array("datum" => T::_("Belegdatum"), "GRLBMpayedDate" => T::_("Zahlungseingang")));
			$F->addJSEvent("stichtag", "onChange", "contentManager.rmePCR('exportDatev','','saveDate',this.value)");
		}
		
		$F->setType("buchungssaetze", "checkbox", mUserdata::getUDValueS("exportDatevBS", "0"));
		$F->setType("start", "date", mUserdata::getUDValueS("exportDatevStart", ""));
		$F->setType("ende", "date", mUserdata::getUDValueS("exportDatevEnde", ""));
		$F->setType("defaultErloes", "text", mUserdata::getUDValueS("exportDatevDefaultErloes", "0"));
		$F->setType("defaultKundenkonto", "text", mUserdata::getGlobalSettingValue("DVKappendixErloeskonto", "8400"));
		$F->setType("profil", "select", mUserdata::getGlobalSettingValue("exportDatevProfil", ""), ["" => "Standard", "RHVFibu" => "RHVFibu"]);
		
		$F->setDescriptionField("buchungssaetze", "Exportiert die einzelnen Buchungssätze aufgeschlüsselt nach den Erlöskonten im Artikel");
		$F->setDescriptionField("start", "inklusive dem ausgewählten Tag");
		$F->setDescriptionField("ende", "inklusive dem ausgewählten Tag");
		$F->setDescriptionField("defaultErloes", "Dieses Erlöskonto wird verwendet, wenn beim Artikel nichts eingetragen ist.");
		$F->setDescriptionField("defaultKundenkonto", "Dieses Kundenkonto wird bei 1x-Adressen und neuen Kunden verwendet.");
		
		$F->setLabel("buchungssaetze", "Buchungssätze");
		$F->setLabel("dateStart", "Datum Start");
		$F->setLabel("dateEnd", "Datum Ende");
		$F->setLabel("defaultErloes", "Standard Erlöskonto");
		$F->setLabel("defaultKundenkonto", "Standard Kundenkonto");
		
		$F->setType("month", "select", $v, $options);
		$F->getTable()->addColStyle(1, "width:120px;");
		
		#$F->hideIf("buchungssaetze", "=", "0", "onchange", array("defaultErloes", "defaultKundenkonto"));
		
		$F->addJSEvent("start", "onChange", "rmeP('exportDatev','','saveStart',this.value,'checkResponse(transport);')");
		$F->addJSEvent("ende", "onChange", "rmeP('exportDatev','','saveEnde',this.value,'checkResponse(transport);')");
		$F->addJSEvent("month", "onChange", "contentManager.rmePCR('exportDatev','','saveMonth',this.value); ");
		$F->addJSEvent("buchungssaetze", "onChange", "rmeP('exportDatev','','saveBuchungssaetze',this.checked ? '1' : '0','checkResponse(transport);')");
		$F->addJSEvent("defaultErloes", "onkeyup", "rmeP('exportDatev','','saveDefaultErloes',\$j(this).val(),'checkResponse(transport);')");
		$F->addJSEvent("defaultKundenkonto", "onkeyup", "rmeP('exportDatev','','saveDefaultKundenkonto',\$j(this).val(),'checkResponse(transport);')");
		$F->addJSEvent("profil", "onChange", "rmeP('exportDatev','','saveProfil',\$j(this).val(),'checkResponse(transport);')");
		
		$F->hideIf("month", "=", "last", "onChange", array("stichtag"));
		$F->hideIf("month", "!=", "manual", "onChange", array("start", "ende"));
		
		return $F.$T.$T2.$T3;
	}

	public static function saveProfil($profil){
		mUserdata::setUserdataS("exportDatevProfil", $profil, "", -1);

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveDefaultKundenkonto($konto){
		mUserdata::setUserdataS("DVKappendixErloeskonto", $konto, "", -1);

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveDefaultErloes($konto){
		mUserdata::setUserdataS("exportDatevDefaultErloes", $konto);

		echo "message:'Einstellung gespeichert'";
	}
	
	public static function saveStart($start){
		mUserdata::setUserdataS("exportDatevStart", $start);

		echo "message:'Einstellung gespeichert'";
	}

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

		echo "message:'Einstellung gespeichert'";
	}
	
	public static function saveBuchungssaetze($yesOrNo){
		mUserdata::setUserdataS("exportDatevBS", $yesOrNo);

		echo "message:'Einstellung gespeichert'";
	}

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

		echo "message:'Einstellung gespeichert'";
	}

	public static function saveDate($date){
		mUserdata::setUserdataS("exportDatevStichtag", $date);

		echo "message:'Einstellung gespeichert'";
	}

	private function makeXML(){
		$tempDir = FileStorage::getFilesDir();
		if(!is_executable($tempDir) AND !Util::isWindowsHost())
			Util::getBasicHTMLError("Das Verzeichnis $tempDir ist nicht beschreibbar.");

		$tempDir = $tempDir.".DatevOnlineXML/";

		if(!file_exists($tempDir))
			mkdir($tempDir);
		
		
		$dir = new DirectoryIterator($tempDir);
		foreach ($dir as $file) {
			if($file->isDot()) continue;
			if($file->isDir()) continue;

			unlink($file->getPathname());
		}
		$this->makeXMLGenPDFs($tempDir, "R");
		$this->makeXMLGenPDFs($tempDir, "G");
		
		
		
		$dokument = array(
			'date' => date("Y-m-d")."T".date("H:i:s"),
			'description' => "Dateibeschreibung",
			'client' => "Kunde123",
			'documents' => $this->dokumente
		);
		$XMLDoc = new exportDatevDOXMLDokument($dokument);
		
		$dom = new DOMDocument;
		$dom->preserveWhiteSpace = FALSE;
		$dom->loadXML($XMLDoc->asXML());
		$dom->formatOutput = TRUE;
		file_put_contents($tempDir."document.xml", $dom->saveXml());
		
		
		$zipFile = $tempDir.Util::makeFilename("DatevOnline").".zip";
		$zip = new ZipArchive();
		if (!$zip->open($zipFile, ZipArchive::CREATE))
			throw new Exception ("Kann Datei $zipFile nicht anlegen");

		$dir = new DirectoryIterator($tempDir);
		foreach ($dir AS $F) {
			if($F->isDot())
				continue;
			
			if(!$zip->addFile($F->getPathname(), $F->getFilename()))
				throw new Exception("Fehler beim Hinzufügen der Datei ".$F->getFilename());
		}
		$zip->close();

		foreach ($dir as $F) {
			if($F->getPathname() == $zipFile)
				continue;
			
			if($F->isDot())
				continue;
			
			unlink($F->getPathname());
		}
		
		header('Content-Type: application/zip');
		header('Content-disposition: attachment; filename="'. basename($zipFile).'"');
		header('Content-Length: '.filesize($zipFile));
		readfile($zipFile);
	}
	
	private $dokumente = array();
	private function makeXMLGenPDFs($tempDir, $type){
		$this->exportMode = $type;
		$AC = $this->getExportCollection(2);
		
		while($GRLBM = $AC->n()){
			$Auftrag = new Auftrag($GRLBM->A("AuftragID"));

			$brief = $Auftrag->getLetter("", false, $GRLBM->getID());
			$filename = $brief->generate(true, null);
			rename($filename, $tempDir.basename($filename));
			
			$fileNameXML = "document_".str_replace(".pdf", "", basename($filename)).".xml";
			
			$this->dokumente[] = array(
				'file' => $fileNameXML,
				'yearMonth' => date("Y-m", $GRLBM->A("datum")),
				'filePDF' => basename($filename)
			);
			
			$ACS = anyC::get("Posten", "GRLBMID", $GRLBM->getID());
			$ACS->setFieldsV3(array("preis", "menge", "mwst", "beschreibung", "name"));
			$lines = array();
			
			/**
			* Trying to get a dueDate from the PaymentConditionText
			*/
			
			$paymentCondition = $GRLBM->A("zahlungsbedingungen");
			$dueDate = NULL;
			if(preg_match("/\{\+([0-9]*)Tage*\}/", $paymentCondition, $matches)) {
				$dueDate = strtotime("+".$matches[1]." days", $GRLBM->A("datum"));
			}
			
			$lines = array();
			
			while($P = $ACS->n()){

				$prices = $P->prices($GRLBM);
				
				$tempBuildingArray = array(
					"date" => date("Y-m-d", $GRLBM->A("datum")),
					"amount" => number_format(Util::kRound((($P->A("preis")*$P->A("menge"))*($P->A("mwst")/100+1)) * (!$GRLBM->A("isR") ? -1 : 1)), 2, ".", ""),
					"accountNo" => $P->A("erloeskonto") != 0 ? str_pad($P->A("erloeskonto"), 6, "0", STR_PAD_RIGHT) : mUserdata::getUDValueS("exportDatevDefaultErloes", "0"),
					#"costCategory1" => "",
					"tax" => number_format($P->A("mwst"), 2, ".", ""),
					#"information" => "",
					"currencyCode" => "EUR",
					"invoiceId" => $GRLBM->A("prefix").$GRLBM->A("nummer"),
					"bookingText" => substr($P->A("name"), 0, 59),
					"information" => substr($P->A("beschreibung"), 0, 119),
					#"dueDate" => "",
					#"paymentConditionsId" => "",
					"bpAccountNo" => "2".str_pad($GRLBM->A("kundennummer"), 6, "0", STR_PAD_RIGHT)
				);
				
				if($dueDate != NULL) {
					$tempBuildingArray['dueDate'] = date("Y-m-d", $dueDate);
			}
			
				array_push($lines, $tempBuildingArray);
			}
			
			$XMLInvoice = new exportDatevDOXMLInvoice(array(
			"consolidatedCurrencyCode" => "EUR",
			"consolidatedInvoiceId" => $GRLBM->A("prefix").$GRLBM->A("nummer"),
			"consolidatedDate" => date("Y-m-d", $GRLBM->A("datum")),
			"consolidatedAmount" => number_format(Util::kRound($GRLBM->A("bruttobetrag")), 2, ".", ""),
			'bookingLines' => $lines
			));
			
			$XMLInvoice->asXML();
			
			$dom = new DOMDocument;
			$dom->preserveWhiteSpace = FALSE;
			$dom->loadXML($XMLInvoice->asXML());
			$dom->formatOutput = TRUE;
			file_put_contents($tempDir.$fileNameXML, $dom->saveXml());
		}
	}
	
	public function getExportData($type, $start = 0, $count = 0, $fileMode = false){
		if($fileMode == 2){
			$this->makeXML();
			return;
		}
		
		$this->exportMode = $type[0];
		
		$highestID = 0;
		$CSV = new CSVExport(8);
		$CSV->spareNumerics(true);
		
		if(mUserdata::getGlobalSettingValue("exportDatevProfil", "") == "RHVFibu"){
			$CSV->spareNumerics(false);
			$CSV->setCSVNewline("\r\n");
			$CSV->addHeaderRow([
				"khaben",
				"ksoll",
				"opnum",
				"btext",
				"datum",
				"belnr",
				"betrag",
				"stschl"
			]);
		}
		
		$AC = $this->getExportCollection($fileMode);
		while($D = $AC->getNextEntry())
			$this->entryParser($D);
		
		$AC->resetPointer();
		
		while($D = $AC->getNextEntry()){
			$r = array();
			foreach($D->getA() AS $k => $v){
				if($k == "GRLBMID")
					continue;
				
				if($k == "Umsatz" OR $k == "Nettobetrag" OR $k == "Steuern" OR $k == "betrag")
					$v = Util::CLFormatNumber ($v * 1, "default", true, true, false);
				
				if($k == "Land" AND trim($v) != "")
					$v = ISO3166::getCodeToCountry($v);
			
				$r[] = $v;
			}
			
			if($D->getID() > $highestID)
				$highestID = $D->getID();
			
			$CSV->addRow($r);
		}
		
		$last = mUserdata::getUDValueS("exportDatevLastExport".$this->exportMode, "0");
		if($highestID > $last)
			mUserdata::setUserdataS ("exportDatevLastExport".$this->exportMode, $highestID);
		
		if(mUserdata::getGlobalSettingValue("exportDatevProfil", "") == "RHVFibu")
			$CSV->getExport($this->exportFile."_".Util::CLDateParser(time()).".asc");
		else
			$CSV->getExport($this->exportFile."_".Util::CLDateParser(time()).".csv");
	}

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

	private static $Zahlungsarten = [];
	
	public function getExportCollection($fileMode = false){
		if(in_array($this->exportMode, array("R", "G", "T", "A")) AND mUserdata::getUDValueS("exportDatevBS", "0") == "1" AND $fileMode != 2)
				$this->exportMode .= "BS";
		
		$v = mUserdata::getUDValueS("exportDatev", "all");
		
		if($v == "manual"){
			$start = mUserdata::getUDValueS("exportDatevStart", "");
			if($start == "")
				die(Util::getBasicHTMLError ("Bitte geben Sie ein Start-Datum an.", "Datev Export"));
			
			$ende = mUserdata::getUDValueS("exportDatevEnde", "");
			if($ende == "")
				die(Util::getBasicHTMLError ("Bitte geben Sie ein End-Datum an.", "Datev Export"));
			
			$start = Util::CLDateParser($start, "store");
			$ende = Util::CLDateParser($ende, "store");
		}
		
		$profil = mUserdata::getGlobalSettingValue("exportDatevProfil", "");
		
		$buchungstextIf = "IF(isG = 1, 'Gutschrift', IF(isWhat='T', 'Stornorechnung', 'Rechnung'))";
		
		switch($this->exportMode){
			case "R":
			case "G":
			case "T":
			case "A":
				$datum = mUserdata::getUDValueS("exportDatevStichtag", "datum");

				$ac = anyC::get("GRLBM");
				
				if($this->exportMode == "R")
					$ac->addAssocV3("isR", "=", "1","AND","1");
				
				if($this->exportMode == "G")
					$ac->addAssocV3("isG", "=", "1","AND","1");
				
				if($this->exportMode == "T")
					$ac->addAssocV3("isWhat", "=", "T","AND","1");
				
				if($this->exportMode == "A"){
					$ac->addAssocV3("isR", "=", "1","AND","1");
					$ac->addAssocV3("isG", "=", "1","OR","1");
					$ac->addAssocV3("isWhat", "=", "T","OR","1");
				}
				
				$ac->addJoinV3("Auftrag", "AuftragID","=","AuftragID");
				$ac->addJoinV3("Kappendix", "t2.kundennummer","=","kundennummer");
				$ac->addJoinV3("Adresse", "t2.AdresseID","=","AdresseID");

				if($v != "all" AND $v != "last") {
					if($v == "manual"){
						$DStart = new Datum($start);
						$DEnd = new Datum($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");
				}
				
				if($v == "last"){
					$last = mUserdata::getUDValueS("exportDatevLastExport".$this->exportMode, "0");
					
					$ac->addAssocV3("GRLBMID", ">", $last, "AND", "2");
				}

				$umsatzkennzeichenIf = "IF(isR = 1, 'H', 'S')";
				$kontoIf = "IF(isR = 1, KappendixErloeskonto, KappendixSollkonto)";
				#$umsatzkennzeichen = "S";
				#$konto = "KappendixErloeskonto";
				#if($this->exportMode == "G" OR $this->exportMode == "T"){
					#$umsatzkennzeichen = "H";
					#$konto = "KappendixSollkonto";
				#}
				
				$ac->setFieldsV3(array(
					"IF(isG = 1, bruttobetrag * -1, bruttobetrag) AS Umsatz",
					"IF(firma != '', firma, TRIM(CONCAT(vorname, ' ', nachname))) AS Kundenname",
					"'' AS Buchungsschluessel",
					"$kontoIf AS Erloeskonto",
					"nummer AS Belegnummer",
					"'' AS Belegfeld2",
					"FROM_UNIXTIME(datum,'%d%m%Y') AS Rechnungsdatum",
					"'' AS leer1",
					"'' AS leer2",
					"$buchungstextIf AS Buchungstext",
					"IF(t2.kundennummer > 0, t2.kundennummer, '') AS Kundennummer",
					"t2.UStIdNr AS UStIdNr",
					"t4.land AS Land",
					"$umsatzkennzeichenIf AS Umsatzkennzeichen",
					"IF(t2.kundennummer < 0, 0, t2.kundennummer) + 10000 AS Kundenkonto",
					"FROM_UNIXTIME(datum,'%d.%m.%Y') AS Belegdatum",
					"KappendixErloeskonto AS Debitorenkonto"));
				
				if($profil == "RHVFibu"){
					$ac->addJoinV3("Posten", "GRLBMID", "=", "GRLBMID");
					$ac->addGroupV3("GRLBMID");
					$ac->setFieldsV3([
						"KappendixErloeskonto AS khaben",
						"IF(t2.kundennummer < 0, 0, t2.kundennummer) + 10000 AS ksoll",
						"nummer AS opnum",
						"$buchungstextIf AS btext",
						"FROM_UNIXTIME(datum,'%d%m%y') AS datum",
						"nummer AS belnr",
						"IF(isG = 1, bruttobetrag * -1, bruttobetrag) AS betrag",
						"GROUP_CONCAT(DISTINCT mwst SEPARATOR ';') AS stschl"]);
				}
				
				if($fileMode == 1)
					$ac->setFieldsV3(array(
						"bruttobetrag AS Umsatz",
						"IF(isG = 1, 'S', 'H') AS Kennzeichen",
						"'' AS WKZ",
						"'' AS Kurs",
						"'' AS BasisUmsatz",
						"'' AS WKZBasisUmsatz",
						"'' AS Kontonummer",
						"$kontoIf AS Gegenkonto",
						"'' AS BUSchluessel",
						"FROM_UNIXTIME(datum,'%d%m%Y') AS Belegdatum",
						"nummer AS Belegfeld1",
						"'' AS Belegfeld2",
						"payedWithSkonto AS Skonto",
						"$buchungstextIf AS Buchungstext",
						"$umsatzkennzeichenIf AS Umsatzkennzeichen",
						"IF(t2.kundennummer < 0, 0, t2.kundennummer) + 10000 AS Kundenkonto",
						"KappendixErloeskonto AS Debitorenkonto"));
				
				if($fileMode == 2)
					$ac->setFieldsV3 (array("*"));

				if($this->exportMode == "R")
					$this->exportFile = "Ausgangsrechnungen";
				
				if($this->exportMode == "G")
					$this->exportFile = "Ausgangsgutschriften";
				
				if($this->exportMode == "T")
					$this->exportFile = "Ausgangsstornorechnungen";
				
				if($this->exportMode == "A")
					$this->exportFile = "Ausgangsbelege";
			break;
			
			case "RBS":
			case "GBS":
			case "TBS":
			case "ABS":
				#$v = mUserdata::getUDValueS("exportDatev", "all");
				$datum = mUserdata::getUDValueS("exportDatevStichtag", "datum");

				$ac = anyC::get("GRLBM");
				
				if($this->exportMode == "RBS")
					$ac->addAssocV3("isR", "=", "1","AND","1");
				
				if($this->exportMode == "GBS")
					$ac->addAssocV3("isG", "=", "1","AND","1");
				
				if($this->exportMode == "TBS")
					$ac->addAssocV3("isWhat", "=", "T","AND","1");
				
				if($this->exportMode == "ABS"){
					$ac->addAssocV3("isR", "=", "1","AND","1");
					$ac->addAssocV3("isG", "=", "1","OR","1");
					$ac->addAssocV3("isWhat", "=", "T","OR","1");
				}
				
				$ac->addJoinV3("Auftrag", "AuftragID","=","AuftragID");
				$ac->addJoinV3("Kappendix", "t2.kundennummer","=","kundennummer");
				
				$ac->addJoinV3("Posten", "t1.GRLBMID", "=", "GRLBMID");
				$ac->addJoinV3("Posten", "preis", "!=", "0");
				$ac->addJoinV3("Adresse", "t2.AdresseID","=","AdresseID");
				$ac->addGroupV3("GRLBMID");
				$ac->addGroupV3("erloeskonto");

				if($v != "all" AND $v != "last") {
					if($v == "manual"){
						$DStart = new Datum($start);
						$DEnd = new Datum($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");
				}
				
				if($v == "last"){
					$last = mUserdata::getUDValueS("exportDatevLastExport".$this->exportMode, "0");
					
					$ac->addAssocV3("t1.GRLBMID", ">", $last, "AND", "2");
				}

				$defaultKudnenkonto =  mUserdata::getGlobalSettingValue("DVKappendixErloeskonto", "8400");
				$umsatzkennzeichenIf = "IF(isR = 1, 'S', 'H')";
				$kontoIf = "IF(isR = 1, IF(KappendixErloeskonto IS NULL, $defaultKudnenkonto, KappendixErloeskonto), KappendixSollkonto)";
				#$umsatzkennzeichen = "S";
				#$konto = "KappendixErloeskonto";
				#if($this->exportMode == "GBS" OR $this->exportMode == "TBS"){
				#	$umsatzkennzeichen = "H";
				#	$konto = "KappendixSollkonto";
				#} 
        
				$ac->setFieldsV3(array(
					"SUM(ROUND(t4.preis * (1 + (mwst / 100)) * menge * ((100 - t1.rabatt) / 100) * ((100 - t4.rabatt) / 100), 2)) AS Umsatz",
					"IF(firma != '', firma, TRIM(CONCAT(vorname, ' ', nachname))) AS Kundenname",
					"'' AS Buchungsschluessel",
					"erloeskonto AS Erloeskonto",
					"nummer AS Belegnummer",
					"'' AS Belegfeld2",
					"FROM_UNIXTIME(datum,'%d%m%Y') AS Rechnungsdatum",
					"$kontoIf AS Gegenkonto",
					"'' AS leer2",
					"$buchungstextIf AS Buchungstext",
					"IF(t2.kundennummer > 0, t2.kundennummer, '') AS Kundennummer",
					"t2.UStIdNr AS UStIdNr",
					"t5.land AS Land",
					"$umsatzkennzeichenIf AS Umsatzkennzeichen",
					"IF(t2.kundennummer < 0, 0, t2.kundennummer) + 10000 AS Kundenkonto",
					"KappendixErloeskonto AS Debitorenkonto"));
				
				
				if($this->exportMode == "RBS")
					$this->exportFile = "Ausgangsbuchungen_Rechnungen";
				
				if($this->exportMode == "GBS")
					$this->exportFile = "Ausgangsbuchungen_Gutschriften";
				
				if($this->exportMode == "TBS")
					$this->exportFile = "Ausgangsbuchungen_Stornorechnungen";
				
				if($this->exportMode == "ABS")
					$this->exportFile = "Ausgangsbuchungen_Ausgangsbelege";
			break;
			
			case "E":
				#$v = mUserdata::getUDValueS("exportDatev", "all");
				$datum = mUserdata::getUDValueS("exportDatevStichtag", "datum");
				
				if(Session::isPluginLoaded("mZahlungsart")){
					$AC = anyC::get("Zahlungsart");
					$AC->addAssocV3("ZahlungsartStammdatenID", "=", Stammdaten::getActiveStammdaten()->getID());
					#$AC->addAssocV3("ZahlungsartUseFor", "=", "");

					while($Z = $AC->getNextEntry()){
						if($Z->A("ZahlungsartUseFor") == "")
							self::$Zahlungsarten[$Z->getID()] = [$Z->A("ZahlungsartName"), $Z->A("ZahlungsartKonto")];
						else
							self::$Zahlungsarten[$Z->A("ZahlungsartUseFor")] = [$Z->A("ZahlungsartName"), $Z->A("ZahlungsartKonto")];
					}
				}
				
				if($datum == "datum")
					$datum = "EingangsbelegDatum";
				
				if($datum == "GRLBMpayedDate")
					$datum = "EingangsbelegBezahltAm";
				
				$ac = new anyC();
				$ac->setCollectionOf("Eingangsbeleg");
				#$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("Lieferant", "EingangsbelegLieferantID","=","LieferantID");

				if($v != "all" AND $v != "last") {
					if($v == "manual"){
						$DStart = new Datum($start);
						$DEnd = new Datum($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");
				}
				
				if($v == "last"){
					$last = mUserdata::getUDValueS("exportDatevLastExport".$this->exportMode, "0");
					
					$ac->addAssocV3("EingangsbelegID", ">", $last, "AND", "2");
				}
				
				$ac->setFieldsV3(array(
					"EingangsbelegBetragBrutto AS Umsatz",
					"IF(EingangsbelegLieferantID = 0, EingangsbelegLieferantName, LieferantFirma) AS Kundenname",
					"'' AS Buchungsschluessel",
					"EingangsbelegBetragKonto AS Erloeskonto",
					"EingangsbelegNummer AS Belegnummer",
					"'' AS Belegfeld2",
					"FROM_UNIXTIME(EingangsbelegDatum,'%d%m%Y') AS Rechnungsdatum",
					"'' AS leer1",
					"'' AS leer2",
					"'Rechnungseingang' AS Buchungstext",
					"EingangsbelegBetragMwSt AS MwStSatz",
					"EingangsbelegBetragNetto AS Nettobetrag",
					"EingangsbelegBetragBrutto - EingangsbelegBetragNetto AS Steuern",
					"EingangsbelegBemerkung AS Bemerkung",
					"EingangsbelegZahlungVia AS Zahlungsart",
					"'' AS ZahlungsartKonto"
					#"'' AS Kundennummer",
					#"'' AS UStIdNr"
				));
				
				$this->exportFile = "Eingangsbelege";
			break;
			
			case "K":
				$v = mUserdata::getUDValueS("exportDatev", "all");
				$datum = mUserdata::getUDValueS("exportDatevStichtag", "datum");
				
				if($datum == "datum")
					$datum = "KassenbuchDatum";
				
				if($datum == "GRLBMpayedDate")
					$datum = "KassenbuchDatum";
				
				$ac = anyC::get("Kassenbuch");
				#$ac->addJoinV3("Lieferant", "EingangsbelegLieferantID","=","LieferantID");

				if($v != "all" AND $v != "last") {
					if($v == "manual"){
						$DStart = new Datum($start);
						$DEnd = new Datum($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");
				}
				
				if($v == "last"){
					$last = mUserdata::getUDValueS("exportDatevLastExport".$this->exportMode, "0");
					
					$ac->addAssocV3("EingangsbelegID", ">", $last, "AND", "2");
				}

				$ac->setFieldsV3(array(
					"KassenbuchEinnahme - KassenbuchAusgabe AS Umsatz",
					"'' AS Kundenname",
					"KassenbuchKontoKasse AS Buchungsschluessel",
					"IF(KassenbuchEinnahme > KassenbuchAusgabe, KassenbuchKontoEinzahlung, KassenbuchKontoEntnahme) AS Erloeskonto",
					"KassenbuchBelegnummer AS Belegnummer",
					"KassenbuchKontoSteuern AS Steuerkonto",
					"FROM_UNIXTIME(KassenbuchDatum,'%d%m%Y') AS Rechnungsdatum",
					"'' AS leer1",
					"'' AS leer2",
					"KassenbuchBuchungstext AS Buchungstext",
					"KassenbuchSteuersatz AS Steuersatz",
					"KassenbuchSteuern AS Steuern",
					#"'' AS UStIdNr"
				));
				
				$this->exportFile = "Kassenbuch";
			break;
		}
		return $ac;
	}
	private $defaultErloes;
	private $defaultKunde;
	protected function entryParser(PersistentObject $entry){
		if($this->defaultErloes === null)
			$this->defaultErloes = mUserdata::getUDValueS("exportDatevDefaultErloes", "0");
		
		if($this->defaultKunde === null)
			$this->defaultKunde = mUserdata::getGlobalSettingValue("DVKappendixErloeskonto", "0");

		$A = $entry->getA();
			
		if(isset($A->stschl)){
			$ex = explode(";", $A->stschl);
			foreach($ex AS $k => $v){
				if($v == 19)
					$ex[$k] = 29;
				
				if($v == 7)
					$ex[$k] = 27;
				
			}
			$A->stschl = implode(";", $ex);
		}
		
		if(isset($A->Erloeskonto) AND !$A->Erloeskonto)
			$A->Erloeskonto = $this->defaultErloes;
		
		if(isset($A->Debitorenkonto) AND !$A->Debitorenkonto)
			$A->Debitorenkonto = $this->defaultKunde;
		
		unset($A->EingangsbelegID);

		if(isset($A->Zahlungsart) AND isset(self::$Zahlungsarten[$A->Zahlungsart])){
			$A->ZahlungsartKonto = self::$Zahlungsarten[$A->Zahlungsart][1];
			$A->Zahlungsart = self::$Zahlungsarten[$A->Zahlungsart][0];
		}
		
	}
}
?>