<?php
//add mz 2014-12-30
//check session variable
global $current_user;
//toEmail?
$session_key = $current_user->id."_EcmInvoiceOuts_toEmail";
if (isset($_SESSION[$session_key])) {
	$_REQUEST['record'] = $_SESSION[$session_key];
	unset($_SESSION[$session_key]);
	$toEmail = true;
}
unset($session_key);
//toMultiPdf?
$session_key = $current_user->id."_EcmInvoiceOuts_toMultiPdf";
if (isset($_SESSION[$session_key])) {
	$_REQUEST['record'] = $_SESSION[$session_key];
	unset($_SESSION[$session_key]);
	$toMultiPdf = true;
}
unset($session_key);

if (! $_REQUEST ['record'] || $_REQUEST ['record'] == '')
	die ( 'Brak rekordu' );
else
	$record = $_REQUEST ['record'];

include_once ("modules/EcmInvoiceOuts/PDFTemplate/helper.php");

$focus = new EcmInvoiceOut ();
$focus->retrieve ( $record );

$user = new User ();
$user->retrieve ( $focus->assigned_user_id );
$labels = return_module_language($focus->ecmlanguage, 'EcmInvoiceOuts');
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 30, 45, 5, 5 );
$mpdf->mirrorMargins = 1;

$db = $GLOBALS ['db'];
// document pdf
// document already exist?

$res = $db->query ( "SELECT footer, content FROM ecminvoiceout_pdf WHERE id='$record'" );
if ($res->num_rows == 0) {
	// create and save document
	$positions = formatPDFPositions ( $focus->getPositionList ( true ), $focus );
	// get header
	$header = '';
	include_once ("modules/EcmInvoiceOuts/PDFTemplate/header.php");
	$content = '';
	include_once ("modules/EcmInvoiceOuts/PDFTemplate/content.php");
	
	global $current_user,$app_list_strings;
	
	$db->query ( "INSERT INTO ecminvoiceout_pdf VALUES ('$record','$current_user->id', NOW(),'" . urlencode ( $header ) . "', '" . urlencode( $content ) . "','')" );
} else {
	$row = $db->fetchByAssoc ( $res );
	$header = urldecode ( $row ['footer'] ); // punk rock!
	$content = urldecode ( $row ['content'] );
}
//var_dump($positions);
$p->SetHTMLHeader ( $header );
$footer='<hr><table style="font-size: 8pt; width: 100%;vertical-align:top;">
		<tr><td width="25%">Saas SystemS Sp. z o.o.<br />
		ul. Lipnowska 21-23<br />
		87-100 Toruń<br />
		NIP: 9562307719</td><td width="25%"></td><td width="20%">Bank: <br>Numer konta:</td><td>PKO BP<br> 53 1020 5011 0000 9002 0270 6323</td></tr></table>';
$p->SetHTMLFooter($footer);
$p->WriteHTML ( $content );
//echo $content;
// draw PDF
if ($toEmail) {
	include_once 'include/ECM/EcmSendMail/EcmSendMail.inc';
	$p->Output (EcmSendMail::TEMP_DIR.'FV_'.$focus->number.'.pdf',"F");
	return;
}
if ($toMultiPdf) {
	include_once 'include/ECM/EcmMultiPdf/EcmMultiPdf.inc';
	$p->Output (EcmMultiPdf::TEMP_DIR.'EcmInvoiceOuts_'.$focus->id.'.pdf',"F");
	return;
}

if($_REQUEST['file']){
    $p->Output ('upload/fk_'.$focus->number.'.pdf',"F");
} else {
    $p->Output ();
}
