<?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 LastschriftListeGUI extends LastschriftListe implements iGUIHTML2, icontextMenu {
	private $defaultPain = "pain.008.003.02";
	
    public function getHTML($id){
		$AC = $this->getInterestingData();

		$T = new HTMLTable(4, "Rechnungen mit Einzugsermächtigung");
		$T->addColStyle(4, "width:26px;");
		$T->maxHeight(500);
		#$T->setTableStyle("padding-left:8px;");
		
		$B2 = new HTMLInput("toggleAll", "checkbox", 0);
		$B2->onclick("\$j('.overDueCheckBox:enabled').prop('checked', \$j(this).prop('checked'));");

		$T->addHeaderRow(array("Kunde/Rechnung", "fällig am", "Betrag", $B2));
		$T->addColStyle(1,"text-align:left;width:180px;");
		$T->addColStyle(3,"text-align:right;");
		
		$total = 0;
		while($GRLBM = $AC->n()){


			$HI = new HTMLInput("ID".$GRLBM->A("GRLBMID").($GRLBM->A("ZahlungsaufforderungID") === null ? "" : "_".$GRLBM->A("ZahlungsaufforderungID")), "checkbox", 1);
			$HI->id("ID".$GRLBM->A("GRLBMID").($GRLBM->A("ZahlungsaufforderungID") === null ? "" : "_".$GRLBM->A("ZahlungsaufforderungID")));
			$HI->setClass("overDueCheckBox");
			
			$datum = Util::CLDateParser($GRLBM->A("datum") + 14 * 24 * 3600);
			if($GRLBM->A("zahlungsziel") !== null)
				$datum = Util::CLDateParser($GRLBM->A("zahlungsziel"));
			
			$data = new stdClass();
			if($GRLBM->A("GRLBMSEPAData") != "" AND $GRLBM->A("GRLBMSEPAData") != "[]")
				$data = json_decode($GRLBM->A("GRLBMSEPAData"));
				
			$B = "";
			$messageSEPA = "";
			$validBic = preg_match("/^[A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1}$/", $data->BIC);
			if(strlen($data->BIC) != 8 AND strlen($data->BIC) != 11)
				$validBic = false;
			
			$I = new IBAN($data->IBAN);
			$validIBAN = $I->VerifyChecksum();
			
			#echo $e->A("nummer").": ".strlen($e->A("KappendixSWIFTBIC"))."<br>";
			$error = false;
			if(Session::isPluginLoaded("mSEPA") AND ($data->BIC == "" OR $data->IBAN == "" OR $data->MandateDate == "0") OR !$validBic OR !$validIBAN){
				$B = new Button("Fehlende Kontodaten","./images/i2/note.png", "icon");
				$B->style("float:right;");
				
				if(!$validBic)
					$messageSEPA .= "SEPA: Der BIC ist ungültig!";
				
				if(!$validIBAN)
					$messageSEPA .= "SEPA: Die IBAN ist falsch!";
				
				if($data->BIC == "" OR $data->IBAN == "")
					$messageSEPA .= ($messageSEPA != "" ? "<br>" : "")."SEPA: Fehlende Kontodaten";
				
				if($data->MandateDate == "0")
					$messageSEPA .= ($messageSEPA != "" ? "<br>" : "")."SEPA: Fehlendes Mandatsdatum";
				
				$messageSEPA = "<small><a style=\"color:darkred;\" href=\"#\" onclick=\"".OnEvent::popup("SEPA-Daten bearbeiten", "GRLBMDisplay", -1, "sepaPopup", array("'".$GRLBM->getID()."'"))."\">$messageSEPA</a></small>";
				#$HI->style("display:none;");
				$HI->setValue(0);
				$HI->isDisabled(true);
				$error = true;
			}

			$messageRechnung = "";
			if($GRLBM->A("bruttobetrag") <= 0){
				$messageRechnung = "<small style=\"color:darkred;\">Rechnung: Rechnungbetrag kleiner gleich Null!</small>";
				$HI->isDisabled(true);
				$HI->setValue(0);
				$error = true;
			}
				
			
			if($GRLBM->A("GRLBMSEPATransmitted") > 0){
				$HI->setValue(0);
				
				$B = new Button("Auftrag übermittelt am ".Util::CLDateTimeParser($GRLBM->A("GRLBMSEPATransmitted")),"./open3A/Uebersicht/inAuftrag18.png", "icon");
				$B->style("float:right;");
			}
			
			if($GRLBM->A("GRLBMSEPATransmitted") < 0){
				$HI->setValue(0);
				
				$B = new Button("Auftrag freigegeben am ".Util::CLDateTimeParser($GRLBM->A("GRLBMSEPATransmitted") * -1),"./open3A/Lastschriften/cleared18.png", "icon");
				$B->style("float:right;");
				$B->rmePCR("LastschriftListe", "-1", "unmarkCleared", array("'".$GRLBM->A("GRLBMID").($GRLBM->A("ZahlungsaufforderungID") === null ? "" : "_".$GRLBM->A("ZahlungsaufforderungID"))."'"), OnEvent::reload("Left"));
			}
			
			if(Session::isPluginLoaded("mSEPA") AND $messageSEPA == "")
				$messageSEPA = "<small style=\"color:darkgreen;\">SEPA: OK</small>";

			$name = $GRLBM->A("firma");
			if($name == "") $name = $GRLBM->A("vorname")." ".$GRLBM->A("nachname");

			$BB = "";
			if(Session::isPluginLoaded("mBanking")){
				$ACBT = anyC::get("BankingTransfer");
				$ACBT->addAssocV3("BankingTransferDone", ">", "0");
				$ACBT->addAssocV3("BankingTransferType", "=", "debit");
				$ACBT->addAssocV3("BankingTransferPurpose", "LIKE", $GRLBM->A("prefix").$GRLBM->A("nummer")."%");
				$BT = $ACBT->n();
				
				$BB = new Button("Lastschrift erstellen", "./open3A/Banking/transfer18.png", "icon");
				$BB->style("float:right;margin-right:10px;");
				$BB->popup("", "Lastschrift", "mBanking", '-1', "newTransfer", array("'GRLBM'", $GRLBM->getID(), "'debit'", "1"));
				if($BT != null){
					$BB->image ("./images/i2/bestaetigung.png");
					$BB->label("Lastschrift ausgeführt am ".($BT->A("BankingTransferDone")));
				}
			}
			
			$win = OnEvent::window(new Auftrag($GRLBM->A("AuftragID")), "getGRLBMPDF", Array('0','',$GRLBM->A("GRLBMID")), "_Brief;templateType:PDF");
			
			$skontoText = "";
			if($GRLBM->A("GRLBMSkonto") != ""){
				$skontoData = json_decode($GRLBM->A("GRLBMSkonto"));
				$skontoText = "<small style=\"color:darkgreen;\">".Util::CLNumberParser($skontoData->prozent)."% Skonto</small>";
			}
			
			$brutto = $GRLBM->A("bruttobetrag");
			if(isset($skontoData) AND $skontoData->prozent > 0)
				$brutto = Util::kRound($brutto * ((100 - $skontoData->prozent) / 100));
				
			$brutto += $GRLBM->A("gebuehren");
			
			$T->addRow(array(
				"<a href=\"#\" onclick=\"".$win."return false\">".$GRLBM->A("prefix").$GRLBM->A("nummer")."</a><br><small style=\"color:grey;\">".$name." (<a href=\"#\" onclick=\"contentManager.selectRow(this); contentManager.loadFrame('contentLeft', 'Kappendix', ".$GRLBM->A("KappendixID").", 0);return false;\" style=\"color:grey;\">".$GRLBM->A("kundennummer")."</a>)</small>",
				$B.$BB.$datum." <br>$messageSEPA<br>$messageRechnung",
				Util::CLNumberParserZ($brutto)."<br>$skontoText",
				$HI));
			
			
			$T->addCellStyle (1, "vertical-align:top;");
			$T->addCellStyle (2, "text-align:left;");
			
			if($brutto > 0){
				$total += $brutto;
			}
		}
		
		if($AC->numLoaded() == 0){
			$T->addRow (array("Keine Belege"));
			$T->addRowColspan(1, 4);
		}
		
		$T2 = new HTMLTable(2);
		$T2->addColStyle(2, "width:26px;");
		if($AC->numLoaded() > 0){
			$T2->addRow(array("Gesamt: <span style=\"float:right;\">".Util::CLNumberParserZ($total)."</span>"), "");
			$T2->addRowClass("backgroundColor0");
			$T2->addCellStyle(1, "border-top-width:3px;border-top-style:double;font-weight:bold;");
			$T2->addCellClass(1, "borderColor1");
			
			$T2->addCellStyle(2, "border-top-width:3px;border-top-style:double;font-weight:bold;");
			$T2->addCellClass(2, "borderColor1");
		}

		$ST = new HTMLSideTable("right");
		if(Session::isPluginLoaded("mSEPA")){
			$BM = new Button("SEPA Basis-\nLastschrift", "lastschrift");
			$BM->windowRmeP('LastschriftListe','','createLastschrift',array("'SEPABasisLastschrift'", "joinFormFieldsToString('createLastschriftForm')"));
			#$BM->style("float:left;margin-right:10px;");
			$BM->settings("LastschriftListe", "SEPA");
			
			$BF = new Button("SEPA Firmen-\nLastschrift", "lastschrift");
			$BF->windowRmeP('LastschriftListe','','createLastschrift',array("'SEPAFirmenLastschrift'", "joinFormFieldsToString('createLastschriftForm')"));
			#$BF->style("float:left;margin-right:10px;");
			
			
			$BR = new Button("SEPA-Bericht", "pdf");
			$BR->windowRmeP('LastschriftListe','','createLastschrift',array("'SEPAReport'", "joinFormFieldsToString('createLastschriftForm')"));

			$M = "";
			$S = Stammdaten::getActiveStammdaten();
			if($S->A("glaeubigerID") == ""){
				$BM->disabled(true);
				$BF->disabled(true);
				$M = "<span style=\"color:red;\">Bitte tragen Sie Ihre Gläubiger-ID in den Stammdaten ein.</span>";
				$BR->disabled(true);
			}
			
			$ST->addRow($BM);
			$ST->addRow($BF);
			$ST->addRow("");
			$ST->addRow($BR.$M);
			#$T2->addRow($BR.$BM.$BF.$M);
			#$T2->addRowColspan(1,3);
		}


		$LoginData = LoginData::get("RegIDUserPass");
		$LoginData = $LoginData == null ? -1 : $LoginData->getID();

		if(Session::isPluginLoaded("mRegID")){
			$BM = new Button("An RegID\nübertragen", "./open3A/RegID/RegID.png");
			$BM->popup('','RegID-Protokoll','RegID', "-1",'createLastschriftWrapper',array("'SepaDDOrder'", "joinFormFieldsToString('createLastschriftForm')"));
			$BS = $BM->settings("");
			$BS->popup("edit", "RegID-Zugangsdaten", "LoginData", $LoginData, "getPopup", "", "LoginDataGUI;preset:regID");
			$BS->onclick("");
			
			$ST->addRow($BM);
		}
		
		$ST->addRow("");
		
		
		if(Session::isPluginLoaded("mLastschrift")){
			$BP = new Button("Zur Lastschrift\nfreigeben", "./open3A/Lastschriften/cleared.png");
			$BP->rmePCR('LastschriftListe','','markCleared', array("joinFormFieldsToString('createLastschriftForm')"), OnEvent::reload("Left"));
			
			$ST->addRow($BP);
		}
		
		$BP = new Button("Als übermittelt\nmarkieren", "./open3A/Uebersicht/inAuftrag.png");
		$BP->rmePCR('LastschriftListe','','markTransmitted', array("joinFormFieldsToString('createLastschriftForm')"), OnEvent::reload("Left"));

		$ST->addRow($BP);
		
		$ST->addRow("");
		
		$BP = new Button("Als bezahlt\nmarkieren", "okCatch");
		$BP->rmePCR('LastschriftListe','','markPayed', array("joinFormFieldsToString('createLastschriftForm')"), OnEvent::reload("Left"));
		$BP->doBefore("if(confirm('Die ausgewählten Belege als bezahlt markieren?')) %AFTER");
		$ST->addRow($BP);
			
		#$T2->addRow($BP);
		#$T2->addRowColspan(1,3);
		
		return $ST."<form id=\"createLastschriftForm\">".$T.$T2."</form>";
	}

	public function markPayed($data){
		parse_str($data, $pdata);

		$i = 0;

		foreach($pdata AS $k => $v){
			if($v == "0" OR $k == "toggleAll")
				continue;

			$GRLBMID = str_replace("ID", "", $k);

			if(strpos($GRLBMID, "_") !== false){
				$ex = explode("_", $GRLBMID);
				
				$G = new Zahlungsaufforderung($ex[1], false);
				$G->setPayed(time());
				
			} else {
				$G = new GRLBM($GRLBMID);
				$G->setPayed("true", "0,00", Util::CLDateParser(time()));
			}
			
			$i++;
		}

		if($i == 1)
			Red::messageD("$i Rechnung wurde als bezahlt markiert");
		
		Red::messageD("$i Rechnungen wurden als bezahlt markiert");
	}

	

	public function markTransmitted($data){
		parse_str($data, $pdata);

		$i = 0;

		foreach($pdata AS $k => $v){
			if($v == "0" OR $k == "toggleAll")
				continue;

			$GRLBMID = str_replace("ID", "", $k);
			if(strpos($GRLBMID, "_") !== false){
				$ex = explode("_", $GRLBMID);
				$G = new Zahlungsaufforderung($ex[1], false);
				$G->changeA("ZahlungsaufforderungSEPATransmitted", time());
				$G->saveMe();
				
			} else {
				$G = new GRLBM($GRLBMID, false);
				$G->changeA("GRLBMSEPATransmitted", time());
				$G->saveMe();
			}
			$i++;
		}

		if($i == 1)
			Red::messageD("$i Rechnung wurde als übermittelt markiert");
		
		Red::messageD("$i Rechnungen wurden als übermittelt markiert");
	}
	
	public function unmarkCleared($GRLBMID){
		if(strpos($GRLBMID, "_") !== false){
			$ex = explode("_", $GRLBMID);
			$G = new Zahlungsaufforderung($ex[1], false);
			$G->changeA("ZahlungsaufforderungSEPATransmitted", 0);
			$G->saveMe();
			
			return;
		}
				
		$G = new GRLBM($GRLBMID, false);
		$G->changeA("GRLBMSEPATransmitted", 0);
		$G->saveMe();
	}
	
	public function markCleared($data){
		parse_str($data, $pdata);

		$i = 0;

		foreach($pdata AS $k => $v){
			if($v == "0" OR $k == "toggleAll")
				continue;

			$GRLBMID = str_replace("ID", "", $k);

			if(strpos($GRLBMID, "_") !== false){
				$ex = explode("_", $GRLBMID);
				$G = new Zahlungsaufforderung($ex[1], false);
				$G->changeA("ZahlungsaufforderungSEPATransmitted", time() * -1);
				$G->saveMe();
				
			} else {
				$G = new GRLBM($GRLBMID, false);
				$G->changeA("GRLBMSEPATransmitted", time() * -1);
				$G->saveMe();
			}
			
			$i++;
		}

		if($i == 1)
			Red::messageD("$i Rechnung wurde freigegeben");
		
		Red::messageD("$i Rechnungen wurden freigegeben");
	}
	
	
	public function createLastschrift($mode, $data){
		parse_str($data, $pdata);

		$ndata = array();

		foreach($pdata AS $k => $v){
			if($v == "0")
				continue;
			
			if($k == "toggleAll")
				continue;
			
			$ndata[] = str_replace("ID","",$k);
		}

		if(count($ndata) == 0)
			die(Util::getBasicHTMLError("Keine Rechnungen ausgewählt", "SEPA"));
		
		
		$AC = $this->getInterestingData($ndata, $mode == "SEPAReport");
		$orderMode = mUserdata::getUDValueS("SEPAZahlungsziel", "min");
		$days = 14;#mUserdata::getUDValueS("maxDaysUnpayedBeforeRed", 14);
		$minDays = mUserdata::getUDValueS("SEPAZahlungszielMin", "2");
		$type = mUserdata::getUDValueS("SEPAArt", "COR1");
		
		$AC->lCV3();
		if($AC->numLoaded() == 0)
			die(Util::getBasicHTMLError("Keine Rechnungen ausgewählt", "SEPA"));
		
		#if($mode == "SEPABasisLastschrift" OR $mode == "SEPAReport" OR $mode == "SEPAFirmenLastschrift"){
		$s = Stammdaten::getActiveStammdaten();

		$sepaDD = new SEPADirectDebitBasic(array(
			'messageID' => time(),
			'paymentID' => time()
		));

		if($mode == "SEPAFirmenLastschrift")
			$sepaDD = new SEPADirectDebitBusiness(array(
				'messageID' => time(),
				'paymentID' => time()
			));


		$sepaDD->setCreditor($this->getCreditor($s));

		
		while($k = $AC->getNextEntry()){
			if($k->A("bruttobetrag") * 1 == 0)
				continue;

			$D = $this->getDebitor($k, $orderMode, $days, $minDays, $type);

			Aspect::joinPoint("alterDebitor", $this, __METHOD__, array($D));

			$sepaDD->addDebitor($D);
		}

		
		if($mode == "SEPABasisLastschrift" OR $mode == "SEPAFirmenLastschrift"){
			try {
				$xml = $sepaDD->toXML(mUserdata::getUDValueS("SEPAPainFormat", $this->defaultPain));

				header("Content-Type: application/xml");
				header("Content-Disposition: attachment; filename=\"{$mode}_".date("Y.m.d").".xml\"");
				header('Content-Length: '.strlen($xml));

				echo $xml;
				exit();
			} catch (Exception $e){
				echo "<p>".$sepaDD->errors()."</p>";
			}
		}

		if($mode == "SEPAReport"){
			Util::showPDF($sepaDD, "getReportData");
			die();
		}
	}

	public function getContextMenuHTML($identifier) {
		switch($identifier){
			case "SEPA":
				$gui = new HTMLGUI();
				$selectedKey = mUserdata::getUDValueS("SEPAZahlungsziel", "min");
				
				$kAL = array();
				$kAL["min"] = "Minimal (s.u.)";
				$kAL["default"] = "Standard (14 Tage)";
				
				echo "<div style=\"margin:1px;padding:3px;font-weight:bold;\" class=\"backgroundColor2\">Zahlungsziel:</div>";
				echo $gui->getContextMenu($kAL, "LastschriftListe", "SEPA", $selectedKey);
				
				#$gui = new HTMLGUI();
				$selectedKey = mUserdata::getUDValueS("SEPAZahlungszielMin", "2");
				
				$kAL = array();
				$kAL["2"] = "2 Werktage";
				$kAL["3"] = "3 Werktage";
				$kAL["4"] = "4 Werktage";
				$kAL["8"] = "8 Werktage";
				
				echo "<div style=\"margin:1px;padding:3px;font-weight:bold;\" class=\"backgroundColor2\">Minimal:</div>";
				echo $gui->getContextMenu($kAL, "LastschriftListe", "SEPAMin", $selectedKey);
				
				
				$selectedKey = mUserdata::getUDValueS("SEPAArt", "COR1");
				
				$kAL = array();
				$kAL["COR1"] = "Eillastschrift";
				$kAL["CORE"] = "Standard";
				
				echo "<div style=\"margin:1px;margin-top:10px;padding:3px;font-weight:bold;\" class=\"backgroundColor2\">Art:</div>";
				echo $gui->getContextMenu($kAL, "LastschriftListe", "SEPAArt", $selectedKey);
				
				$selectedKey = mUserdata::getUDValueS("SEPAPainFormat", $this->defaultPain);
				
				$kAL = array();
				$kAL["pain.008.003.02"] = "pain.008.003.02";
				$kAL["pain.008.001.02"] = "pain.008.001.02";
				
				echo "<div style=\"margin:1px;margin-top:10px;padding:3px;font-weight:bold;\" class=\"backgroundColor2\">pain-Format:</div>";
				echo $gui->getContextMenu($kAL, "LastschriftListe", "SEPAPainFormat", $selectedKey);
			break;
		}
	}
	
	public function saveContextMenu($identifier, $key){
		$ud = new mUserdata();
		
		if($identifier == "SEPA")
			$ud->setUserdata("SEPAZahlungsziel",$key);
		
		if($identifier == "SEPAMin")
			$ud->setUserdata("SEPAZahlungszielMin",$key);
		
		if($identifier == "SEPAArt")
			$ud->setUserdata("SEPAArt",$key);
		
		if($identifier == "SEPAPainFormat")
			$ud->setUserdata("SEPAPainFormat",$key);
	}

}
?>
