<?php
ob_start();
session_start();

if ($_GET['lst']=='1'){
	$file = "Antrag.pdf";
	header('Content-Disposition: attachment; filename="'. $file . '"');
	header('Content-Length: ' . strlen($_SESSION['lst']));
	
	echo $_SESSION['lst'];

	die;
}
?>

<html>
<head>
	<title>Kostenerstattungsforumlar</title>
	<meta charset="utf-8">
	
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<!-- Kube CSS -->
	<link rel="stylesheet" href="css/kube.min.css">
	<link rel="stylesheet" href="addons/kube-addons.min.css" />

	<link rel="stylesheet" href="master.css" />

</head>
<body>
<?php

error_log("SUBMIT\n");

require "config.php";
require "PHPMailer/PHPMailer.php";
require "PHPMailer/SMTP.php";
require "PHPMailer/Exception.php";



#$CONVERT_CMD = "/usr/bin/pdftk";

require_once('TCPDF/tcpdf.php');

class kaformPDF extends TCPDF {
	//Page header
	public function Header() {
	}

	// Logo
	// $image_file = K_PATH_IMAGES.'logo_example.jpg';
	// $this->Image($image_file, 10, 10, 15, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
	// // Set font
	// $this->SetFont('helvetica', 'B', 20);
	// // Title
	// $this->Cell(0, 15, '<< TCPDF Example 003 >>', 0, false, 'C', 0, '', 0, false, 'M', 'M');
	// }
	
	//  Page footer
	public function Footer() {
	}
	// Position at 15 mm from bottom
	// $this->SetY(-15);
	// Set font
	// $this->SetFont('helvetica', 'I', 8);
	// Page number
	//  $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
	//  }
	//  }
	//                                                           
};


function get_adv()
{
	$aval = $_POST['advance'];
	if (!$aval)
		$aval = "0";
	$advance = floatval(str_replace(",",".",$aval));
	if ($advance < 0 )
		$advance = -$advance;	
	return $advance;
}

function mkFrontPDF(){
	$comments = str_replace("\n","<BR>",$_POST['comments']);
	$bankaddress = str_replace("\n","<BR>",$_POST['n_bankaddress']);
	$address = str_replace("\n","<BR>",$_POST['n_address']);

#	$aval = $_POST['advance'];
#	$advance = floatval(str_replace(",",".",$aval));

	$aw = $_POST;

	switch ($_POST['banktype']){

	case "bank-eu":
		$account_owner = $_POST['sepa_owner'];
		if (!$account_owner) $account_owner = $_POST['realname'];

		$aw = "EU-Bank&uuml;berweisung";
		$aw_details = "
		Kontoinhaber: $account_owner<br>
		IBAN: $_POST[iban]<br>
		BIC: $_POST[bic]<br>
		Anmerkungen:<br> $comments<br>
		";
		break;
	case "bank-noneu":
		$account_owner = $_POST['non_sepa_owner'];
		if (!$account_owner) $account_owner = $_POST['realname'];
		$aw = "Non-EU-Bank&uuml;berweisung";
		$aw_details = "
		Kontoinhaber: $account_owner<br>
		Kontonummer: $_POST[n_iban]<br>
		BIC/SWIFT: $_POST[n_bic]<br>
		Bank: $_POST[n_ankname]<br><br>
		Bankanschrift:<br>$bankaddress<br><br>
		Anschrift des Empf&auml;ngers:<br>$address<br><br>
		Verwendungszweck:<br> $_POST[n_purpose]<br>
		Anmerkungen:<br> $comments<br>
		";			
		break;
	case "bank-paypal":
		$aw = "PayPal";
		$aw_details = "PayPal Account:";

	}


	$thtml = mkTable();

	
	// create new PDF document
	$pdf = new kaformPDF(
		PDF_PAGE_ORIENTATION, PDF_UNIT, $pageLayout /*PDF_PAGE_FORMAT*/, 
		true, 'UTF-8', false);

	// set document information
/*	$pdf->SetCreator(PDF_CREATOR);
	$pdf->SetAuthor('Nicola Asuni');
	$pdf->SetTitle('TCPDF Example 001');
	$pdf->SetSubject('TCPDF Tutorial');
	$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
 */
	// set default header data
//	$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 
	//	PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, 
//		array(0,64,255), array(0,64,128));

//	$pdf->setFooterData(array(0,64,0), array(0,64,128));

	// set header and footer fonts
	$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
	$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

	// set default monospaced font
	$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

	// set margins
	$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
	$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
	$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

	// set auto page breaks
	$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

	// set image scale factor
	$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

	// set some language-dependent strings (optional)
	if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
		require_once(dirname(__FILE__).'/lang/eng.php');
		$pdf->setLanguageArray($l);
	}

	// ---------------------------------------------------------

	// set default font subsetting mode
	$pdf->setFontSubsetting(true);

	// Set font
	// dejavusans is a UTF-8 Unicode font, if you only need to
	// print standard ASCII chars, you can use core fonts like
	// helvetica or times to reduce file size.
	$pdf->SetFont('dejavusans', '', 14, '', true);

	// Add a page
	// This method has several options, check the source code 
	// documentation for more information.
	$pdf->AddPage('P');

	// set text shadow effect
	$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 
		'depth_h'=>0.2, 'color'=>array(196,196,196), 
		'opacity'=>1, 'blend_mode'=>'Normal'));

	// calculate the overall summary
	$sum = calcSum();

	// Set some content to print
	$html = 
