<?php
global $current_user;
if ($current_user->id == '4965a9d3419a3f09b5e2d4135e664700') {
	//ini_set('display_errors',1);
}
if ($_REQUEST['createBlob']) {
	$type = 'BLOB';
} else {
	$type = isset($_REQUEST['file']) ? 'FILE' : 'BROSWER';
}
if ($_REQUEST['action'] == 'createPDF') {

	$EcmSysInfo = new EcmSysInfo();
	if ($EcmSysInfo->getDatabaseName() == 'preDb_60b08fe051546309b61d2714d4a0438d') {
		newPDFCreator($_REQUEST['record'], $type);
		return;
	}

	if ($EcmSysInfo->getDatabaseName() == 'preDb_8a7e080a76ef97c3e304cf463118ef9b') {
		$EcmInvoiceOut = new EcmInvoiceOut();
		$EcmInvoiceOut->retrieve($_GET['record']);

		header("Location: " . $EcmInvoiceOut->get_PDF_file_path($_REQUEST['pdf_type']));
		return;
	}

	if ($EcmSysInfo->getDatabaseName() == 'preDb_0dcc87940d3655fa574b253df04ca1c3') {
		$EcmInvoiceOut = new EcmInvoiceOut();
		$EcmInvoiceOut->retrieve($_GET['record']);

		if ($EcmInvoiceOut->pdf_type != 'K' && $EcmInvoiceOut->ecmlanguage == 'en_us' && $EcmInvoiceOut->type == 'normal') {

			createEngFv($EcmInvoiceOut);
		}
	}

	createEcmInvoiceOutPdf($_REQUEST['record'], $type);
}

function newPDFCreator($record, $outputtype, $save = null)
{
	if ($record == '') {
		echo "Brak rekordu";
	}

	//Sprawdzamy czy katalog istneje jak nie to tworzymy
	$EcmSysInfo = new EcmSysInfo();
	$dir = 'upload/' . $EcmSysInfo->getDatabaseName() . '/pdf/EcmInvoiceOuts/';
	if (!is_dir($dir)) {
		mkdir($dir, '755', true);
	}
	//Pobieramy fakturke z bazy
	$EcmInvoiceOut = new EcmInvoiceOut();
	$EcmInvoiceOut->retrieve($record);

	// Tworzymy nazwe pliku
	$data_array = explode(".", $EcmInvoiceOut->register_date);
	$prefix = "FK";
	$infix = $data_array[2] . $data_array[1] . $data_array[0];
	$suffix = str_replace('/', '', (str_replace(' ', '', $EcmInvoiceOut->document_no)));


	$file_name = $prefix . "_" . $infix . "_" . $suffix . '.pdf';

	//Sprawdzam czy pdf juz istnieje
	if (file_exists($dir . $file_name) && $save == null) {
		header("Location: " . $file_location);
		return;
	}
	// jak nie to tworzmy : )
	include_once("include/MPDF57/mpdf.php");

	if (file_exists('custom/' . $EcmSysInfo->getDatabaseName() . '/pdf_teplate/EcmInviceoutContent.tpl')) {
		if ($EcmInvoiceOut->type == 'normal') {
			global $mod_strings, $app_list_strings;
			include_once("modules/EcmKpkw/PDFTemplate/kwota.php");
			$kwota = new KwotaSlownie();

			$slownieKwota = $kwota->convertPrice(floatval($EcmInvoiceOut->total_brutto));
			$EcmInvoiceOut->position_list = $EcmInvoiceOut->getPositionList(true);
			$vats_array = explode(",", $EcmInvoiceOut->vats_summary);

			foreach ($vats_array as $key => $value) {
				if ($value == "") {
					unset($vats_array[$key]);
					continue;
				}
				$vats_array[$key] = explode(":", $value);
			}

			$EcmInvoiceOut->vats_summary = $vats_array;

			$tmp = explode(".", $EcmInvoiceOut->register_date);
			$EcmInvoiceOut->register_date = $tmp[2] . "-" . $tmp[1] . "-" . $tmp[0];

			$tmp = explode(".", $EcmInvoiceOut->sell_date);
			$EcmInvoiceOut->sell_date = $tmp[2] . "-" . $tmp[1] . "-" . $tmp[0];

			$smarty = new Sugar_Smarty();

			if ($_REQUEST['pdf_type'] == '1') {
				$duplikat = "<br>Duplikat wystawiony dnia: <b>" . date('d.m.Y') . '</b>';
				$smarty->assign("duplikat", $duplikat);
			}

			$smarty->assign("MOD", $mod_strings);
			$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
			$smarty->assign("DATA", $data);
			$smarty->assign("EcmSysInfo", $EcmSysInfo);
			$smarty->assign("EcmInvoiceOut", $EcmInvoiceOut);
			$smarty->assign("slownieKwota", $slownieKwota);
			$content = $smarty->fetch('custom/' . $EcmSysInfo->getDatabaseName() . '/pdf_teplate/EcmInviceoutContent.tpl');

			$mPDF = new mPDF('pl', 'A4', 9, 'arial',  10, 10, 125, 20, 14, 20);
			$mPDF->setAutoTopMargi = 'stretch';
			$mPDF->setAutoBottomMargin = 'stretch';
			$mPDF->mirrorMargins = 1;
			$mPDF->WriteHTML($content);
			//echo $content;
			if ($save == true) {
				$mPDF->Output($file_name, "F");
				return $file_name;
			} else {
				$mPDF->Output($file_name, "I");
			}
		} else {

			createEcmInvoiceOutPdf($record, $outputtype);
		}
	} else {
	}


	/*	foreach($EcmInvoiceOut as $key => $val){
		echo $key . '<Br>';
		var_dump($val);
		echo '<Br><Br>';
	}*/
}

