<?php
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 *
 *
 *   73: class InvoicePDF extends PDF
 *   84:     function init($x=12, $y=15)
 *  103:     function Header()
 *  115:     function preHeaderOfTheInvoice()
 *  128:     function headerOfTheInvoice($y_offset=24.5)
 *  278:     function printTableHeader()
 *  317:     function printTableBody()
 *  460:     function printTableFooter()
 *  573:     function printAdditionalInfo($offset)
 *  594:     function printShipmentCost($y0, $x0, $i)
 *  694:     function printLeaflet()
 *  838:     function fillBlankLeaflet($x0, $y0)
 * 1010:     function printWatermark()
 * 1033:     function acceptPageBreak()
 *
 *              SECTION: Helper functions
 * 1053:     function printTotalInWords($h, $x0, $y0)
 * 1094:     function printInTheLine($str, $x, $y)
 * 1113:     function printLoyaltyDiscount()
 * 1113:     function printRedemtionsDiscount()
 * 1144:     function invoiceNumberFormat($amount, $dig = 2, $dec = ',', $sep = ' ')
 * 1160:     function getMaxArticlesName($name)
 *
 *              SECTION: Setting and getting functions
 * 1187:     function getPaymentTitle()
 * 1233:     function setPaymentPeriod($days='0')
 * 1245:     function getPaymentPeriod()
 * 1261:     function setOrderId($order_id)
 * 1273:     function getOrderId()
 * 1288:     function setInvoiceNr($invoice_nr='')
 * 1348:     function getInvoiceNr()
 * 1373:     function setInvoiceDate($invoice_date='')
 * 1430:     function getInvoiceDate()
 * 1445:     function getData($key)
 * 1457:     function setData($key, $value)
 * 1472:     function setFaksymileImage($faksymile_file, $faksymile_x, $faksymile_y, $faksymile_width=0, $faksymile_height=0)
 * 1486:     function getFaksymileImage()
 * 1509:     function setLogoImage($logo_file, $logo_x, $logo_y, $logo_width, $logo_height)
 * 1523:     function getLogoImage()
 *
 * TOTAL FUNCTIONS: 35
 *
 */

require('pdf/fpdf/pdf.php');
require_once(DIR_WS_CLASSES . 'order.php');
require_once(DIR_WS_CLASSES . 'currencies.php');

define('DIR_WS_ADMIN', 'administracja/'); // absolute path required

define('DIR_WS_ADMIN', 'administracja/'); // absolute path required
define('DIR_FS_ADMIN', DIR_FS_CATALOG.'administracja/'); // absolute pate required

define('DUPLIKAT', 4);
define('PROFORMA', 3);
define('COP', 2);
define('ORYGINAL', 1);

class InvoicePDF extends PDF {
	var $data;