<<<EOD
	<h1>Kostenerstattungsantrag &uuml;ber $sum $_POST[currency]</h1>
	<p><b>Projekt: $_POST[project]</b></p>
	<hr>
	<p>
	&nbsp;
	<br>
<!--	Nickname: $_POST[nickname]<br> -->
	Name: $_POST[realname]<br>
	Telefon: $_POST[phone]<br>
	E-Mail: $_POST[email]<br>
	Ansprechpartner: $_POST[wmdecontact]<br>
	</p>
	<hr>
	<br>
	<p>
	Auszahlungsweg: $aw<br>
	$aw_details
	</p>
	<hr>
	$thtml
	
	

EOD;

	// Print text using writeHTMLCell()
	$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);

	// ---------------------------------------------------------
	$tn = tempnam("/tmp","kaform");

	// Close and output PDF document
	// This method has several options, check the source code 
	// documentation for more information.
	$pdf->Output($tn, 'F');
	return $tn;

}

function mkSnippedPdf($key){
	$pageLayout = array(210,70);
	
	// create new PDF document
#	$pdf = new kaformPDF(
#		PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, 
#		true, 'UTF-8', false);

	$pdf = new kaformPDF(
		PDF_PAGE_ORIENTATION, PDF_UNIT, $pageLayout /*PDF_PAGE_FORMAT*/, 
		true, 'UTF-8', false);



	$pdf->AddPage('L');

	$pos = array_search($key,array_keys($_POST['desc']))+1;



//	echo "<br>Make Snipped for $key -> $pos<br>";

	#	$mydesk = $_POST[desc][$key];
	#
	$amount = $_POST['amount'][$key];
	$desc = $_POST['desc'][$key];

	$am = floatval(str_replace(",",".",$amount));
	$am =  str_replace(".",",",sprintf("%.2f",$am));


	$html = 
<<<EOD
	
	<h1>Position $pos</h1>
	<p>$desc</p><br>
	<p>$am $_POST[currency]</p><br>
EOD;
	
	// Print text using writeHTMLCell()
	$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);

	$tn = tempnam("/tmp","kaform");

	// Close and output PDF document
	// This method has several options, check the source code 
	// documentation for more information.
	$pdf->Output("$tn", 'F');
	return $tn;
}



//var_dump($_POST);
function convert($row) {
	$r = array();
	foreach ($_SESSION['files'] as $filename => $file){
		if ($file['row'] != $row)
			continue;

		$tn = tempnam("/tmp","kaform");
		file_put_contents("$tn",$file['content']);
		array_push($r,"$tn");
	}
	return $r;
}


function calcSum(){
	$sum =0;
	if (!isset($_POST['amount'])) {
		echo "wrong parameters";
		die;
	}

	foreach ($_POST['amount'] as $val){
//		var_dump($val);
		$sum += floatval(str_replace(",",".",$val));
		
	}
	$sum -= get_adv();
	return str_replace(".",",",sprintf("%0.2f",$sum));
}


