<?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 GRLBMDisplayGUI extends UnpersistentClass implements iGUIHTML2 {
	public $CustomizerTeilzahlungen = false;
	public $Zahlungsziel = false;

	function  __construct() {
		parent::__construct();
		$this->customize();
	}
	public function getHTML($id){
		T::load(__DIR__, "Uebersicht");
		
		$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
		$pSpecDataRechnungen = mUserdata::getPluginSpecificData("Provisionen");
		
		$G = new GRLBM($id);
		#$G->setParser("GRLBMpayedDate","Util::CLDateParserE");
		$G->loadMe();

		$Auftrag = new Auftrag($G->A("AuftragID"));
		$Auftrag->loadMe();

		$Adresse = new Adresse($Auftrag->A("AdresseID"));
		$Adresse->loadMe();

		$Auftrag->checkUserRestrictions($pSpecData);

		
		#$dispProv = ($_SESSION["S"]->checkForPlugin("Provisionen") AND isset($pSpecDataRechnungen["pluginSpecificCanGiveProvisions"]));

		$U = new UebersichtGUI();
		$I = new HTMLInput("isPayed", "select", $G->getA()->isPayed, $U->getAvailableCategories());
		$I->onchange("/*if(this.value == 2) contentManager.toggleFormFields('show',['GRLBMpayedBemerkung']); else contentManager.toggleFormFields('hide',['GRLBMpayedBemerkung']); */if(this.value != 0) contentManager.toggleFormFields('show',['GRLBMpayedDate']); else contentManager.toggleFormFields('hide',['GRLBMpayedDate']); ");
		$I->isDisplayMode(!isset($pSpecData["pluginSpecificCanSetPayed"]));

		if($G->A("isPayed") == "0") $G->changeA("GRLBMpayedDate", Util::CLDateParser(time()));
		$P = new HTMLInput("GRLBMpayedDate", "date", $G->A("GRLBMpayedDate"));
		$P->id("GRLBMpayedDate");
		$P->hasFocusEvent(true);
		$P->isDisplayMode(!isset($pSpecData["pluginSpecificCanSetPayed"]));

		$Zahlungsmoral = null;
		if((Session::isPluginLoaded("mStatistik") AND $Auftrag->A("kundennummer") > 0))
			$Zahlungsmoral = ZahlungsmoralGUI::getAverage($Auftrag->A("kundennummer"));
				
		$X = new HTMLTable(2, T::_(Stammdaten::getLongType($G->getMyPrefix()))." ".$G->A("nummer"));
		$X->setColWidth(1, 120);
		
		$X->addLV(T::_("Kunde").":", ($Auftrag->A("kundennummer") > 0 ? AdressenGUI::getContactButton($Auftrag->A("kundennummer")) : "").$Adresse->getHTMLFormattedAddress());
		$X->addLV(T::_("Kundennummer").":", ($Auftrag->A("kundennummer") > 0 ? $Auftrag->A("kundennummer") : ""));
		
		$X->addRow(array());
		$X->addRowClass("backgroundColor0");
		
		$X->addLV(T::_("Datum").":", $G->A("datum"));
		
		if($this->Zahlungsziel)
			$X->addLV(T::_("Zahlungsziel").":", ($G->A("zahlungsziel") > 0 ? Util::CLDateParser($G->A("zahlungsziel")) : "keines"));
		
		if($Zahlungsmoral !== null)
			$X->addLV(T::_("Zahlungsmoral").":", $Zahlungsmoral." ".T::_("Tag".($Zahlungsmoral == 1 ? "" : "e")));
		
		$X->addLV(T::_("Gesamt").":", Util::CLFormatCurrency($G->getSumOfPosten(),true));
		
		$X->addRow(array());
		$X->addRowClass("backgroundColor0");
		
		if(Session::isPluginLoaded("mZahlungsart")){
			$IZA = new HTMLInput("GRLBMpayedVia", "select", $G->A("GRLBMpayedVia"), GRLBM::getPaymentVia());
			$IZA->isDisplayMode(!isset($pSpecData["pluginSpecificCanSetPayed"]));
			
			$X->addLV(T::_("Zahlungsart").":", $IZA);
		}
		
		if(Session::isPluginLoaded("mLastschrift")){
			$L = Lastschrift::exists($G->getID());
			if($L)
				$X->addLV(T::_("Lastschrift").":", T::_("Ausgeführt am")." ".Util::CLDateParser($L->A("LastschriftTime")));
		}
		
		$X->addLV(T::_("Status").":", $I);
		
		if(Session::isPluginLoaded("mSEPA")){
			$I = new HTMLInput("GRLBMRuecklastschrift", "checkbox", $G->A("GRLBMRuecklastschrift"));
			$X->addLV(T::_("Rücklastschrift?").":", $I."<br><small style=\"color:grey;\">Der Beleg wird nicht mehr in der SEPA-XML-Datei berücksichtigt.</small>");
		}
		
		Aspect::joinPoint("afterState", $this, __METHOD__, array($X, $G));
		
		$X->addLV(T::_("Datum").":", $P);
		if($G->A("isPayed") == "0")
			$X->addRowStyle ("display:none;");

		$T = new HTMLInput("GRLBMpayedBemerkung", "textarea", $G->A("GRLBMpayedBemerkung"));
		$T->hasFocusEvent(true);
		$T->id("GRLBMpayedBemerkung");
		$T->isDisplayMode(!isset($pSpecData["pluginSpecificCanSetPayed"]));

		$X->addLV(T::_("Bemerkung").":", $T);
		
		if(isset($pSpecData["pluginSpecificCanSetPayed"])){
			#contentManager.updateLine('editGRLBMForm', '$id', 'Uebersicht'); contentManager.rmePCR('Uebersicht', '-1', 'summeUnbezahlt', [], function(t){
			#		\$j('#unpaidSum').html(t.responseText);
			#	});
			$S = new HTMLInput("currentSaveButton", "button", "Änderungen speichern");
			$S->style("background-image: url(./images/i2/save.gif);");
			$S->onclick("saveClass('GRLBM','$id',function() { ".OnEvent::reload("Right")." },'editGRLBMForm');");

			$X->addRow(array($S));
			$X->addRowColspan(1, 2);
		}
		
		$html = "<form id=\"editGRLBMForm\">$X</form>";

		
		$BPDFK = new Button(($G->getMyPrefix() == "R" ? "Rechnung" : "Gutschrift")."\nanzeigen", "pdf");
		$BPDFK->windowRme("Auftrag", $G->getA()->AuftragID, "getGRLBMPDF", array("'false'", "''", $G->getID()), "_Brief;templateType:PDF");
		#$BPDFK->className("backgroundColor2");
		
		
		$BAuftrag = new Button("Auftrag\nöffnen", "edit");
		$BAuftrag->loadFrame("contentLeft", "Auftrag", $G->A("AuftragID"), 0, "AuftragGUI;GRLBMID:".$G->getID());
		#$BAuftrag->onclick("contentManager.loadFrame('contentLeft','Auftrag','{$G->getA()->AuftragID}');");
		
		$ST = new HTMLSideTable("right");
		$ST->addRow($BAuftrag);
		$ST->addRow($BPDFK);
		$ST->addRow("&nbsp;");
		
		
		if(Session::isPluginLoaded("Provisionen")){
			$B = new Button("Provisionen\nvergeben", "provision");
			$B->onclick("contentManager.loadFrame('contentLeft','ProvisionSwitch', -1, 0,'ProvisionSwitchGUI;useGRLBMID:{$G->getID()}');");
			$ST->addRow($B);
		}
		
		if(Session::isPluginLoaded("mSEPA")){
			$KA = Kappendix::getKappendixToKundennummer($Auftrag->A("kundennummer"));
			
			$BEditSEPA = new Button("SEPA-Daten\nbearbeiten", "new");
			$BEditSEPA->popup("", "SEPA-Daten bearbeiten", "GRLBMDisplay", "-1", "sepaPopup", $G->getID());
			if($KA != null AND strpos($G->A("GRLBMSEPAData"), "\"MandateDate\":\"0\"") AND $KA->A("KappendixEinzugsermaechtigung"))
				$BEditSEPA->className("highlight");

			$ST->addRow($BEditSEPA);
			$ST->addRow("&nbsp;");
		}
		
		$BPDF = new Button("Original\ndrucken", "printer", "MPBig");
		$BPDF->doBefore("\$j(this).addClass('confirm'); %AFTER");
		$BPDF->windowRme("Auftrag", $G->A("AuftragID"), "getGRLBMPDF", array("'false'", "''", $G->getID(), 1), "_Brief;templateType:PDF");
		$BPDF->id("buttonPrintOriginal");
		#$BPDF->style("width:100px;background-position: 95% 50%;");
		if($G->A("isPrinted") > 0)
			$BPDF->addClass("confirm");
		
		$BPDFK = new Button("Kopie\ndrucken", "printer", "LPBig");
		$BPDFK->doBefore("\$j(this).addClass('confirm'); %AFTER");
		$BPDFK->windowRme("Auftrag", $G->A("AuftragID"), "getGRLBMPDF", array("'true'", "''", $G->getID(), 1), "_Brief;templateType:PDF");
		$BPDFK->id("buttonPrintCopy");
		#$BPDFK->style("float:right;margin-right:3px;");
		if($G->A("isPrintedCopy") > 0)
			$BPDFK->addClass("confirm");
		
		$ST->addRow($BPDF.$BPDFK.(($G->A("isPrinted") == "1" AND $G->A("isPrintedTime") != "0") ? "<br /><small style=\"color:grey;\">".Util::CLDateTimeParser($G->A("isPrintedTime"))."</small>" : ""));
		
		if(Session::isPluginLoaded("PL")) {
			$BPL = PLGUI::getButton($G->A("AuftragID"), $G->getID());
			if($G->A("isPixelLetteredTime") > 0)
				$BPL->addClass ("confirm");
			
			$SPL = new Button("Einstellungen","wrench", "iconic");
			$SPL->className("buttonSettings iconicG");
			$SPL->onclick("phynxContextMenu.start(this, 'PL','1','".T::_("Einstellungen").":','right','up');");

			$ST->addRow($BPL.(($G->A("isPixelLetteredTime") > 0) ? "<br /><small style=\"color:grey;\">".Util::CLDateTimeParser($G->A("isPixelLetteredTime"))."</small>" : ""));
		}
		
		$BMail = new Button("per E-Mail\nverschicken","mail");
		$BMail->onclick("Auftrag.windowMail(".$G->A("AuftragID").", '".$G->getID()."','E-Mail', ".$G->A("GRLBMAnsprechpartnerID").");");
		$BMail->id("sendViaEmailButton");
		if($G->A("isEMailed") == "1" AND $G->A("isEMailedTime") != "0")
			$BMail->addClass ("confirm");
		
		$ST->addRow($BMail.(($G->A("isEMailed") == "1" AND $G->A("isEMailedTime") != "0") ? "<br /><small style=\"color:grey;\">".Util::CLDateTimeParser($G->A("isEMailedTime"))."</small>" : ""));
		
		
		$BO = "";
		if($Auftrag->A("kundennummer") > 0 and Session::isPluginLoaded("Berichte")){
			$AC = anyC::get("Auftrag", "kundennummer", $Auftrag->A("kundennummer"));
			$AC->addJoinV3("GRLBM", "AuftragID", "=", "AuftragID");
			$AC->addAssocV3("isPayed", "=", "0");
			$AC->addAssocV3("isR", "=", "1", "AND", "2");
			$AC->addAssocV3("isG", "=", "1", "OR", "2");
			$AC->addAssocV3("isWhat", "=", "T", "OR", "2");
			$num = $AC->getTotalNum();
			
			$unbezahlt = "%1 ".($num != 1 ? "offene\nPosten" : "offener\nPosten");
			#windowWithRme('Bericht_AusstehendeRechnungen', '-1', 'getPDF', Array(''), '', 'window');
			$BO = new Button("", "bericht", "MPBig");
			$BO->label($unbezahlt, $num);
			$BO->windowRme("Bericht_AusstehendeRechnungen", "-1", "getPDF", array(0, "'".$Auftrag->A("kundennummer")."'"));
			if($num > 3)
				$BO->className ("highlight");
			
			$BF = new Button("Ansicht filtern", "./open3A/Uebersicht/filter.svg", "LPBig");
			#$BF->onclick("; {  contentManager.rmePCR('HTML', '', 'saveContextMenu', ['searchFilter','Uebersicht;:;'+$('quickSearchUebersicht').value], 'if(checkResponse(transport)) contentManager.loadFrame(\'contentRight\', \'Uebersicht\', -1, 0);', '', true ); }");
			
			$BF->rmePCR("GRLBMDisplay", -1, "filter", ["'".$Adresse->getShortAddress()."'"], OnEvent::reload("Right"));
			
			$ST->addRow($BO.$BF);
		}
		
		if(Session::isPluginLoaded("mMicropayment") AND $Auftrag->A("kundennummer") > 0){
			$BM = new Button("Lastschrift per\nMicropayment", "./open3A/Micropayment/Micropayment.png");
			$BM->popup("", "Lastschrift", "Micropayment", "-1", "directDebit", array("'".$Auftrag->A("kundennummer")."'", $G->getID()));
			
			$ST->addRow($BM);
		}
		
		
		$basketBPS = BPS::getAllProperties("multiPrintBasketGUI");
		
		$BAddMP = new Button("zur multiDruck-\nListe hinzufügen", "./images/navi/addtolist.png");
		$BAddMP->id("GRLBMAddToMultiPrintList");
		$BAddMP->style(((!strstr($basketBPS["ids"],",".$G->getID().",") OR $basketBPS["ids"] == "") ? "":"display:none;")."float:left;");
		$BAddMP->onclick("addToMultiPrintAusAuftrag(".$G->getID().");");

		$BDelMP = new Button("von multiDruck-\nListe entfernen", "./images/navi/subfromlist.png");
		$BDelMP->id("GRLBMSubFromMultiPrintList");
		$BDelMP->style(((!strstr($basketBPS["ids"],",".$G->getID().",") OR $basketBPS["ids"] == "") ? "display:none;":"")."float:left;");
		$BDelMP->onclick("subFromMultiPrintAusAuftrag(".$G->getID().");");
		
		$ST->addRow($BAddMP.$BDelMP);
			
		
		/*$html .= "
			<tr class=\"backgroundColor0\">
				<td></td>
			</tr>
			
			<tr ".(!$dispProv ? "style=\"display:none;\"" : "" ).">
				<td class=\"backgroundColor3\" colspan=\"2\">
				".(($dispProv AND $_SESSION["S"]->checkForPlugin("Mahnung")) ? str_replace("%%FLOAT%%","float: right;",$mahnungButton) : "")."
				".(($dispProv) ? "<input type=\"button\" value=\"Provisionen\nvergeben\" style=\"background-image: url(./images/navi/provision.png);\" class=\"bigButton backgroundColor2\" onclick=\"\" />"
					: (($_SESSION["S"]->checkForPlugin("Mahnung")) ? str_replace("%%FLOAT%%","",$mahnungButton) : ""))."
				</td>
			</tr>
		</table>
		</form>";*/

		#<img src=\"./images/i2/".($G->getA()->isPayed == "1" ? "" : "not")."ok.gif\" id=\"GRLBMDisplayPaydIcon{$G->getID()}\" ".(isset($pSpecData["pluginSpecificCanSetPayed"]) ? "onclick=\"setRechnungPayed(this,'{$G->getID()}');" :"")."\" />
		if($G->A("GRLBMTeilzahlungenSumme") != null AND $this->CustomizerTeilzahlungen){
			if(trim($G->A("GRLBMTeilzahlungen")) != ""){
				$s = explode("\n", trim($G->A("GRLBMTeilzahlungen")));
				$Ts = "<table>
					<colgroup>
						<col />
						<col />
						<col style=\"width:20px;\" />
					</colgroup>";
				
				for($i = 0; $i < count($s); $i++){
					$B = new Button("Teilzahlung löschen","./images/i2/delete.gif");
					$B->type("icon");
					$B->onclick("if(confirm('Wirklich löschen?')) ");
					$B->rme("GRLBM", $G->getID(), "deleteTeilzahlung",$i,"if(checkResponse(transport)) { contentManager.reloadFrame(\'contentLeft\'); contentManager.updateLine(\'\', {$G->getID()}, \'Uebersicht\'); }");
					
					if(!isset($pSpecData["pluginSpecificCanSetPayed"])) $B = "";
					
					$s2 = explode(";",$s[$i]);
					$Ts .= "<tr><td>".Util::CLDateParser($s2[1])."".(isset($s2[2]) ? "<br /><small style=\"color:grey;\">".$s2[2]."</small>" : "")."</td><td style=\"text-align:right;\">".Util::CLFormatCurrency($s2[0]*1,true)."</td><td>$B</td></tr>";
				}
				$Ts .= "</table>";
			} else $Ts = "keine";

			$onEnter = "rme('GRLBM','{$G->getID()}','setPayed',['false','0,00', $('neueTeilzahlungDatum').value,'true',$('neueTeilzahlungBetrag').value],'if(checkResponse(transport)) { contentManager.reloadFrame(\'contentLeft\'); contentManager.updateLine(\'\', {$G->getID()}, \'Uebersicht\');}');";

			$ITD = new HTMLInput("neueTeilzahlungDatum", "text", Util::CLDateParser(time()));
			$ITD->id("neueTeilzahlungDatum");
			$ITD->style("width:100px;");
			$ITD->hasFocusEvent(true);
			$ITD->onEnter($onEnter);

			$ITB = new HTMLInput("neueTeilzahlungBetrag", "text");
			$ITB->id("neueTeilzahlungBetrag");
			$ITB->style("width:110px;text-align:right;");
			$ITB->hasFocusEvent(true);
			$ITB->onEnter($onEnter);

			$ITS = new Button("Teilzahlung speichern", "./images/i2/save.gif");
			$ITS->type("icon");
			$ITS->style("float:right;margin-left:5px;margin-top:7px;");
			$ITS->onclick($onEnter);

			$html .= "
		<div class=\"backgroundColor1 Tab\" style=\"margin-top:10px;\"><p>Teilzahlungen</p></div>
		<table>
			<colgroup>
			<col class=\"backgroundColor2\" style=\"width: 120px;\"/>
			<col class=\"backgroundColor3\" />
			</colgroup>
			<tr>
				<td><label>".T::_("Teilzahlungen").":</label></td>
				<td>$Ts</td>
			</tr>";

			if(isset($pSpecData["pluginSpecificCanSetPayed"])) $html .= "
			<tr>
				<td><label>neu:</label></td>
				<td style=\"text-align:right;\"><div style=\"float:left;text-align:left;\">$ITD<br /><small>Datum</small></div>$ITS<div>$ITB<br /><small>Betrag ohne Währungs-Symbol</small></div></td>
			</tr>";

			$ausstehend = $G->getSumOfPosten() - $G->A("GRLBMTeilzahlungenSumme") * 1;
			if($G->A("isPayed") == "1") $ausstehend = 0;

			$html .= "
			<tr>
				<td><label>".T::_("Ausstehend").":</label></td>
				<td>".Util::CLFormatCurrency($ausstehend,true)."</td>
			</tr>
		</table>";
		}
					
		if($_SESSION["S"]->checkForPlugin("Mahnung") AND $G->getMyPrefix() == "R"){
			$M = new MahnungGUI();
			$html .= $M->getHTML($G->getID());
		}

		#if(Session::isPluginLoaded("mArchivista")){
		#	$Arch = new ArchivistaGUI();
		#	$html .= $Arch->getHTML($G->getID());
		#}

		return $ST.$html;
	}
	
	public function filter($kd){
		#$BF->rmePCR("HTML", "", "saveContextMenu", ["'searchFilter'","'Uebersicht;:;".$Auftrag->A("kundennummer")."'"], OnEvent::reload("Right"));
		$G = new HTMLGUI();
		$G->saveContextMenu("searchFilter", "Uebersicht;:;".$kd);
		$G->saveContextMenu("filterCategories", "Uebersicht--;0:1");
	}
	
	public function sepaPopup($GRLBMID){
		T::load(__DIR__, "Uebersicht");
		$G = new GRLBM($GRLBMID, false);

		$F = new HTMLForm("sepa", array(
			"GRLBMID",
			"IBAN",
			"BIC",
			"MandateDate",
			"MandateID",
			"Typ"
		));
		$F->useRecentlyChanged();
		
		$F->getTable()->setColWidth(1, 120);
		
		$F->setValue("GRLBMID", $GRLBMID);
		
		
		$F->setType("MandateDate", "date");
		$F->setType("GRLBMID", "hidden");
		$F->setType("Typ", "select", null, array("" => "Standard (".mUserdata::getUDValueS("SEPAArt", "COR1").")", "COR1" => "COR1 (Eillastschrift)", "CORE" => "CORE"));
		
		if(trim($G->A("GRLBMSEPAData")) != "" AND $G->A("GRLBMSEPAData") != "{}" AND $G->A("GRLBMSEPAData") != "[]"){
			$data = json_decode($G->A("GRLBMSEPAData"));
			$data->MandateDate = Util::CLDateParserE($data->MandateDate);
			foreach($data AS $fieldName => $value)
				$F->setValue($fieldName, $value);
		}
		
		$F->setLabel("MandateDate", "Mandatsdatum");
		$F->setLabel("MandateID", "Mandat");
		
		$F->setSaveRMEPCR("Speichern", "", "GRLBMDisplay", "-1", "sepaSave", OnEvent::closePopup("GRLBMDisplay").OnEvent::reload("Left"));
		
		$B = new Button("Aktuelle\nDaten", "down");
		$B->style("margin:10px;");
		$B->rmePCR("GRLBMDisplay", "-1", "getSEPA", $GRLBMID, "function(t){ for (var name in t.responseData) { if(\$j('[name='+name+']').val() != t.responseData[name]) \$j('[name='+name+']').trigger('keydown'); \$j('[name='+name+']').val(t.responseData[name]); } }");
		
		echo $B.$F;
	}
	
	public function sepaSave($GRLBMID, $IBAN, $BIC, $MandateDate, $MandateID, $Typ){
		$c = new stdClass();
		$c->IBAN = $IBAN;
		$c->BIC = $BIC;
		$c->MandateDate = Util::CLDateParserE($MandateDate, "store");
		$c->MandateID = $MandateID;
		$c->Typ = $Typ;
		
		$G = new GRLBM($GRLBMID, false);
		$G->changeA("GRLBMSEPAData", json_encode($c));
		$G->saveMe();
	}
	
	public function getSEPA($GRLBMID){
		$G = new GRLBM($GRLBMID, false);
		$Auftrag = new Auftrag($G->A("AuftragID"));
		$KA = Kappendix::getKappendixToKundennummer($Auftrag->A("kundennummer"));
		if(!$KA)
			die("{}");
		
		$data = $KA->getSEPAData();
		$data->MandateDate = Util::CLDateParserE($data->MandateDate);
		
		echo json_encode($data);
	}
}

?>