function createEcmInvoiceOutPdf($record, $outputtype)
{
	$EcmInvoiceOut = new EcmInvoiceOut();
	$EcmInvoiceOut->retrieve($record);
	var_dump($record);
	$file_location = $EcmInvoiceOut->get_PDF_file_path($_REQUEST['pdf_type']);
	$EcmSysInfo = new EcmSysInfo();
	/*
	if($EcmSysInfo->getDatabaseName() == 'preDb_60b08fe051546309b61d2714d4a0438d'){
		$file_location=newPDFCreator($record, $type,true);
	} */
	//	return;
	switch ($outputtype) {
		case "BROSWER":
			header("Location: " . $file_location);
			return true;
		case "FILE":
			$path = $file_location;
			break;
		case "EMAIL":
			include_once 'include/ECM/EcmSendMail/EcmSendMail.inc';
			$path = EcmSendMail::TEMP_DIR . 'ZS_' . $EcmInvoiceOut->number . '.pdf';
			//$path=EcmSendMail::$file_location;
			copy($file_location, $path);
			break;
		case "MULTIPDF":
			include_once 'include/ECM/EcmMultiPdf/EcmMultiPdf.inc';
			$path = EcmMultiPdf::TEMP_DIR . 'EcmSales_' . $focus->id . '_' . create_guid() . '.pdf';
			copy($file_location, $path);
			break;
		case "BLOB":
			var_dump($file_location);
			$pdfData = file_get_contents($file_location);
			var_dump($pdfData);
			break;
	};
	return $file_location;
}

function createEngFv($focus)
{

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

	$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?
	$recipient_code = 0;
	foreach ($focus->getPositionList(true) as $k => $v) {
		if ($v['recipient_code'] != '') {
			$recipient_code = 1;
		}
	}
	$recipient_code;
	$res = $db->query("SELECT footer, content, header FROM ecminvoiceout_pdf WHERE id='$record'");
	if ($res->num_rows == 0) {
		// create and save document
		$positions = formatPDFPositionsEng($focus->getPositionList(true), $focus);
		$header = '';
		$footer = '';
		$content = '';
		include_once("modules/EcmInvoiceOuts/PDFTemplate/tpl/header_en.php");
		include_once("modules/EcmInvoiceOuts/PDFTemplate/tpl/content_en.php");
		include_once("modules/EcmInvoiceOuts/PDFTemplate/tpl/footer-en_us.php");

		global $current_user, $app_list_strings;

		$db->query("INSERT INTO ecminvoiceout_pdf VALUES ('$record','$current_user->id', NOW(),'" . urlencode($footer) . "', '" . urlencode($content) . "', '" . urlencode($header) . "')");
	} else {
		$row = $db->fetchByAssoc($res);
		$footer = urldecode($row['footer']);
		$header = urldecode($row['header']);
		$content = urldecode($row['content']);
	}

	$p->SetHTMLHeader($header);
	$p->SetHTMLFooter($footer);
	$p->WriteHTML($content);
	//echo $content;
	// draw PDF
	$filename = str_replace(" ", "_", str_replace("/", "_", $focus->document_no));
	$p->Output($filename . '.pdf', 'I');
	die();
}