function mkTable(){
	$html = "<br>&nbsp;<br><table>";
	$pos = 1;
	$sum =0;
	if (!isset($_POST['amount'])) {
		echo "wrong parameters";
		die;
	}



	foreach ($_POST['amount'] as $key=>$val){
		$html .='<tr>';
		
		$html .= "<td>$pos</td>";

		$html .= "<td>".$_POST['date'][$key]."</td>";
		$html .= "<td>".$_POST['desc'][$key]."</td>";
		$am = floatval(str_replace(",",".",$val));
		$am =  str_replace(".",",",sprintf("%.2f",$am));
		$html .= '<td align="right">'.$am." ".$_POST['currency']. "</td>";
		

		$html .="</tr>";



		$sum += floatval(str_replace(",",".",$val));
		$pos ++;
	}

	$adv = get_adv();
	if ($adv) {
		$html .= "<tr>";
		$html .= '<td colspan="3">';
		$html .= "Bereits erhaltener Vorschuss:";
		$html .= '</td>';
		$html .= '<td align="right">';
		$html .= sprintf("-%0.2f",$adv)." ".$_POST['currency'];
		$html .= '</td>';
		$html .= "</tr>";

	}

	$html .= '<tr>';
	$html .= '<td colspan="3">';
	$html .= "<b>Summe:</b>";
	$html .= '</td>';
	$html .= '<td align="right">';
	$html .= "<b>".calcSum()." ".$_POST['currency']."</b>";
	$html .= '</td>';
	$html .= '</tr>';

	$html .= "</table>";
#	$html .="<br>&nbsp;<br>";
#	$html .="<b>Summe: ".calcSum()."</b>";
	return $html;

//	return str_replace(".",",",sprintf("%0.2f",$sum));
//	return sprintf("%.2f",$sum);

}


$pdfs = array();

error_log("Making Front PDF");

//
// Applicatoin starts here
//
$p = mkFrontPDF();

$file = $p;
#header('Content-Disposition: attachment; filename="'. basename($file) . '"');
#header('Content-Length: ' . filesize($file));
#readfile($file);


array_push($pdfs,$p);

foreach ($_POST['desc'] as $key => $val) {
//	echo "DREESK KEY VAL $key --> $val<br>";
	$p = mkSnippedPDF($key);
	array_push($pdfs,$p);

	$pr = convert($key);
	$pdfs = array_merge($pdfs,$pr);

}

//var_dump($pdfs);
//
$resultnam = tempnam("/tmp","karesult");



$cmd = "$PDFTK_CMD";
foreach ($pdfs as $filename){
	$cmd .= " $filename";
}
$cmd .= " cat output $resultnam.pdf";

error_log("EXEC CMD $cmd");
exec ($cmd);

$file = "$resultnam.pdf";

if ($_POST['sendmail']=='yes'){
	$subj = "Kostenerstattungsantrag ueber ".calcSum()." ".$_POST['currency'];	


	$mail = new PHPMailer\PHPMailer\PHPMailer();
	$mail->SMTPOptions = array(
	        'ssl' => array(
		        'verify_peer' => false,
	       		'verify_peer_name' => false,
		        'allow_self_signed' => true
   		 )
	);

	$mail->IsSMTP();	
	$mail->setFrom($mailFrom);
	$mail->Subject = $subj;
	$mail->addCustomHeader('Auto-Submitted', 'auto-generated'); // comply to RFC 3834 (https://www.iana.org/assignments/auto-submitted-keywords/auto-submitted-keywords.xhtml)
	$mail->Body = "Kostenerstattungsantrag ...";
	$mail->AddAddress($mailDest);
	if ($mailDestCC) {
		$mail->AddCC($mailDestCC);
	}
	$mail->AddAttachment( $file , 'antrag.pdf' );

	$mail->Host = $mailHost;                 // Specify main and backup server
	$mail->Port = $mailPort;                                     // Set the SMTP port
	$mail->SMTPAuth = $mailSMTPAuth;
	$mail->Username = $mailUsername;
	$mail->Password = $mailPassword;
	$mail->SMTPSecure = $mailSMTPSecure;                            // Enable encryption, 'ssl' also accepted
	$rc = 	$mail->send();
	if (!$rc) {
		echo 'Mailer Error: ' . $mail->ErrorInfo;
		die;
	}


	echo "Dein Antrag wurde versendet.<BR>";
?>

<!--	<div class="is-col">
		<button type="button" onclick="downloadDocument(false);"
		class="button is-orange"><?=_("Kopie des Antrags herunterladen")?></button>
	</div> -->
<?php
	echo '<a href="./submit.php?lst=1" target="_blank">Kopie des Antrags herunterladen</a>';
	echo "<br>";
	echo '<a href="./">
	Weiteren Antrag auf Kostenerstattung stellen</a><BR>';

	$_SESSION['lst']=file_get_contents("$resultnam.pdf");
	session_write_close();

	die;


}

$file = "$resultnam.pdf";
header('Content-Disposition: attachment; filename="'. basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);

?>
	<script src="js/kube.min.js"></script>
	<script src="kaform.js"></script>
	<script src="addons/upload/kube.upload.min.js"></script>
	<script src="addons/kube-addons.min.js"></script>
	<script src="iban.js/iban.js"></script>


</body>
</html>