	/**
	 * Add the some fonts
	 *
	 * @param	[type]		$x: ...
	 * @param	[type]		$y: ...
	 * @return	void
	 */
	function init($x=12, $y=15) {
		// If an invoice type equals DUPLIKAT and an order
		// hasn't got the invoice nr this script ends its job.
		// A DUPLIKAT invoice is allowed if an ORYGINAL invoice exists.
		if (DUPLIKAT == intval($_GET['type']) ) {
			$res = tep_db_query('SELECT invoice_nr FROM ' . TABLE_ORDERS . '  WHERE orders_id=' . intval($_GET['oID']));
			$query = tep_db_fetch_array($res);
			if ($query['invoice_nr'] == 0) {
				die('<html><head><title>Odmowa</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>
						<p><b>Admin nie wystawił oryginalnej faktury, dlatego nie można wystawić jej duplikatu!</b></p></body></html>');
			}
		}

		// Default coding of the input string is Latin2
		// Default coding of the output string is Latin2
		// Every coding has its own set gliphs for PDF documents
		// If coding changes, it needs its own set gliphs also
		// See www.fpdf.org
		if (!isset($this->data['charset_in'])) {
			$this->setData('charset_in','UTF-8');
		}
		if (!isset($this->data['charset_out'])) {
			$this->setData('charset_out', 'UTF-8');
		}

		$this->setData('currencies', new currencies());


		$this->data['x0'] = $x;
		$this->data['y0'] = $y;
		// Number of the item on which follows a page break
		// Count of the items on the first page equals 33
		// because it contains the header of the invoice and of the table
		$this->data['items_on_page'] = array(33, 73, 113, 153, 193, 233, 273, 313, 353, 393, 433, 473, 513,
                                               553, 593, 633, 673, 713, 753, 793, 833, 873, 913, 953, 993);

		$this->setData('leaflet_type', 'wplata');
		$this->setData('redemptions', 0);
		$this->setData('discount', 0);

		$this->AddFont('ArialMT', '', 'arial.php');
//		$this->AddFont('ArialMT', '', 'arialbd.php');
	}


	/**
	 * Header of the first page
	 *
	 * @return	void
	 */
	function Header() {
		$this->printWatermark();
		$this->preHeaderOfTheInvoice();
		$this->headerOfTheInvoice( $this->getData('header_top_margin') );
	}


	/**
	 * Preheader of the first page that contains the header of the invoice
	 *
	 * @return	void
	 */
	function preHeaderOfTheInvoice() {
		if (($this->PageNo() == 1) and (HEADER_IMAGE != '')) {
			$this->Image(DIR_FS_CATALOG.HEADER_IMAGE , floatval(HI_XO), floatval(HI_YO), 0, 0, 'PNG');
		}
	}


	/**
	 * Header of the first page
	 *
	 * @param	[type]		$y_offset: ...
	 * @return	void
	 */
	function headerOfTheInvoice($y_offset=24.5) {
		$a = array();

		if ($this->PageNo() == 1) {
			// Place the logo on the right place
			$a = $this->getLogoImage();
			if ($a['logo_file'] != '') {
				$this->Image(DIR_FS_CATALOG.$a['logo_file'], $a['logo_x'], $a['logo_y']);
			}

			// The border arround the logo
			$this->SetXY(12, $y_offset - 9.5);
			if ( $this->getData('border') == 'true' ) {
				$this->Cell(59, 20.5, '', 1);
			} else {
				$this->Cell(59, 20.5, '', 0);
			}

			// FAKTURA PRO FORMA or FAKTURA VAT NR?
			$this->SetXY(72, $y_offset - 9.5);
			$this->SetFont('ArialMT', '', 16);
			if ($this->data['invoice_type'] == PROFORMA) {
				$this->Cell(85, 8.5, 'FAKTURA PRO FORMA', 1, 0, 'C');
			} else {
				$this->Cell(85, 8.5, 'FAKTURA VAT NR', 1, 0, 'C');
			}

			// City and date
			$this->SetXY(72, $y_offset);
			$this->SetFont('ArialMT','', 6);
			$this->Cell(35, 5, 'Miejscowość, data:', 'LTB');
			$this->SetFont('ArialMT','', 8);
			$this->SetXY(97, $y_offset);
			$this->Cell(60, 5, MIASTO.', '.$this->getInvoiceDate(), 'TRB');

			// Sell date
			$this->SetFont('ArialMT','', 6);
			$this->SetXY(72, $y_offset + 6);
			$this->Cell(35, 5, 'Data sprzedaży/zaliczki:', 'LTB');
			$this->SetFont('ArialMT','', 8);
			$this->SetXY(97, $y_offset + 6);
			$this->Cell(20, 5, $this->getInvoiceDate(), 'TRB');

			// Client nr
			$this->SetFont('ArialMT','', 8);
			$this->SetXY(118, $y_offset + 6);
			$nr = intval($this->data['order']->customer['id']) + $this->getData('first_client_nr');
			$this->Cell(39, 5, 'Nr klienta: '.$nr, 1);

			// Invoice nr
			$this->SetFont('ArialMT','', 14);
			$this->SetXY(158, $y_offset - 9.5);
			$this->Cell(42.5, 8.5, $this->getInvoiceNr(), 1, 0, 'C');

			// Type of the invoice
			$this->SetXY(158, $y_offset - 0.5);
			$this->SetFont('ArialMT','', 14);
			$this->SetFillColor(200);
			if ($this->data['invoice_type'] == ORYGINAL) {
				$this->Cell(42.5, 6, 'ORYGINAŁ', 0, 0, 'C', 1);
			} elseif ($this->data['invoice_type'] == COP) {
				$this->Cell(42.5, 6, 'KOPIA', 0, 0, 'C', 1);
			} elseif ($this->data['invoice_type'] == PROFORMA) {
				$this->Cell(42.5, 6, 'ORYGINAŁ', 0, 0, 'C', 1);
			} elseif ($this->data['invoice_type'] == DUPLIKAT) {
				$this->Cell(42.5, 6, 'DUPLIKAT', 0, 0, 'C', 1);
			}

			// Order nr
			$this->SetFont('ArialMT','', 8);
			$this->SetXY(158, $y_offset + 6);
			$nr = $this->getOrderId() + $this->getData('first_order_nr');
			$this->Cell(42.5, 5, 'Nr zamówienia: '.$nr, 1);

			///////////////////////////// FIRMA DATA ///////////////////////////
			// A firma, a street, a zip, a city, NIP, a bank name and an account
			$this->SetFont('ArialMT','', 8);
			$this->SetXY(12, $y_offset + 12);
			$this->Cell(22, 5, 'Sprzedawca:', 'LT');
			$this->SetXY(12, $y_offset + 17);
			$this->Cell(22, 5, 'Adres:', 'L');
			$this->SetXY(12, $y_offset + 22);
			$this->Cell(22, 5, 'Kod i miejscowość:', 'L');
			$this->SetXY(12, $y_offset + 27);
			$this->Cell(22, 5, 'NIP:', 'L');
			$this->SetXY(34, $y_offset + 12);
			$this->SetFont('ArialMT','', 8);
			$this->Cell(68.5, 5, $this->getData('firma_name'), 'TR', 0, 'R');
			$this->SetXY(34, $y_offset + 17);
			$this->Cell(68.5, 5, 'ul. '.$this->getData('firma_street'), 'R', 0, 'R');
			$this->SetXY(34, $y_offset + 22);
			$this->Cell(68.5, 5, $this->getData('firma_zip').' '.$this->getData('firma_city'), 'R', 0, 'R');
			$this->SetXY(34, $y_offset + 27);
			$this->Cell(68.5, 5, $this->getData('firma_nip'), 'R', 0, 'R');
			$this->SetXY(12, $y_offset + 32);
			$this->SetFont('ArialMT','', 8);
			$this->Cell(22, 5, 'Bank:', 'L');
			$this->SetXY(12, $y_offset + 37);
			$this->Cell(22, 5, 'Nr rach. bank.:', 'LB');
			$this->SetXY(34, $y_offset + 32);
			$this->SetFont('ArialMT','', 8);
			$this->Cell(68.5, 5, $this->getData('firma_bank_name'), 'R', 0, 'R');
			$this->SetXY(34, $y_offset + 37);
			$this->Cell(68.5, 5, $this->getData('firma_account_nr'), 'BR', 0, 'R');
			$this->SetXY(103.5, $y_offset + 12.0);
			$this->SetFont('ArialMT','', 8);
			$this->Cell(17, 5, 'Nabywca:', 'LT');
			$this->SetXY(103.5, $y_offset + 17.0);
			$this->Cell(17, 1.7, '', 'L');
			$this->SetXY(103.5, $y_offset + 18.8);
			$this->Cell(17, 10, 'Adres:', 'L');
			$this->SetXY(103.5, $y_offset + 23.7);
			$this->Cell(17, 10, 'Kod i miejscowość:', 'L');
			$this->SetXY(103.5, $y_offset + 31);
			$this->Cell(17, 5, 'NIP:', 'LB');
			$this->SetXY(120.5, $y_offset + 12);
			$this->SetFont('ArialMT','', 8);

			///////////////////////////// CLIENT DATA ///////////////////////////
			// A name, a street, a city, a zip code,
			if ( tep_not_null($this->data['order']->billing['company']) ) {
				// A first string width: 80
				$strings = $this->getTwoStrings($this->data['order']->billing['company'], 80);
			} else {
				$strings = $this->getTwoStrings($this->data['order']->billing['name'], 80);
			}
			$this->Cell(80, 5, $strings[0], 'TR', 0, 'R');
			$this->SetXY(104.5, $y_offset + 17);
			$this->Cell(96, 5, $strings[1], '', 0, 'R');
			$this->SetXY(120.5, $y_offset + 17.2);
			$this->Cell(80, 4.2, '', 'R');
			$this->SetXY(120.5, $y_offset + 21.5);
			$this->Cell(80, 5, $this->data['order']->billing['street_address'], 'R', 0, 'R');
			$this->SetXY(120.5, $y_offset + 26.4);
			$this->Cell(80, 5, $this->data['order']->billing['postcode'].' '.$this->data['order']->billing['city'], 'R', 0, 'R');
			$this->SetXY(120.5, $y_offset + 31);
			$this->Cell(80, 5, $this->data['order']->billing['nip'], 'BR', 0, 'R');

			/////////////////////////////// PAYMENT /////////////////////////////
			$this->SetFont('ArialMT','', 6);
			$this->SetXY(103.5, $y_offset + 37);
			$this->Cell(48, 5, 'Forma płatności', 'T',0,'L');
			$this->SetXY(103.5, $y_offset + 37);
			$this->SetFont('ArialMT','', 6);
			$this->Cell(48, 5, substr(strip_tags($this->data['order']->info['payment_method']), 0, 28), 'LBR', 0, 'R');
			$this->SetFont('ArialMT','', 6);
			$this->SetXY(152.5, $y_offset + 37);
			$this->Cell(48, 5,'Termin płatności','T',0,'L');
			$this->SetXY(152.5, $y_offset + 37);
			$this->SetFont('ArialMT','', 6);
			$this->Cell(48, 5, $this->getPaymentPeriod(), 'LBR', 0, 'R');
		}
	}


	/**
	 * Print the header of the table
	 *
	 * @return	void
	 */
	function printTableHeader() {
			$x0 = $this->data['x0'];
			$y0 = $this->data['y0'];
			if ($this->PageNo() == 1) {
				// Below the header of the invoice
				$y0 = $this->GetY() + 6;
			}

			$this->SetFont('ArialMT','', 6);
			$this->SetXY($x0, $y0);
			$this->MultiCell(5, 14, 'Lp', 'LTB', 'C');
			$this->SetXY($x0 + 5, $y0);
			$this->MultiCell(80, 14, "Nazwa towaru lub usług", 'LTB', 'C');
			$this->SetXY($x0 + 83, $y0);
			$this->MultiCell(14.5, 7, "Symbol\nPKWiU", 'LTB', 'C');
			$this->SetXY($x0 + 97.5, $y0);
			$this->MultiCell(7, 14, 'J.m.', 'LTB', 'C');
			$this->SetXY($x0 + 104.5, $y0);
			$this->MultiCell(10, 14, 'Ilość', 'LTB', 'C');
			$this->SetXY($x0 + 114.5, $y0);
			$this->MultiCell(16, 3.5, "Cena\njednost.\nbez podatku\n           zł   gr", 'LTB', 'C');
			$this->SetXY($x0 + 130.5, $y0);
			$this->MultiCell(17, 3.5, "Wartość\ntowaru/usługi\nbez podatku\n            zł   gr", 'LTB', 'C');
			$this->SetXY($x0 + 147.5, $y0);
			$this->MultiCell(19, 4, 'Podatek', 'LTB', 'C');
			$this->SetXY($x0 + 147.5, $y0 + 4);
			$this->MultiCell(6.5, 10, '%', 'LBR', 'C');
			$this->SetXY($x0 + 154, $y0 + 4);
			$this->MultiCell(12.5, 5, "kwota\n     zł   gr", 'B', 'C');
			$this->SetXY($x0 + 166.5, $y0);
			$this->MultiCell(22, 3.5, "Wartość\ntowaru/usługi\nwraz z podatkiem\n                   zł   gr", 1, 'C');
	}


	/**
	 * Print the header of the table
	 *
	 * @return	void
	 */
	function printTableBody() {
			$x0         = $this->data['x0'];
			$tax_value  = 0;
			$netto_sum  = 0;
			$brutto_sum = 0;
			$name       = '';

			//	For debug only!
//			for ($i=1; $i <= 192; $i++) {
			for ($i=1; $i <= $this->data['articles_count']; $i++) {
				$y0 = $this->GetY();
				foreach ($this->data['items_on_page'] as $items) {
					if ($items == $i) {
						$this->addPage();
						$this->printTableHeader();
						$y0 = $this->GetY();
						break;
					}
				}

				// Lp
				if ($i < 100) {
					$this->SetFont('ArialMT','', 7);
				} else {
					$this->SetFont('ArialMT','', 5);
				}
				$this->SetXY($x0, $y0);
				$this->MultiCell(5, 6, $i, 'LB', 'R');

				// Article name
				$this->SetFont('ArialMT','', 8);
				$this->SetXY($x0 + 5, $y0);
				$name         = $this->unhtmlentities($this->data['order']->products[$i-1]['name']);
				// For debug only!
//			$article_name = $this->getMaxArticlesName($this->data['order']->products[0]['name']);
				$article_name = $this->getMaxArticlesName($name);
				$this->MultiCell(80, 6, $article_name, 'LB', 'L');

				// PKWiU
				$this->SetFont('ArialMT','', 5);
				$this->SetXY($x0 + 83, $y0);
				if ($this->data['order']->products[$i-1]['pkwiu'] == 0) {
					$this->data['order']->products[$i-1]['pkwiu'] = '';
				}
				$this->MultiCell(14.5, 6, $this->data['order']->products[$i-1]['pkwiu'], 'LB', 'C');
				$this->SetFont('ArialMT','', 8);

				// J.m.
				$this->SetXY($x0 + 97.5, $y0);
				$this->MultiCell(7, 6, 'szt.', 'LB', 'C');

				// Quantity
				$this->SetXY($x0 + 104.5, $y0);
				// For debug only!
//				$this->MultiCell(10, 6, $this->data['order']->products[0]['qty'], 'LB', 'R');
				$this->MultiCell(10, 6, $this->data['order']->products[$i-1]['qty'], 'LB', 'R');

				// Netto price for one piece
				$this->SetXY($x0 + 114.5, $y0);
				// For debug only!
//				$price_for_one = $this->invoiceNumberFormat($this->data['order']->products[0]['final_price']);
				$price_for_one = $this->invoiceNumberFormat($this->data['order']->products[$i-1]['final_price']);
				$this->MultiCell(16, 6, $price_for_one, 'LB', 'R');
				$price_for_one = str_replace(',', '.', $price_for_one);
				$price_for_one = floatval(str_replace(' ', '', $price_for_one));

				// Netto sum
				$this->SetXY($x0 + 130.5, $y0);
				// For debug only!
//				$netto_sum = $price_for_one * $this->data['order']->products[0]['qty'];
				$netto_sum = $price_for_one * $this->data['order']->products[$i-1]['qty'];
				$this->MultiCell(17, 6, $this->invoiceNumberFormat($netto_sum), 'LB', 'R');

				// Tax
				$this->SetXY($x0 + 147.5, $y0);
				// For debug only!
//				$tax = $this->data['order']->products[0]['tax'];
				$tax = $this->data['order']->products[$i-1]['tax'];
				$this->MultiCell(6.5, 6, number_format($tax, 0), 'LB', 'C');

				// Value of the tax
				// If an end of the cent is greater or equal than 0.5
				// round up the value. If the end of the cent is less than
				// 0.5 round down the value.
				// See http://www.jotka.pl/porady/tematyczne/rachunki2000.html
				$tax_value = ($netto_sum * $tax)/100.0;
				$n         = explode('.', $tax_value);
				$zl        = $n[0];
				$grosze    = intval(substr($n[1], 0, 2));
				$n_length  = strlen($n[1]);
				if ($n_length > 2) {
					$part_of_grosze = '0.'.substr($n[1], 2);
					if ( floatval($part_of_grosze) >= 0.5 ) {
						$grosze = $grosze + 1;
					}
				}
				if (($grosze < 10) and ($n_length >= 2)) {
					$grosze = '0'.$grosze;
				}
				$tax_value= floatval($zl.'.'.$grosze);
				$this->SetXY($x0 + 154, $y0);
				$this->MultiCell(13.0, 6, $this->invoiceNumberFormat($tax_value), 'LB', 'R');

				// Brutto price
				$brutto_sum = $tax_value + $netto_sum;
				$this->SetXY($x0 + 166.5, $y0);
				$this->MultiCell(22, 6, number_format($brutto_sum, 2, ',', ' '), 'LBR', 'R');

				// Total
				$this->data['total']             += $brutto_sum;
				$this->data['tax_total']         += $tax_value;
				$this->data['total_without_tax'] += $netto_sum;

				// Total but divided on the tax classes
				if ($tax == 22) {
					$this->data['total22']             += $brutto_sum;
					$this->data['tax_total22']         += $tax_value;
					$this->data['total_without_tax22'] += $netto_sum;
				} elseif ($tax == 7) {
					$this->data['total7']              += $brutto_sum;
					$this->data['tax_total7']          += $tax_value;
					$this->data['total_without_tax7']  += $netto_sum;
				} elseif ($tax == 3) {
					$this->data['total3']              += $brutto_sum;
					$this->data['tax_total3']          += $tax_value;
					$this->data['total_without_tax3']  += $netto_sum;
				} elseif ($tax == 0) {
					$this->data['total0']              += $brutto_sum;
					$this->data['tax_total0']          += $tax_value;
					$this->data['total_without_tax0']  += $netto_sum;
				}
			}

		$oid     = $this->getOrderId();
		$res = tep_db_query('SELECT  value, class FROM '.TABLE_ORDERS_TOTAL.' WHERE orders_id='.$oid);
		while ($row = @tep_db_fetch_array($res)) {
			if ($row['class'] == 'ot_redemptions') {
				$ld = round($row['value'], 2);
				$this->setData('redemptions', $ld);
				$this->setData('total', $this->data['total'] - floatval($this->data['redemptions']));
			}
			if ($row['class'] == 'ot_loyalty_discount') {
				$ld = round($row['value'], 2);
				$this->setData('discount', $ld);
				$this->setData('total', $this->data['total'] - floatval($this->data['discount']));
			}
		}
		$this->printShipmentCost($this->GetY(), $x0, $i);
	}


	/**
	 * Print the footer of the table
	 * It's likely the important part of the invoice
	 *
	 * @return	void
	 */
	function printTableFooter() {
		$a = array();

		$add = 0;
		if ( ((25 < $this->data['articles_count']) AND ($this->data['articles_count'] < 33)) OR ((65 < $this->data['articles_count']) AND ($this->data['articles_count'] < 73)) ) {
			$this->addPage();
			$add = 1;
		}

		$x0 = $this->data['x0'];
		$y0 = $this->GetY() + $add;
		$h  = 6; // Height of the cell
		$this->SetXY($x0 , $y0);
		$this->SetFont('ArialMT','', 8);

		// Total price in the words
		$this->printTotalInWords($h, $x0, $y0);

		$this->Cell(16, $h, 'RAZEM', 'TRB', 0, 'C');

		// Netto
		$this->SetFont('ArialMT','', 8);
		$this->Cell(17, $h, number_format($this->data['total_without_tax'], 2, ',', ' '), 'TRB', 0, 'R');

		$this->Cell(6.5, $h, 'x', 'TRB', 0, 'C');

		// Tax
		$this->Cell(12.5, $h, number_format($this->data['tax_total'], 2, ',', ' '), 'TRB', 0, 'R');

		// Total price
		$this->Cell(22, $h, number_format($this->data['total'] + $this->data['discount'] + $this->data['redemptions'], 2, ',', ' '), 'TRB', 0, 'R');

		// Draw rows
		$this->SetFont('ArialMT', '', 10);
		$this->SetXY(126.5, $y0 + $h);
		$this->Cell(16, $h, 'W TYM', 'RB', 0, 'C');
		$this->SetFont('ArialMT','', 8);
		$this->Cell(17, $h, '', 'TRB', 0, 'R');
		$this->Cell(6.5, $h, 'zw', 'TRB', 0, 'C');
		$this->Cell(12.5, $h, '', 'TRB', 0, 'R');
		$this->Cell(22, $h, '', 'TRB', 0, 'R');

		// Area for the seals
		$y0 = $this->GetY() + 1 + $h;
		$this->SetXY($x0 , $y0);
		$this->Cell(64.5, 4*$h, '', 'LTR');
		$this->Cell(64.5, 4*$h, '', 'TR');
		$this->SetFont('ArialMT','', 6);
		$y0 = $y0 + (4 * $h);
		$this->SetXY($x0 , $y0);
		if ($this->getData('electronic_sell') == 'true') {
			$this->Cell(64.5, 4, '', 'LR', 0, 'C');
		} else {
			$this->Cell(64.5, 4, 'imię i nazwisko oraz podpis', 'LR', 0, 'C');
		}
		$this->Cell(64.5, 4, 'podpis i pieczęć imienna osoby', 'LR', 0, 'C');
		$y0 = $y0 + 2;
		$this->SetXY($x0 , $y0);
		if ($this->getData('electronic_sell') == 'true') {
			$this->Cell(64.5, 4, 'nie wymaga podpisu odbiorcy', 'LBR', 0, 'C');
		} else {
			$this->Cell(64.5, 4, 'osoby upoważnionej do otrzymania faktury', 'LBR', 0, 'C');
		}
		$this->Cell(64.5, 4, 'uprawnionej do wystawienia faktury', 'LBR', 0, 'C');


		// Draw a faksymile image
		$a = $this->getFaksymileImage();
		if ($a['faksymile_file'] != '') {
			$this->Image(DIR_FS_CATALOG.$a['faksymile_file'], $x0 + $a['faksymile_x'], $y0 - $a['faksymile_y'], $a['faksymile_width'], $a['faksymile_height'], 'PNG');
		}

		$x0 = $this->GetX()+ 1.5;
		$y0 = $y0 - 3 - (4 * $h);
		$this->SetFont('ArialMT','', 8);
		// A tax value: 22%
		$this->SetXY($x0 , $y0);
		$this->Cell(17, $h, $this->invoiceNumberFormat($this->data['total_without_tax22']), 'LB', 0, 'R');
		$this->Cell(6.5, $h, '22', 'LB', 0, 'C');
		$this->Cell(12.5, $h, $this->invoiceNumberFormat($this->data['tax_total22']), 'LB', 0, 'R');
		$this->Cell(22, $h, $this->invoiceNumberFormat($this->data['total22']), 'RBL', 0, 'R');
		// A tax value: 7%
		$this->SetXY($x0 , $y0 + $h);
		$this->Cell(17, $h, $this->invoiceNumberFormat($this->data['total_without_tax7']) , 'LB', 0, 'R');
		$this->Cell(6.5, $h, '7', 'LB', 0, 'C');
		$this->Cell(12.5, $h, $this->invoiceNumberFormat($this->data['tax_total7']), 'LB', 0, 'R');
		$this->Cell(22, $h, $this->invoiceNumberFormat($this->data['total7']), 'RBL', 0, 'R');
		// A tax value: 3%
		$this->SetXY($x0 , $y0 + (2 * $h));
		$this->Cell(17, $h, $this->invoiceNumberFormat($this->data['total_without_tax3']), 'LB', 0, 'R');
		$this->Cell(6.5, $h, '3', 'LB', 0, 'C');
		$this->Cell(12.5, $h, $this->invoiceNumberFormat($this->data['tax_total3']), 'LB', 0, 'R');
		$this->Cell(22, $h, $this->invoiceNumberFormat($this->data['total3']), 'RBL', 0, 'R');
		// A tax value: 0%
		$this->SetXY($x0 , $y0 + (3 * $h));
		$this->Cell(17, $h, $this->invoiceNumberFormat($this->data['total_without_tax0']), 'LB', 0, 'R');
		$this->Cell(6.5, $h, '0', 'LB', 0, 'C');
		$this->Cell(12.5, $h, $this->invoiceNumberFormat($this->data['tax_total0']), 'LB', 0, 'R');
		$this->Cell(22, $h, $this->invoiceNumberFormat($this->data['total0']), 'RBL', 0, 'R');
		$this->SetXY($x0 , $y0 + (4 * $h));
		// Discount
		$this->SetFont('ArialMT', '', 7);
		$this->Cell(17, $h + 1, 'RABAT', 'LB', 0, 'R');
		$this->SetFont('ArialMT','', 8);
		$this->Cell(41, $h + 1, ($this->data['redemptions'] != 0 ? '-' : '') . $this->invoiceNumberFormat($this->data['redemptions'] + $this->data['discount']), 'RBL', 0, 'R');
		// Total
		$this->SetFont('ArialMT', '', 7);
		$this->SetXY($x0 , $y0 + (5 * $h));
		$this->Cell(17, $h + 1, 'DO ZAPŁATY', 'LB', 0, 'R');
		$this->SetFont('ArialMT', '', 10);
		$this->Cell(41, $h + 1, $this->invoiceNumberFormat($this->data['total']), 'RBL', 0, 'R');
	}


	/**
	 * Render an attribute info
	 *
	 * @param	int		$offset:
	 * @return	void
	 */
	function printAttributesInfo($offset) {
		$info = '';
		$isAttribute = 0;

		for ($i = 0, $n = sizeof($this->data['order']->products); $i < $n; $i++) {
			$info .= $this->data['order']->products[$i]['name'] . ":\n";
			if (isset($this->data['order']->products[$i]['attributes']) && (($k = sizeof($this->data['order']->products[$i]['attributes'])) > 0)) {
				$isAttribute = 1;
				for ($j = 0; $j < $k; $j++) {
					$info .= ' ' . $this->data['order']->products[$i]['attributes'][$j]['option'].' - '.$this->data['order']->products[$i]['attributes'][$j]['value'];
					if ($this->data['order']->products[$i]['attributes'][$j]['price'] != '0') {
						$info .= ' (' . $data['order']->products[$i]['attributes'][$j]['prefix'] .
							$this->data['currencies']->format($this->data['order']->products[$i]['attributes'][$j]['price'] *
							$this->data['order']->products[$i]['qty'],true,$this->data['order']->info['currency'],$this->data['order']->info['currency_value']).')'."\n";
					} else {
						$info .= "\n";
					}
				}
			}
		}

		if ($isAttribute == 1) {
			$this->SetFont('ArialMT','', 8);
			$this->SetXY($this->data['x0'], $this->GetY() + $offset);
			$this->MultiCell(0, 5, "Opcje\n".$info);
		}
	}



	/**
	 * Render an additonal information from the seller
	 *
	 * @param	int		$offset:
	 * @return	void
	 */
	function printAdditionalInfo($offset) {
		@ $fp   = fopen($this->data['additional_info_file'], 'r');
		if ($fp) {
			$info = fread($fp, filesize($this->data['additional_info_file']));
			fclose($fp);

			$this->SetFont('ArialMT','', 8);
			$this->SetXY($this->data['x0'], $this->GetY() + $offset);
			$this->MultiCell(0, 5, "Dodatkowe informacje\n".$info);
		}
	}


	/**
	 * Print the cost of the shipment
	 *
	 * @param	float		$y0: ...
	 * @param	float		$x0: ...
	 * @param	float		$i: ...
	 * @return	void
	 */
	function printShipmentCost($y0, $x0, $i) {
		if (DOSTAWA == 'false') {
			return;
		}

    $totals_query = tep_db_query("SELECT value, class
                                 FROM " . TABLE_ORDERS_TOTAL . "
                                 WHERE orders_id = '" . (int)$this->data['order_id'] . "' AND class='ot_shipping'");
    $totals =tep_db_fetch_array($totals_query);

    $shipment = '';
    if ( ($totals !== FALSE) && ($totals['class'] == 'ot_shipping')) {
      $shipment = $totals['value'];
    }

		foreach ($this->data['items_on_page'] as $items) {
			if ($items == $i) {
				$this->addPage();
				$this->printTableHeader();
				$y0 = $this->GetY();
				break;
			}
		}

		$this->data['total22']             += $shipment;
		$this->data['total']               += $shipment;
		$shipment_netto                     = $shipment/1.22;
		$value_of_tax                       = floatval($shipment) - $shipment_netto;
		$this->data['tax_total']           += $value_of_tax;
		$this->data['total_without_tax']   += $shipment_netto;
		$this->data['total_without_tax22'] += $shipment_netto;
		$this->data['tax_total22']         += $value_of_tax;

		// L.p.
		$this->SetXY($x0, $y0);
		if ($i < 99) {
			$this->SetFont('ArialMT','', 7);
		} else {
			$this->SetFont('ArialMT','', 5); // Decline the font size because numbers greater than 99 destroy the table layout
		}
		$this->MultiCell(5, 6, $i, 'LB', 'R');

		// An article name
		$this->SetFont('ArialMT','', 8);
		$this->SetXY($x0 + 5, $y0);
		$this->MultiCell(80, 6, 'Koszt dostawy', 'LB', 'L');

//		$this->SetXY($x0 + 83, $y0);
//		$this->MultiCell(14.5, 6, '', 'LB', 'C');
//
//		$this->SetXY($x0 + 97.5, $y0);
//		$this->MultiCell(7, 6, 'szt.', 'LB', 'C');
//
//		$this->SetXY($x0 + 104.5, $y0);
//		$this->MultiCell(10, 6, '1', 'LB', 'R');

		// Netto shipment for the one
		$this->SetXY($x0 + 114.5, $y0);
		if ($shipment == 0) {
			$this->MultiCell(16, 6, '0,00', 'LB', 'R');
		} else {
			$this->MultiCell(16, 6, $this->invoiceNumberFormat($shipment_netto), 'LB', 'R');
		}

		// Netto shipment
		$this->SetXY($x0 + 130.5, $y0);
		if ($shipment == 0) {
			$this->MultiCell(17, 6, '0,00', 'LB', 'R');
		} else {
			$this->MultiCell(17, 6, $this->invoiceNumberFormat($shipment_netto), 'LB', 'R');
		}

		// VAT class of the shipment
		$this->SetXY($x0 + 147.5, $y0);
		$this->MultiCell(6.5, 6, '22', 'LB', 'C');

		// Value of the shipment tax
		$this->SetXY($x0 + 154, $y0);
		if ($shipment == 0) {
			$this->MultiCell(12.5, 6, '0,00', 'LB', 'R');
		} else {
			$this->MultiCell(12.5, 6, $this->invoiceNumberFormat($value_of_tax), 'LB', 'R');
		}

		// Brutto shipment
		$this->SetXY($x0 + 166.5, $y0);
		if ($shipment == 0) {
			$this->MultiCell(22, 6, '0,00', 'LBR', 'R');
		} else {
			$this->MultiCell(22, 6, $this->invoiceNumberFormat($shipment), 'LBR', 'R');
		}
	}


	/**
	 * Render a payment/transfer leaflet
	 *
	 * @return	void
	 */
	function printLeaflet() {
		if ( ($this->getData('print_leaflet') == 'false') and ($this->getData('invoice_type') == PROFORMA)) {
			return;
		} elseif (($this->getData('print_leaflet_oryginal') == 'false') and ($this->getData('invoice_type') == ORYGINAL)) {
			return;
		} elseif (($this->getData('print_leaflet_copy') == 'false') and ($this->getData('invoice_type') == COP)) {
			return;
		} elseif (($this->getData('print_leaflet_copy') == 'false') and ($this->getData('invoice_type') == DUPLIKAT)) {
			return;
		}

		/////////////////////////////////////////////////////
		//
		//          DRAW A BLANK LEAFLET
		//
		////////////////////////////////////////////////////

		$x_off = $this->getData('leaflet_x');
		$y_off = $this->getData('leaflet_y');
		$this->data['accept_page_break'] = FALSE;
		// It's a minimal y pos to draw a whole payment blank
		// It allways draws at the bottom of the page
		$y0 = 185 +$y_off;
		if ($this->GetY() > $y0) {
			$this->AddPage();
		}
		$x0 = $this->data['x0'] + $x_off;

		if ($this->getData('leaflet_type') == 'wplata') {
			$this->Image(DIR_FS_ADMIN.'pdf/fpdf/images/payment_leaflet.png', 2 + $x_off, $y0, 0, 0, 'PNG');
		} elseif ($this->getData('leaflet_type') == 'przelew') {
			$this->Image(DIR_FS_ADMIN.'pdf/fpdf/images/transfer_leaflet.png', 2 + $x_off, $y0, 0, 0, 'PNG');
		}

		$this->SetMargins(0,0,0);
		if ( $this->getData('colour_switch') ) {
			$this->setTextColor(217, 38, 28);
		}
		$this->SetFont('ArialMT','', 7);
		$this->setXY($x0 + 5, $y0 - 0.2);
		$this->Cell(17, 10, 'Nr rachunku odbiorcy:', 0);
		$this->SetFont('ArialMT','', 6);
		$this->setXY($x0 + 5, $y0 + 7.5);
		$this->Cell(17, 10, 'nr rachunku odbiorcy cd.', 0);
		$this->setXY($x0 - 4, $y0 + 17);
		$this->Cell(15, 10, 'Odbiorca:', 0);
		$this->setXY($x0 - 4, $y0 + 32.5);
		$this->Cell(10, 10, 'Kwota:', 0);
		$this->setXY($x0 - 4, $y0 + 42);
		$this->Cell(10, 10, 'Zleceniodawca:', 0);
		$this->setXY($x0 - 4, $y0 + 62);
		$this->Cell(10, 10, 'Tytuł:', 0);
		$this->SetFont('ArialMT','', 5);
		$this->setXY($x0 + 1.5, $y0 + 92.5);
		$this->Cell(10, 0, 'stempel', 0);
		$this->setXY($x0 + 1.5, $y0 + 94.5);
		$this->Cell(10, 0, 'dzienny', 0);
		$this->setXY($x0 + 24, $y0 + 102);
		$this->Cell(10, 0, 'Opłata:', 0);
		if ( $this->getData('colour_switch') ) {
			$this->SetDrawColor(217, 38, 28);
		}
		$this->SetLineWidth(0.2);
		$this->Line($x0 + 50.1, $y0 + 83.1, $x0 + 113, $y0 +103);
		$this->Line($x0 + 117.9, $y0 + 83.1, $x0 + 54, $y0 +103);
		$this->setXY($x0 + 53, $y0 + 105);
		$this->SetFont('ArialMT','', 6);
		$this->Cell(10, 0, 'pieczęć, data i podpis(y) zleceniodawcy na ostatnim blankiecie', 0);
		$this->SetXY($x0 + 51.5, $y0 + 6);
		$this->Cell(10, 0, 'nazwa odbiorcy', 0);
		$this->SetXY($x0 + 51.5, $y0 + 14.5);
		$this->Cell(10, 0, 'nazwa odbiorcy cd.', 0);
		$this->SetXY($x0 + 51.5, $y0 + 23);
		$this->Cell(10, 0, 'nr rachunku odbiorcy', 0);
		$this->SetXY($x0 + 51.5, $y0 + 39.7);
		$this->Cell(10, 0, 'kwota słownie (wpłata)', 0);
		$this->SetXY($x0 + 51.5, $y0 + 48.3);
		$this->Cell(10, 0, 'nazwa zleceniodawcy', 0);
		$this->SetXY($x0 + 51.5, $y0 + 56.8);
		$this->Cell(10, 0, 'nazwa zleceniodawcy cd.', 0);
		$this->SetXY($x0 + 51.5, $y0 + 65.4);
		$this->Cell(10, 0, 'tytułem', 0);
		$this->SetXY($x0 + 51.5, $y0 + 73.8);
		$this->Cell(10, 0, 'tytułem cd.', 0);
		$this->SetXY($x0 + 105.3, $y0 + 31.4);
		$this->Cell(10, 0, 'waluta', 0);
		$this->SetXY($x0 + 125.3, $y0 + 31.4);
		$this->Cell(10, 0, 'kwota:', 0);
		$this->SetXY($x0 + 118.6, $y0 + 95);
		$this->Cell(10, 0, 'Opłata:', 0);
		$this->SetFont('ArialMT','', 10);
		$this->SetXY($x0 + 88.5, $y0 + 35.1);
		$this->Cell(10, 0, 'W', 0);
		$this->SetX($x0 + 94.3);
		$this->Cell(10, 0, 'P', 0);
		$this->SetXY($x0 + 98.3, $y0 + 34.2);
		$this->Cell(10, 0, '*', 0);

		// Rotated text
		$this->SetFont('ArialMT','', 8);
		if (COLOR_ON == 'true') {
			$this->setTextColor(217, 38, 28);
		}
		$this->RotatedText($x0 - 4.8, $y0 + 67, 'odcinek dla zleceniodawcy', 90);
		$this->RotatedText($x0 + 47.5, $y0 + 56, 'Wpłata gotówkowa', 90);
		$this->RotatedText($x0 + 188.8, $y0 + 67, 'odcinek dla banku zleceniodawcy', 90);
		$this->SetFont('ArialMT','', 6);
		$this->RotatedText($x0 + 49.5, $y0 + 106.5, '', 90);

		// Circles
		$this->SetDash(1, 1);
		$this->Circle($x0 + 5.6, $y0 + 93.5, 9);
		$this->Circle($x0 + 151.9, $y0 + 95, 6);

		// Horizontal line form the left margin to the right one
		$this->SetDrawColor(0);
//		$this->Line(0, $y0 + 1.5, 209, $y0 + 1.5);

		$this->setTextColor(0);
		$this->SetFont('ArialMT','', 14);
		$this->SetXY($x0 + 175, $y0 + 85.5);
		$this->Cell(10, 0, '06', 0);
		$this->SetXY($x0 + 104.5, $y0 + 35);
		$this->Cell(10, 0, 'P', 0);
		$this->SetXY($x0 + 110, $y0 + 35);
		$this->Cell(10, 0, 'L', 0);
		$this->SetXY($x0 + 114.5, $y0 + 35);
		$this->Cell(10, 0, 'N', 0);

		/////////////////////////////////////////////////////
		//
		//          FILL A BLANK LEAFLET
		//
		////////////////////////////////////////////////////

		$this->fillBlankLeaflet($x0, $y0);
	}


	/**
	 * Fill a payment/transfer blank with data
	 *
	 * @param	[type]		$x0: ...
	 * @param	[type]		$y0: ...
	 * @return	void
	 * @access private
	 */
	function fillBlankLeaflet($x0, $y0) {
		$str                = $this->getData('firma_account_nr');
		$str2               = '';
		$max_width = 43;
		$this->SetFont('ArialMT','', 10);

		/////////////////////////////////////////////////////
		//
		//          FILL LEFT SIDE OF THE BLANK
		//
		////////////////////////////////////////////////////

		// If a konto nr is too long, divide it on two parts
		if ($this->GetStringWidth($str) <= $max_width) {
			$this->setXY($x0 + 5.7, $y0 + 3.8);
			$this->Cell(25, 10, $str, 0, 0, 'C');
		} else {
			while ($this->GetStringWidth($str) > $max_width) {
				$str2 = substr($str, -1,  1) . $str2;
				$str  = substr($str,  0, -1);
			}
			$this->setXY($x0 + 5.7, $y0 + 3.8);
			$this->Cell(25, 10, $str, 0, 0, 'C');
			$this->setXY($x0 - 4, $y0 + 11.5);
			$this->Cell(25, 10, $str2, 0, 0, 'L');
		}

		$this->SetFont('ArialMT','', 6);

		$this->setXY($x0 + 5, $y0 + 20);
		$this->Cell(25, 10, $this->getData('firma_name'), 0, 0, 'C');

		$this->setXY($x0 + 5, $y0 + 24);
		$this->Cell(25, 10, $this->getData('firma_street'), 0, 0, 'C');

		$this->setXY($x0 + 5, $y0 + 28.5);
		$this->Cell(25, 10, $this->getData('firma_zip').' '.$this->getData('firma_city'), 0, 0, 'C');

		$this->SetFont('ArialMT','', 10);

		$this->setXY($x0 - 4, $y0 + 36.1);
		$total = $this->invoiceNumberFormat($this->data['total']);
		$this->Cell(25, 10, '***'.str_replace(' ', '', $total).'zł***' , 0, 0, 'L');

		$this->SetFont('ArialMT','', 6);

		$this->setXY($x0 + 5, $y0 + 45.5);
		$this->Cell(25, 10, $this->data['order']->billing['name'], 0, 0, 'C');

		$str = $this->data['order']->billing['street_address'];
		$_off= 4;
		if ($this->GetStringWidth($str) <= $max_width) {
			$this->setXY($x0 + 5, $y0 + 50);
			$this->Cell(25, 10, $str, 0, 0, 'C');
		} else {
			$str2 = '';
			while ($this->GetStringWidth($str) > $max_width) {
				$str2 = substr($str, -1,  1) . $str2;
				$str  = substr($str,  0, -1);
			}

			$this->setXY($x0 + 5.7, $y0 + 50);
			$this->Cell(25, 10, $str, 0, 0, 'C');
			$this->setXY($x0 - 4, $y0 + 55);
			$this->Cell(25, 10, $str2, 0, 0, 'C');

			$_off= 0;
		}

		$this->setXY($x0 + 5, $y0 + 59.5 - $_off);
		$this->Cell(25, 10, $this->data['order']->billing['postcode'].' '.$this->data['order']->billing['city'], 0, 0, 'C');

		// Tytułem:
		$str = $this->getPaymentTitle();
		if ($this->GetStringWidth($str) <= $max_width) {
			$this->setXY($x0 + 5.7, $y0 + 68);
			$this->Cell(25, 10, $str, 0, 0, 'C');
		} else {
			$str2 = '';
			while ($this->GetStringWidth($str) > $max_width) {
				$str2 = substr($str, -1,  1) . $str2;
				$str  = substr($str,  0, -1);
			}

			if ($this->GetStringWidth($str2) <= $max_width) {
				$this->setXY($x0 + 5.7, $y0 + 66);
				$this->Cell(25, 10, $str, 0, 0, 'C');
				$this->setXY($x0 - 4, $y0 + 71);
				$this->Cell(25, 10, $str2, 0, 0, 'L');
			} else {
				$str3 = '';
				while ($this->GetStringWidth($str2) > $max_width) {
					$str3 = substr($str2, -1,  1) . $str3;
					$str2 = substr($str2,  0, -1);
				}
				$this->setXY($x0 + 5.7, $y0 + 65);
				$this->Cell(25, 10, $str, 0, 0, 'C');
				$this->setXY($x0 - 4, $y0 + 69);
				$this->Cell(25, 10, $str2, 0, 0, 'L');
				$this->setXY($x0 - 4, $y0 + 73);
				$this->Cell(25, 10, $str3, 0, 0, 'L');
			}
		}

		/////////////////////////////////////////////////////
		//
		//         FILL RIGHT SIDE OF THE BLANK
		//
		////////////////////////////////////////////////////

		$this->SetFont('ArialMT','', 10);

		// Nazwa odbiorcy
		$str = $this->getData('firma_name').' '.$this->getData('firma_street').' '.$this->getData('firma_zip').' '.$this->getData('firma_city');
		if (strlen($str) > 27) {
			$str2 = substr($str, 27, 27);
			$str  = substr($str, 0, 27);
			$this->printInTheLine($str, $x0 + 50.3, $y0 + 4.2);
			$this->printInTheLine($str2, $x0 + 50.3, $y0 + 12.7);
		} else {
			$this->printInTheLine($str, $x0 + 50.3, $y0 + 4.2);
		}

		// Konto
		$digit = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
		$konto = trim($this->getData('firma_account_nr'));
		$str   = '';
		for ($i=0; $i < strlen($konto); $i++) {
			if (in_array($konto[$i], $digit)) {
				$str = $str.$konto[$i];
			}
		}
		if (strlen($str) > 27) {
			$str2 = substr($str, 27, 7);
			$str  = substr($str, 0, 27);
			$this->printInTheLine($str, $x0 + 50.3, $y0 + 21.2);
			$this->printInTheLine($str2, $x0 + 50.3, $y0 + 29.7);
		} else {
			$this->printInTheLine($str, $x0 + 50.3, $y0 + 21.2);
		}

		if ($this->getData('leaflet_type') == 'wplata') {
			// Nazwa zleceniodawcy
			$str = $this->data['order']->billing['name']. ' '.
							$this->data['order']->billing['street_address'].' '.
							$this->data['order']->billing['postcode'].' '.
							$this->data['order']->billing['city'];
			if (strlen($str) > 27) {
				$str2 = substr($str, 27, 27);
				$str  = substr($str, 0, 27);
				$this->printInTheLine($str, $x0 + 50.3, $y0 + 46.5);
				$this->printInTheLine($str2, $x0 + 50.3, $y0 + 55.1);
			} else {
				$this->printInTheLine($str, $x0 + 50.3, $y0 + 46.5);
			}
		}

		// Niepotrzebne skreślić: W lub P
		$this->SetFont('ArialMT','', 14);
		$this->setXY($x0 + 94, $y0 + 30);
		$this->Cell(5, 10, 'X', 0, 0, 'C');
		$this->SetFont('ArialMT','', 14);

		// kwota:
		$this->printInTheLine(str_replace(' ','',$total), $x0 + 124.5, $y0 + 29.5);

		if ($this->getData('leaflet_type') == 'wplata') {
			// kwota słownie:
			$this->SetFont('ArialMT','', 8);
			$this->setXY($x0 + 50.3, $y0 + 38);
			$total = str_replace(' ','', $total);
      $this->Cell(25, 10, $this->parse(str_replace(',', '.', $total), 0), 0, 0, 'L');
			$this->SetFont('ArialMT','', 12);
		}

		// tytułem
		$str = $this->getPaymentTitle();
		if (strlen($str) > 27) {
			$str2 = substr($str, 27, 27);
			$str  = substr($str, 0, 27);
			$this->printInTheLine($str, $x0 + 50.3, $y0 + 63.5);
			$this->printInTheLine($str2, $x0 + 50.3, $y0 + 72.1);
		} else {
			$this->printInTheLine($str, $x0 + 50.3, $y0 + 63.5);
		}
	}


	/**
	 * Render a watermark i.e. a red text
	 *
	 * @return	void
	 */
	function printWatermark() {
		if ( !$this->getData('watermark') ) return;

		$s = $this->getData('watermark');

		$this->SetFont('Arial','B',50);
		$this->SetTextColor(255,192,203);
		$this->RotatedText(65,160,$s,45);
		$this->setTextColor(0);
	}


	/**
	 * Accept a page break and return true
	 * Don't accept a page break and return false
	 *
	 * @return	boolean		default value is true
	 */
	function acceptPageBreak() {
		return $this->data['accept_page_break'];
	}


	/********************************
	 *
	 * Helper functions
	 *
	 ********************************/


	/**
	 * Print a total price in the words in one cell or two cells
	 *
	 * @param	int		a basic height of the cell
	 * @param	[type]		$x0: ...
	 * @param	[type]		$y0: ...
	 * @return	void
	 */
	function printTotalInWords($h, $x0, $y0) {
		// Max string width in the first line
		$max_string_width = 97;
		$part1_in_words = '';
		$total_in_words   = trim($this->parse($this->data['total']));

		if ($this->GetStringWidth($total_in_words) < $max_string_width) {     // Short price
			$this->Cell(114.5, 2 * $h, "Słownie: $total_in_words", 1, 0, 'L');
		} else {                                                              // Long price
			$total_array = explode(' ', $total_in_words);
			$part2_in_words = '';
			$counter = count($total_array);

			for ($i=0; $i < $counter; $i++) {
				if ($this->GetStringWidth($part1_in_words.$total_array[$i].' ') < $max_string_width) {
					$part1_in_words .= $total_array[$i].' ';
				} else {
					$part2_in_words .= $total_array[$i].' ';
				}
			}

			$part1_in_words = trim($part1_in_words);
			$part2_in_words = trim($part2_in_words);
			$this->Cell(114.5, $h, "Słownie: $part1_in_words", 'LTR', 0, 'L');
			$this->SetXY($x0 , $y0 +$h);
			$this->Cell(114.5, $h, $part2_in_words, 'LBR', 0, 'L');

			// Return to the input position
			$this->SetXY($x0 + 114.5, $y0);
		}
	}


	/**
	 * Place all char in the right places
	 *
	 * @param	str		$str: each char is in the right place
	 * @param	int		$x: begin from this x point
	 * @param	int		$y: begin from this y point
	 * @return	string
	 */
	function printInTheLine($str, $x, $y) {
		$wynik = strtr($str, array('Ż'=>'Z','ż'=>'z','Ź'=>'Z','ź'=>'z','Ó'=>'O','ó'=>'o','Ł'=>'L','ł'=>'l','Ń'=>'N','ń'=>'n','Ą'=>'A','ą'=>'a','Ę'=>'E','ę'=>'e','Ć'=>'C','ć'=>'c','Ś'=>'S','ś'=>'s'));
		for ($i=0; $i < strlen($wynik) ; $i++) {
			$this->setXY($x, $y);
			$this->Cell(5, 10, $wynik[$i], 0, 0, 'C');

			$x += 4.87;
			if ( ($i % 5) == 0 ) {
				$x += 0.5;
			}
		}
	}


	/**
	 * Set a redemtions dicount and print on the invoice
	 *
	 * @return	void
	 */
	function printRedemptionsDiscount() {
		$content = '';
    if ($this->getData('discount') > 0 ) {
		  $offset  = 2;
    } else {
		  $offset  = 8;
    }
		$oid     = $this->getOrderId();

		$res = tep_db_query('SELECT  title, value, class FROM '.TABLE_ORDERS_TOTAL.' WHERE orders_id='.$oid);
		while ($row = @tep_db_fetch_array($res)) {
			if ($row['class'] == 'ot_redemptions') {
				$ld = round($row['value'], 2);
				$this->setData('redemptions', $ld);
				$content = strip_tags($row['title']);
				$content = ucfirst($content);

				$this->SetFont('ArialMT','', 7);
				$this->SetXY($this->data['x0'], $this->GetY() + $offset);
				$this->MultiCell(0, 5, $content . ' ' . $this->invoiceNumberFormat($this->getData('redemptions')) . 'zł');
			}
		}
	}

	/**
	 * Set a loyality dicount and print on the invoice
	 *
	 * @return	void
	 */
	function printLoyaltyDiscount() {
		$content = '';
		$offset  = 8;
		$oid     = $this->getOrderId();

		$res = tep_db_query('SELECT  title, value, class FROM '.TABLE_ORDERS_TOTAL.' WHERE orders_id='.$oid);
		while ($row = @tep_db_fetch_array($res)) {
			if ($row['class'] == 'ot_loyalty_discount') {
				$ld = round($row['value'], 2);
				$this->setData('discount', $ld);
				$content = strip_tags($row['title']);
				$content = ucfirst($content);

				$this->SetFont('ArialMT','', 7);
				$this->SetXY($this->data['x0'], $this->GetY() + $offset);
				$this->MultiCell(0, 5, $content . ' ' . $this->invoiceNumberFormat($this->getData('discount')) . 'zł');
			}
		}
	}

	/**
	 * Return a number which is according to the polish standard
	 *
	 *                   if $amount does'nt equal zero, return an amount
	 *
	 * @param	float		$amount: a float number
	 * @param	int		$dig:    number of the digits after
	 * @param	string		$dec:    a char of the seperator between
	 * @param	string		$sep:    a char of the spererator between hundreds, thousends and so on
	 * @return	string		if $amount equals zero, return empty string
	 */
	function invoiceNumberFormat($amount, $dig = 2, $dec = ',', $sep = ' ') {
		$value = number_format($amount, $dig, $dec, $sep);
		if ($value == '0,00') {
			return '';
		} else {
			return $value;
		}
	}


	/**
	 * Return a string which isn't longer than 76 p
	 *
	 * @param	string		an article name
	 * @return	string		the same name or the shorted one
	 */
	function getMaxArticlesName($name) {
		$name = strip_tags($name);

		// A width of the string should not be longer than 76
		if ($this->GetStringWidth($name) <= 76) {
			return $name;
		} else {
			while ($this->GetStringWidth($name) > 76) {
				$name = substr($name, 0, -1);
			}
			return substr($name, 0, -3).'...';
		}
	}


	/**
	 * Divide a name in to two strings, the first one has a properly width
	 * Second string is placed in the second element of an array
	 *
	 * @param	  string		an name
	 * @param	  float     a width of the first string
	 * @return	array     it contains two strings
	 */
	function getTwoStrings($name, $width) {
		if ($this->GetStringWidth($name) < $width) {
			return array(trim($name));
		} else {
			$_a = explode(' ', $name);
			$n  = count($_a);
			$s1 = ''; $s2 = '';
			$i = 0;
			while ($this->GetStringWidth($s1 . ' ' . $_a[$i]) < $width) {
				$s1 = $s1 . ' ' . $_a[$i];
				$i++;
			}
			while ($i < $n) {
				$s2 = $s2 . ' ' . $_a[$i];
				$i++;
			}

		}

		return array(trim($s1), trim($s2));
	}


	/********************************
	 *
	 * Setting and getting functions
	 *
	 ********************************/


	/**
	 * Return a text, where all variables are substituted with real values
	 *
	 * @return	string		a text that will be printed on the blank
	 */
	function getPaymentTitle() {
		$invoice_type = '';
		$replace      = '';
		$search       = array('###INVOICE_NR###', '###ORDER_NR###', '###CLIENT_NR###', '###INVOICE_TYPE###');

		if ( ($this->getData('invoice_type') == ORYGINAL) or ($this->getData('invoice_type') == COP) or ($this->getData('invoice_type') == DUPLIKAT) ) {
			$invoice_type = 'faktura VAT';
		} elseif ($this->getData('invoice_type') == PROFORMA) {
			$invoice_type = 'faktura PRO FORMA';
		}
		$replace = array($this->getInvoiceNr(), $this->getOrderId(), intval($this->data['order']->customer['id']) + $this->getData('first_client_nr'), $invoice_type);

    return str_replace($search, $replace, PAYMENT_TITLE);
	}


	/**
	 * Set a last payment day which is according to the polish standard
	 *
	 * @param	string		$days: add this number of the days
	 * @return	void
	 */
	function setPaymentPeriod($days='0') {
		$end_day = 60*60*24*intval($days);
		$array = explode('.', $this->data['invoice_date']);
		$this->data['payment_period'] = date('d.m.Y', $end_day + mktime(0, 0,0, $array[1], $array[0], $array[2]));
	}


	/**
	 * Get the attribute of the object
	 *
	 * @return	string		a value of	the attribute of the object
	 */
	function getPaymentPeriod() {
		if (isset($this->data['payment_period'])) {
			return $this->data['payment_period'];
		} else {
			return '';
		}
	}


	/**
	 * Set the data of the object
	 * Create the instance of the class (order)
	 *
	 * @param	string		$order_id:   a string
	 * @return	void
	 */
	function setOrderId($order_id) {
		$this->data['order_id']       = tep_db_input($order_id);
		$this->data['order']          = new order($this->data['order_id']);
		$this->data['articles_count'] = sizeof($this->data['order']->products);
	}


	/**
	 * Get the attribute of the object
	 *
	 * @return	string		a value of	the attribute of the object
	 */
	function getOrderId() {
		if (isset($this->data['order_id'])) {
			return intval($this->data['order_id']);
		} else {
			return 0;
		}
	}


	/**
	 * Set the attribute of the object: invoice_nr
	 *
	 * @return	void
	 */
	function setInvoiceNr($invoice_nr='') {
		// Test mode
		if ($this->getData('test') == 'true') {
			if ($invoice_nr == '') {
				$this->data['inovice_nr']          = 9999;
				$this->data['inovice_proforma_nr'] = 9999;
			} else {
				$this->data['inovice_nr']          = $invoice_nr;
				$this->data['inovice_proforma_nr'] = $invoice_nr;
			}

			return;
		}

		$nr = ''; $da = 0; // Invoice nr and an invoice date
		if ($this->getData('invoice_type') == PROFORMA) {
			$nr = 'invoice_proforma_nr';
			$da = 'invoice_proforma_date';
		} else {
			$nr = 'invoice_nr';
			$da = 'invoice_date';
		}

		// Fetch an invoice number for this order!
		$res = tep_db_query('SELECT ' . $nr . ' FROM '.TABLE_ORDERS.' WHERE orders_id='.$this->data['order_id']);
		$row = @tep_db_fetch_array($res);
		// Do you have an invoice nr? If yes, return it
		if ( intval($row[$nr]) > 0 ) {
			$this->data[$nr] = $row[$nr];
			return;
		}

		// A numeration of the invoices will be changed at the begin of each year
		if (CONTINUE_NUMERATION == 'false') {
			$current_year = date('Y', time());
			$begin_year = mktime(0, 0, 0, 1, 1, $current_year);
			$end_year   = mktime(0, 0, 0, 12, 31, $current_year);
		} else {
			$begin_year = mktime(0, 0, 0, 0, 0, 1970);
			$end_year   = mktime(0, 0, 0, 0, 0, 2029);
		}
		$where = ' WHERE '.$begin_year. ' <= ' . $da . ' AND ' . $da . ' <= '.$end_year;
		// Fetch a maximal invoice nr from this year only!
		$res = tep_db_query('SELECT MAX(' . $nr . ') FROM '.TABLE_ORDERS . $where);
		$row = @tep_db_fetch_array($res);
		$max_nr = intval($row['MAX(' . $nr . ')']);
		if ($max_nr == 0) {
			if ($this->getData('invoice_type') == PROFORMA) {
				$max_nr = $this->getData('first_invoice_proforma_nr') + 1;
			} else {
				$max_nr = $this->getData('first_invoice_nr') + 1;
			}
		} else {
			$max_nr = $max_nr + 1;
		}

		// We gather the maximum number and write it to the database
		$this->data[$nr] = $max_nr;
		tep_db_query('UPDATE '.TABLE_ORDERS.' SET ' . $nr . '='.$max_nr.'  WHERE orders_id='.$this->data['order_id']);
	}


	/**
	 * Get the attribute of the object: invoice_nr
	 *
	 * @return	string		a date
	 */
	function getInvoiceNr() {
		$nr = ''; $da = 0; // Invoice nr and an invoice date
		if ($this->getData('invoice_type') == PROFORMA) {
			$nr = 'invoice_proforma_nr';
			$da = 'invoice_proforma_date';
		} else {
			$nr = 'invoice_nr';
			$da = 'invoice_date';
		}

		$array = explode('.', $this->data[$da]);

		$d = intval($array[0]); $m = intval($array[1]); $y = intval($array[2]);
		return strftime(PREFIX_FN, mktime(0, 0, 0, $m, $d, $y)).
						sprintf(((FORMAT_FN == "") ? "%d" : FORMAT_FN), $this->data[$nr]).
						strftime(SUFFIX_FN, mktime(0, 0, 0, $m, $d, $y));
	}


	/**
	 * Set the attribute of the object: invoice_date
	 *
	 * @param	date		$invoice_date: date
	 * @return	void
	 */
	function setInvoiceDate($invoice_date='') {
		$nr = ''; $da = 0; // Invoice nr and an invoice date
		if ($this->getData('invoice_type') == PROFORMA) {
			$nr = 'invoice_proforma_nr';
			$da = 'invoice_proforma_date';
		} else {
			$nr = 'invoice_nr';
			$da = 'invoice_date';
		}

		// Test mode
		if ($this->getData('test') == 'true') {
			$invoice_date                        = time();
			$this->data['invoice_date']          = date('d.m.Y', $invoice_date);
			$this->data['invoice_proforma_date'] = date('d.m.Y', $invoice_date);
			return;
		}

		if ($invoice_date == '') {
			$invoice_date               = time();
			$this->data['invoice_date'] = date('d.m.Y', $invoice_date);
			if ($this->getData('invoice_type') == PROFORMA) {
				$this->data['invoice_proforma_date'] = date('d.m.Y', $invoice_date);
			} else {
				$this->data['invoice_date']          = date('d.m.Y', $invoice_date);
			}
		} else {
			list($day, $month, $year) = explode('.', $invoice_date);
			$invoice_date = mktime(0, 0, 0, $month, $day, $year);
			$this->data['invoice_date'] = date('d.m.Y', $invoice_date);
			if ($this->getData('invoice_type') == PROFORMA) {
				$this->data['invoice_proforma_date'] = date('d.m.Y', $invoice_date);
			} else {
				$this->data['invoice_date']          = date('d.m.Y', $invoice_date);
			}
			tep_db_query('UPDATE '.TABLE_ORDERS.' SET ' . $da . '='.$invoice_date.'  WHERE orders_id='.$this->data['order_id']);
			return;
		}

		// Fetch an invoice date for this order!
		$res = tep_db_query('SELECT ' . $da . ' FROM '.TABLE_ORDERS.' WHERE orders_id='.$this->data['order_id']);
		$row = @tep_db_fetch_array($res);
		// Do you have an invoice date? If yes, return it
		if ( intval($row[$da]) > 0 ) {
			$this->data[$da] = date('d.m.Y', $row[$da]);
			return;
		}

		tep_db_query('UPDATE '.TABLE_ORDERS.' SET ' . $da . '='.$invoice_date.'  WHERE orders_id='.$this->data['order_id']);
//		tep_db_query("UPDATE ".TABLE_ORDERS." SET " . $da . "='100' WHERE orders_id='45'");
	}


	/**
	 * Get the attribute of the object: invoice_date
	 *
	 * @return	string		a date
	 */
	function getInvoiceDate() {
		if ($this->getData('invoice_type') == PROFORMA) {
			return $this->data['invoice_proforma_date'];
		} else {
			return $this->data['invoice_date'];
		}
	}


	/**
	 * Get the attribute of the object
	 *
	 * @param	string		$key: a name of the attribute
	 * @return	string		a file path to the info text
	 */
	function getData($key) {
		return $this->data[$key];
	}


	/**
	 * Set the attribute of the object
	 *
	 * @param	string		$key:   a name of the attribute
	 * @param	string		$value: a value of the attribute
	 * @return	string		a file path to the info text
	 */
	function setData($key, $value) {
		$this->data[$key] = $this->convertToCharset($value, $this->getData('charset_in'), $this->getData('charset_out'));
	}


	/**
	 * Set the attribute of the object
	 *
	 * @param	string		$faksymile_file:   the file path to the image
	 * @param	string		$faksymile_x:      the x position of the image
	 * @param	string		$faksymile_y:      the y position of the image
	 * @param	string		$faksymile_width:  the width of the image
	 * @param	string		$faksymile_height: the height of the image
	 * @return	void
	 */
	function setFaksymileImage($faksymile_file, $faksymile_x, $faksymile_y, $faksymile_width=0, $faksymile_height=0) {
		$this->data['faksymile_file']   = $faksymile_file;
		$this->data['faksymile_x']      = $faksymile_x;
		$this->data['faksymile_y']      = $faksymile_y;
		$this->data['faksymile_width']  = $faksymile_width;
		$this->data['faksymile_height'] = $faksymile_height;
	}


	/**
	 * Get the attribute of the object
	 *
	 * @return	an		associative array with the file path, the faksymile x position, the fakymile y position
	 */
	function getFaksymileImage() {
		if (isset($this->data['faksymile_file'])) {
			return array('faksymile_file' => $this->data['faksymile_file'],
									 'faksymile_x'    => floatval($this->data['faksymile_x']),
									 'faksymile_y'    => floatval($this->data['faksymile_y']),
									 'faksymile_y'    => floatval($this->data['faksymile_y']),
									 'faksymile_y'    => floatval($this->data['faksymile_y']) );
		} else {
			return '';
		}
	}


	/**
	 * Set the attribute of the object
	 *
	 * @param	string		$logo_file:   the file path to the image
	 * @param	string		$logo_x:      the x position of the image
	 * @param	string		$logo_y:      the y position of the image
	 * @param	string		$logo_width:  the width of the image
	 * @param	string		$logo_height: the height of the image
	 * @return	void
	 */
	function setLogoImage($logo_file, $logo_x, $logo_y, $logo_width, $logo_height) {
		$this->data['logo_file']   = $logo_file;
		$this->data['logo_x']      = $logo_x;
		$this->data['logo_y']      = $logo_y;
		$this->data['logo_width']  = $logo_width;
		$this->data['logo_height'] = $logo_height;
	}


	/**
	 * Get the attribute of the object
	 *
	 * @return	an		associative array with the file path, the image x position, the image y position
	 */
	function getLogoImage() {
		if (isset($this->data['logo_file'])) {
			return array('logo_file' => $this->data['logo_file'],
									 'logo_x'    => floatval($this->data['logo_x']),
									 'logo_y'    => floatval($this->data['logo_y']),
									 'logo_y'    => floatval($this->data['logo_y']),
									 'logo_y'    => floatval($this->data['logo_y']) );
		} else {
			return '';
		}
	}
}
?>
