<?php

include 'webroot/iso/_all_reports.php';
include 'webroot/iso/_all_ulazni.php';
//include 'views/reports/f.php';
include 'webroot/iso/my/html/f.php';
include 'libs/qrcode/tcpdf_barcodes_2d.php';

App::import('Lib', 'Document');

class ReportsController extends AppController
{

	var $name = 'Reports';
	var $uses = array('Sale', 'Receiving', 'ReceivingOrder', 'Setting', 'Article', 'RetailItem', 'ReceivingItem', 'ReceivingOrderItem', 'InventoryBook', 'InventoryArticles', 'Offer', 'PaymentType', 'RadniNalog');

	var $components = array(
		'Filter' => array(
			'index,payment_types,tax_groups,articles,data_tax_groups_totals,data_tax_groups_by_dates,data_payment_types,
						daily_report_of_sale_with_tax,json_daily_report_of_sale_with_tax,json_report_normativ,json_report_tax_group_for_period,
						json_report_articles,json_pnp_group_for_period,json_report_storage,print_receiving,print_inventura,print_medjus,print_receiving_order,print_sale,
						stock_state,inventory_books,price_changes,print_returnee,print_writeOff,print_transfer_note,print_offer,print_work_order,print_skladiste' => array(
					'date_start' => array(
						'form_options' => array('label' => 'From', 'class' => 'datepicker'),
						'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
					),
					'date_end' => array(
						'form_options' => array('label' => 'To', 'class' => 'datepicker'),
						'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
					),
					'date' => array(
						'form_options' => array(),
						'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '=', 'encoded' => false),
					),
					'user' => array(
						'form_options' => array(),
						'filter_options' => array('fields' => array('`User`.`id`'), 'operator' => '=', 'encoded' => false),
					),

				),
			'test123' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
			),
			'pregled_prodaje_po_nacinu_placanja' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				'user' => array(
					'form_options' => array('label' => 'Korisnik', 'options' => 'Articles'),
				),
			),
			'pregled_napojnice' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				//				'user' => array(
//					'form_options' => array('label' => 'Korisnik', 'options' => 'Articles'),
//				),
			),
			'pregled_prodaje_po_artiklu' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				'grupa_prikaza' => array(
					'form_options' => array('label' => 'Grupa_prikaza', 'options' => 'Articles'),
					//'form_options' => array('label' => 'Vrsta_izvjesca', 'default' => 'Z'),
					//'filter_options' => array('fields' => array('`User`.`id`'), 'operator' => '=', 'encoded' => false),
				),
				'supplier' => array(
					'form_options' => array('label' => 'Dobavljač', 'options' => 'Suppliers'),
				),
			),
			'pregled_prodaje_po_normativu' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				'user' => array(
					'form_options' => array('label' => 'Korisnik', 'options' => 'Articles'),
				),
			),
			'dnevni_promet' => array(
				'datum' => array(
					'form_options' => array('label' => 'Odaberite_datum', 'class' => 'datepicker'),
					//'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'vrsta_izvjesca' => array(
					'form_options' => array('label' => 'Vrsta_izvjesca', 'options' => 'Articles'),
					//'form_options' => array('label' => 'Vrsta_izvjesca', 'default' => 'Z'),
					//'filter_options' => array('fields' => array('`User`.`id`'), 'operator' => '=', 'encoded' => false),
				),
				'user' => array(
					'form_options' => array('label' => 'Korisnik', 'options' => 'Articles'),
				),
			),
			'porez_na_potrosnju' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
			),
			'rekapitulacija_prometa' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
			),
			'prodani_artikli' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				'vrsta' => array(
					'form_options' => array(
						'label' => 'Vrsta',
						'type' => 'select',
						'style' => 'width:150px; ',
						'options' => array(1 => 'Svi', 2 => 'Roba', 3 => 'Usluge'),
						'value' => '1',
					),
				),
				'group' => array(
					'form_options' => array('label' => 'Group', 'options' => 'Groups'),
				),
				'supplier' => array(
					'form_options' => array('label' => 'Dobavljač', 'options' => 'Suppliers'),
				),
			),
			'kartica_artikla' => array(
				'articles_id' => array(
					'form_options' => array('label' => 'Odaberi-artikl', 'options' => 'Articles'),
					'filter_options' => array(),
				),
				'pord_f2' => array(
					'form_options' => array('label' => 'PROD F2', 'type' => 'checkbox', 'checked' => true, 'style' => 'width:20px; height:20px; '),
				),
			),
			'ispis_normativa' => array(
				'grupe' => array(
					'form_options' => array(
						'label' => 'Grupe normativa',
						'type' => 'select',
						'style' => 'width:150px; ',
						'disabled' => 'disabled',
						'options' => array(0 => 'Sve'),
						'selected' => 0
					),
				),
			),
			'rekapitulacija_po_danima' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
			),
			'ispis_cjenika' => array(
				'group' => array(
					'form_options' => array('label' => 'Group', 'type' => 'select', 'class' => 'my-group'),
					'filter_options' => array('fields' => array('DATE(`article_groups`.`id`)'), 'operator' => '=', 'encoded' => false),
				),
				'sort' => array(
					'form_options' => array(
						'label' => 'Sort',
						'type' => 'select',
						'class' => 'my-sort',
						'options' => array(
							1 => 'Grupa: ID ASC, Artikl: Barcode ASC',
							2 => 'Grupa: ID ASC, Artikl: Naziv ASC',
							3 => 'Grupa: Naziv ASC, Artikl: Barcode ASC',
							4 => 'Grupa: Naziv ASC, Artikl: Naziv ASC',
						),
						'value' => '1',
					),
				),
			),
			'kolicina_materijala_po_stolovima' => array(
			),
			'rekapitproizvmedjus' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				'povrat_ili_ne' => array(
					'form_options' => array(
						'label' => 'Vrsta - Prikazi samo:',
						'type' => 'select',
						'style' => 'width:150px; ',
						'options' => array(1 => 'koje nisu povrat', 2 => 'koje jesu povrat')
					),
				),
				'keub_or_all' => array(
					'form_options' => array('label' => 'Prikazi samo KEUB?', 'type' => 'checkbox', 'style' => 'width:20px; height:20px; '),
				),
			),
			'rekapitreceivings' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
				'grupiraj_dobavljac' => array(
					'form_options' => array('label' => 'Grupiraj po dobavljaču?', 'type' => 'checkbox', 'style' => 'width:20px; height:20px; '),
				),
				'dobavljaci' => array(
					'form_options' => array(
						'label' => 'Dobavljači',
						'type' => 'select',
						'style' => 'width:150px; ',
						'options' => array('' => '--')
					),
				),
			),
			'keub' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
			),
			'stanje_skladista' => array(
				'date' => array(
					'form_options' => array('label' => 'dateLabel', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'time' => array(
					'form_options' => array('label' => 'timeLabel'),
					'filter_options' => array('encoded' => false),
				),
				'group' => array(
					'form_options' => array('label' => 'Group', 'options' => 'Groups'),
				),
			),
			'stanje_skladista_iz_artikala' => array(
				'date' => array(
					'form_options' => array('label' => 'dateLabel', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'time' => array(
					'form_options' => array('label' => 'timeLabel'),
					'filter_options' => array('encoded' => false),
				),
			),
			'rekapitulacija_dobavljaca' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
			),
			'pregled_nabave_materijalno' => array(
				'date_start' => array(
					'form_options' => array('label' => 'From', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '>=', 'encoded' => false),
				),
				'date_end' => array(
					'form_options' => array('label' => 'To', 'class' => 'datepicker'),
					'filter_options' => array('fields' => array('DATE(`Sale`.`date`)'), 'operator' => '<=', 'encoded' => false),
				),
			),
		),
	);

	function beforeFilter()
	{

		$l_id = $this->Session->read('Auth.User.id');
		if (empty($l_id)) {
			$this->redirect(array('action' => '../home/'));
			return;
		}

		$la_tmp = explode('/', $_GET['url']);

		if ($la_tmp[0] == 'reports') {

			$rez = mysql_query('select user_level_id from users where id = ' . $this->Session->read('Auth.User.id'));
			$row = mysql_fetch_array($rez);
			$l_user_level = $row['user_level_id'];

			if ($l_user_level == 30) {
				switch ($la_tmp[1]) {
					case 'kolicina_materijala_po_stolovima':
						$this->Session->setFlash(__('Nemate ovlasti za pristup odabranom izvjescu!', true));
						$this->redirect(array('action' => '../home/'));
						return;

					default:
				}
			}

			$rez = mysql_query('select value from settings where name = "security.barman_can_see_reports" limit 1 ');
			$row = mysql_fetch_array($rez);
			if ($l_user_level == 30 && trim($row[0]) == 'no') {
				switch ($la_tmp[1]) {
					case 'dnevni_promet':
					case 'pregled_prodaje_po_normativu':
					case 'pregled_prodaje_po_nacinu_placanja':
					case 'pregled_napojnice':
					case 'rekapitulacija_prometa':
					case 'pregled_prodaje_po_artiklu':
					case 'porez_na_potrosnju':
					case 'stanje_skladista':
					case 'stanje_skladista_iz_artikala':
					case 'kartica_artikla':
					case 'ispis_normativa':
					case 'rekapitulacija_po_danima':
					case 'ispis_cjenika':
					case 'prodani_artikli':
					case 'rekapitulacija_dobavljaca':
					case 'pregled_nabave_materijalno':
						$this->Session->setFlash(__('Nemate ovlasti za pristup odabranom izvjescu!', true));
						$this->redirect(array('action' => '../home/'));
						return;
						break;
				}
			}
		}



		parent::beforeFilter();
		$this->Auth->allow(
			'data_tax_groups_totals',
			'data_tax_groups_by_dates',
			'data_payment_types',
			'daily_report_of_sale_with_tax',
			'json_daily_report_of_sale_with_tax',
			'json_report_normativ',
			'json_report_tax_group_for_period',
			'json_report_articles',
			'json_pnp_group_for_period',
			'json_report_storage',
			'import',
			'print_receiving',
			'print_inventura',
			'print_medjus',
			'print_receiving_order',
			'print_sale',
			'stock_state',
			'inventory_books',
			'price_changes',
			'print_returnee',
			'print_writeOff',
			'print_transfer_note',
			'print_offer',
			'print_work_order',
			'dnevni_promet',
			'pregled_prodaje_po_normativu',
			'pregled_prodaje_po_nacinu_placanja',
			'pregled_napojnice',
			'rekapitulacija_prometa',
			'pregled_prodaje_po_artiklu',
			'porez_na_potrosnju',
			'stanje_skladista',
			'stanje_skladista_iz_artikala',
			'kartica_artikla',
			'ispis_normativa',
			'rekapitulacija_po_danima',
			'ispis_cjenika',
			'prodani_artikli',
			'kolicina_materijala_po_stolovima',
			'rekapitproizvmedjus',
			'rekapitreceivings',
			'keub',
			'rekapitulacija_dobavljaca',
			'pregled_nabave_materijalno',
			'save_offer_pdf'
		);
		$this->Auth->mapActions(array(
			'payment_types' => 'read',
			'tax_groups' => 'read',
			'articles' => 'read',
			'test123' => 'read',
			//'pregled_prodaje_po_nacinu_placanja' => 'read',
			//'pregled_prodaje_po_artiklu' => 'read',
			//'pregled_prodaje_po_normativu' => 'read',
			//'dnevni_promet' => 'read',
			//'rekapitulacija_prometa' => 'read',
			//'porez_na_potrosnju' => 'read',
			//'prodani_artikli' => 'read',
			//'kartica_artikla' => 'read',
			//'kolicina_materijala_po_stolovima' => 'read',
			//'stanje_skladista' => 'read',
		));
	}

	function index()
	{
	}




	function get_item($sql, $db_res = "", $test_mode = 0)
	{

		if ($db_res) {
			$rez = mysql_query($sql, $db_res);
		} else {
			$rez = mysql_query($sql);
		}

		// ova funkcija uvijek mora vratiti samo nula ili jedan redak
		$l_br_redaka = mysql_num_rows($rez);
		switch ($l_br_redaka) {
			case 0:
				$result = "";
				break;
			case 1:
				$row = mysql_fetch_array($rez);
				$result = trim($row[0]);
				break;
			default:
				if ($test_mode == 1) {
					die("Funkcija <i>get_item()</i> vratila je više od jednog retka iako je dozvoljeno vraćanje samo jednog" .
						"<br><br> &nbsp; :::=>> <b>" . $sql . "</b>");
				}
		}

		return $result;
	}

	function get_data($sql, $force_array = 0, $db_res = "")
	{
		$la_polje = array();

		if ($db_res) {
			$rez = mysql_query($sql, $db_res);
		} else {
			$rez = mysql_query($sql);
		}
		//echo $sql."\n<br><br>";
		//echo mysql_errno() . ": " . mysql_error() . "\n<br><br>";


		$l_br_polja = mysql_num_fields($rez);
		for ($i = 0; $i < $l_br_polja; $i++) {
			array_push($la_polje, mysql_field_name($rez, $i));
		}

		$l_br_redaka = mysql_num_rows($rez);
		if ($force_array && $l_br_redaka == 1) {
			// uvijek vrati array
			$l_br_redaka = -1;
		}
		switch ($l_br_redaka) {
			case 0:
				$result = array("");
				break;
			case 1:
				$row = mysql_fetch_array($rez);
				for ($i = 0; $i < $l_br_polja; $i++) {
					$result[$la_polje[$i]] = $row[$i];
				}
				break;
			default:
				for ($i = 0; $i < $l_br_polja; $i++) {
					$result[$la_polje[$i]] = array();
				}
				while ($row = mysql_fetch_array($rez)) {
					for ($i = 0; $i < $l_br_polja; $i++) {
						array_push($result[$la_polje[$i]], $row[$i]);
					}
				}
		}
		return $result;
	}




	function test123()
	{
		if (sizeof($this->filterParams) > 0) {
			print_r($this->filterParams);
			//print "abc";
			$xml_string = "1234\r\n5678\r\n9101112\r\n" . $this->filterParams['date_start'] . "\r\n" . $this->filterParams['date_end'] . "\r\n";
			$fp = fopen('C:\Apache\htdocs\fiskal-x/test123.txt', "w");
			$l_length = fwrite($fp, $xml_string);
			fclose($fp);
		}
	}





	function dnevni_promet()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['datum']) || empty($this->filterParams['vrsta_izvjesca'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_dnevni_promet($this->filterParams['datum'], $this->filterParams['vrsta_izvjesca'], $this->filterParams['user']);
				} else {
					$la_file = all_dnevni_promet('01-01-2000', $this->filterParams['vrsta_izvjesca'], $this->filterParams['user']);
				}
			}
		}
	}

	function pregled_prodaje_po_normativu()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_pregled_prodaje_po_normativu($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['user']);
				} else {
					$la_file = all_pregled_prodaje_po_normativu('01-01-2000', '01-01-2000', $this->filterParams['user']);
				}
			}
		}
	}

	function pregled_prodaje_po_nacinu_placanja()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_pregled_prodaje_po_nacinu_placanja($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['user']);
				} else {
					$la_file = all_pregled_prodaje_po_nacinu_placanja('01-01-2000', '01-01-2000', $this->filterParams['user']);
				}
			}
		}
	}

	function pregled_napojnice()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_pregled_napojnice($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_pregled_napojnice('01-01-2000', '01-01-2000');
				}
			}
		}
	}

	function rekapitulacija_prometa()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_rekapitulacija_prometa($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_rekapitulacija_prometa('01-01-2000', '01-01-2000');
				}
			}
		}
	}

	function rekapitulacija_dobavljaca()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_rekapitulacija_dobavljaca($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_rekapitulacija_dobavljaca('01-01-2000', '01-01-2000');
				}
			}
		}
	}

	function pregled_prodaje_po_artiklu()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_pregled_prodaje_po_artiklu($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['grupa_prikaza'], $this->filterParams['supplier']);
				} else {
					$la_file = all_pregled_prodaje_po_artiklu('01-01-2000', '01-01-2000', 'DA', 0);
				}
			}
		}
	}

	function porez_na_potrosnju()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_porez_na_potrosnju($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_porez_na_potrosnju('01-01-2000', '01-01-2000');
				}
			}
		}
	}

	function stanje_skladista()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date']) || empty($this->filterParams['time'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_stanje_skladista($this->filterParams['date'], $this->filterParams['time'], $this->filterParams['group']);
				} else {
					$la_file = all_stanje_skladista('01-01-2000', '23:59', $this->filterParams['group']);
				}
			}
		}
	}


	function stanje_skladista_iz_artikala()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date']) || empty($this->filterParams['time'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_stanje_skladista_iz_artikala($this->filterParams['date'], $this->filterParams['time']);
				} else {
					$la_file = all_stanje_skladista_iz_artikala('01-01-2000', '23:59');
				}
			}
		}
	}


	function prodani_artikli()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_prodani_artikli($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['vrsta'], $this->filterParams['group'], $this->filterParams['supplier']);
				} else {
					$la_file = all_prodani_artikli('01-01-2000', '01-01-2000', 0, 0, 0);
				}
			}
		}
	}



	function kartica_artikla()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['articles_id'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_kartica_artikla($this->filterParams['articles_id']);
				} else {
					$la_file = all_kartica_artikla(-1);
				}
			}
		}
	}

	function ispis_normativa()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_ispis_normativa($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_ispis_normativa('01-01-2000', '01-01-2000');
				}
			}
		}
	}

	function rekapitulacija_po_danima()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_rekapitulacija_po_danima($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_rekapitulacija_po_danima('01-01-2000', '01-01-2000');
				}
			}
		}
	}

	function ispis_cjenika()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['group']) || empty($this->filterParams['sort'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_ispis_cjenika($this->filterParams['group'], $this->filterParams['sort']);
				} else {
					$la_file = all_ispis_cjenika(null, 1);
				}
			}
		}
	}

	function kolicina_materijala_po_stolovima()
	{
		if (mailer_check_date()) {
			$la_file = all_kolicina_materijala_po_stolovima();
		} else {
			$la_file = all_kolicina_materijala_po_stolovima();
		}
	}

	function rekapitproizvmedjus()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_rekapitproizvmedjus($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['keub_or_all'], $this->filterParams['povrat_ili_ne']);
				} else {
					$la_file = all_rekapitproizvmedjus($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['keub_or_all'], $this->filterParams['povrat_ili_ne']);
				}
			}
		}
	}

	function rekapitreceivings()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_rekapitreceivings($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['grupiraj_dobavljac'], $this->filterParams['dobavljaci']);
				} else {
					$la_file = all_rekapitreceivings($this->filterParams['date_start'], $this->filterParams['date_end'], $this->filterParams['grupiraj_dobavljac'], $this->filterParams['dobavljaci']);
				}
			}
		}
	}

	function keub()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_keub($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_keub($this->filterParams['date_start'], $this->filterParams['date_end']);
				}
			}
		}
	}

	function pregled_nabave_materijalno()
	{
		if (sizeof($this->filterParams) > 0) {
			if (empty($this->filterParams['date_start']) || empty($this->filterParams['date_end'])) {
			} else {
				if (mailer_check_date()) {
					$la_file = all_pregled_nabave_materijalno($this->filterParams['date_start'], $this->filterParams['date_end']);
				} else {
					$la_file = all_pregled_nabave_materijalno('01-01-2000', '01-01-2000');
				}
			}
		}
	}


	function p($obj)
	{
		print_r($obj);
		print "\n\n";
	}

	function _convert($str)
	{
		//return iconv('utf-8', 'iso-8859-2//TRANSLIT', utf8_decode($str));
		return iconv('utf-8', 'iso-8859-2//TRANSLIT', $str);
	}



	function payment_types()
	{
		$filter_conditions = $this->filterConditions;
		$filter_params = $this->filterParams;

		$sale_dates = $this->Sale->saleDates($filter_conditions);

		// payment types

		$payment_types = array('total' => $this->Sale->reportPayments($filter_conditions), 'dates' => array());
		foreach ($sale_dates as $d) {
			$payment_types['dates'][$d] = $this->Sale->reportPayments(array_merge($filter_conditions, array('DATE(`Sale`.`date`)' => $d)));
		}

		$this->set('data', $payment_types);
	}

	function tax_groups()
	{
		$filter_conditions = $this->filterConditions;
		$filter_params = $this->filterParams;

		$sale_dates = $this->Sale->saleDates($filter_conditions);

		// tax groups
		$tax_groups = array('total' => $this->Sale->reportTaxGroup($filter_params), 'dates' => array());
		foreach ($sale_dates as $d) {
			$tax_groups['dates'][$d] = $this->Sale->reportTaxGroup(array_merge($filter_params, array('date' => $d)));
		}

		$this->set('data', $tax_groups);
	}

	function articles()
	{
		$filter_conditions = $this->filterConditions;
		$filter_params = $this->filterParams;

		$sale_dates = $this->Sale->saleDates($filter_conditions);

		// articles
		$articles = array('total' => $this->Sale->reportArticles($filter_params), 'dates' => array());
		foreach ($sale_dates as $d) {
			$articles['dates'][$d] = $this->Sale->reportArticles(array_merge($filter_params, array('date' => $d)));
		}

		$this->set('data', $articles);
	}

	function taxg($a)
	{
		switch ($a) {
			case 'Sank1':
			case 'Sank3':
			case 'Sank2':
				return 2;
			case 'Kava':
				return 8;
			case 'Sank8':
				return 5;
			case 'Sank9':
				return 6;
			case 'Sank7':
				return 4;
			case 'Hrana':
				return 1;
			case 'Sank6':
			case 'Sank4':
				return 3;
			case 'Sank0':
				return 7;
		}
		;
		return 1;
	}

	function nula($a)
	{
		if ($a)
			return $a;
		else
			return "null";
	}

	function import()
	{

		$zip = new ZipArchive;
		$zip->open($_FILES['fajl']['tmp_name']);

		$artikli = $zip->getStream('ARTIKLI.csv');
		$grupe = $zip->getStream('GRUPE.csv');

		$normativi = $zip->getStream('NORMATIV.csv');
		$norm = $zip->getStream('NORM.csv');

		if (!($artikli && $normativi && $grupe && $norm))
			die("Nije dobar zip. Fajlovi se moraju zvati ARTIKLI.csv GRUPE.csv NORMATIV.csv NORM.csv, paziti na velika i mala slova!");

		if ((!feof($artikli)))
			$t = fgets($artikli); //skip header
		while (!feof($artikli)) {
			$t = fgets($artikli);
			$t = str_replace("'", "`", $t);
			$t = str_replace("\n", "", $t);
			$l = explode(";", $t);
			$this->Sale->query("insert into articles (id,tax_group_id,name,amount,price_buy,price_sell,unit,display) values (" . $l[0] . ",1,'" . $l[1] . "','" . $l[3] . "','" . $l[5] . "','" . $l[6] . "','" . $l[2] . "','" . $l[1] . "');\n");
			//SIFRA_A;NAZIV_A;JM_A;KOLICINA_A;KDP_A;N_CJENA_A;P_CJENA_A
		}
		fclose($artikli);

		if ((!feof($grupe)))
			$t = fgets($grupe); //skip header
		while (!feof($grupe)) {
			$t = fgets($grupe);
			$t = str_replace("'", "`", $t);
			$t = str_replace("\n", "", $t);
			$l = explode(";", $t);
			$this->Sale->query("insert into product_groups (id,name) values (" . $l[0] . ",'" . $l[1] . "');\n");
		}
		fclose($grupe);

		if ((!feof($normativi)))
			$t = fgets($normativi); //skip header
		while (!feof($normativi)) {
			$t = fgets($normativi);
			$t = str_replace("'", "`", $t);
			$t = str_replace("\n", "", $t);
			$l = explode(";", $t);
			$this->Sale->query("insert into products (id,product_group_id,tax_group_id,name,description,name_long,price,price_1,price_2,price_3,price_4,created) values (" . $l[0] . "," . $this->nula($l[5]) . "," . $this->taxg($l[3]) . ",'" . $l[1] . "','" . $l[1] . "','" . $l[1] . "','" . $l[8] . "','" . $l[7] . "','" . $l[7] . "','" . $l[7] . "','" . $l[7] . "','" . date("Y-m-d H:i:s") . "');\n");
			//NORM_ID;NAZIV_N;CJENA_N;KDP_N;JM_N;GRUPA;BOJA;NOC;DAN;CJENA3;CJENA4;N_CJENA_N
		}
		fclose($normativi);

		if ((!feof($norm)))
			$t = fgets($norm); //skip header
		while (!feof($norm)) {
			$t = fgets($norm);
			$t = str_replace("'", "`", $t);
			$t = str_replace("\n", "", $t);
			$l = explode(";", $t);
			$this->Sale->query("insert into product_items (product_id,article_id,amount) values (" . $l[0] . "," . $l[1] . ",'" . $l[2] . "');\n");
			//NORM_ID;SIFRA_A;KOLICINA_A
		}
		fclose($norm);


		//exec("mysqldump",$a,$b);
		//print_r($a);
		$this->Session->setFlash(__('Masina je spremna', true), 'default', array('class' => 'success'));
		$this->redirect(array('action' => 'index'));
	}



	function data_tax_groups_totals()
	{
		// test
//		$date_start = '2011-04-01';
//		$date_end = '2011-06-01';
//		$conds = array('date_start' => $date_start, 'date_end' => $date_end);
//		$result = $this->Sale->reportTaxGroup($conds, false);

		$result = $this->Sale->reportTaxGroup($this->filterParams, false);
		die(json_encode($result));
	}

	function data_tax_groups_by_dates()
	{
		// test
//		$date_start = '2011-04-01';
//		$date_end = '2011-06-01';
//		$conds = array('date_start' => $date_start, 'date_end' => $date_end);
//		$sale_dates = $this->Sale->saleDatesAlt($conds);

		$sale_dates = $this->Sale->saleDates($this->filterConditions);
		$result = array();
		foreach ($sale_dates as $d) {
			$temp = $this->Sale->reportTaxGroup(array_merge($this->filterParams, array('date' => $d)), true);
			$result[$d] = $temp[__('Total', true)];
		}
		print_r($result);

		die(json_encode($result));
	}

	function data_payment_types()
	{
		$result = $this->Sale->reportPayments($this->filterConditions);
		die(json_encode($result));
	}


	function raw_daily_report_of_sale_with_tax()
	{
		//$df = Configure::read('Formats.date_short'); 
		$ret = array();

		$res = "@@H2\n";
		$res .= "Dnevni promet za datum: " . date_format(date_create_from_format('Y-m-d', $this->filterParams["date"]), "d-m-Y") . "\n";
		$res .= "@@NL\n";
		$res .= "@@H1\nGotovinski promet\n@@N\n";

		$this->filterParams["paymentSubtype"] = 2;
		$result = $this->Sale->reportTaxGroupWithPaymentSubtype($this->filterParams);

		$rss = array();
		$b = 0;
		foreach ($result as $t) {
			$rss[$t["tax_groups"]["name"]] = array();
			$rss[$t["tax_groups"]["name"]]["pdv"] = $t[0]["pdv"];
			$rss[$t["tax_groups"]["name"]]["pnp"] = $t[0]["pnp"];
			$rss[$t["tax_groups"]["name"]]["price"] = $t[0]["group_price"];
			$rss[$t["tax_groups"]["name"]]["ptype"] = $t["payment_types"]["name"];
			$b = 1;
		}

		if ($b)
			$ret[2] = array("text" => $res, "obj" => $rss);

		$res = "@@L\n";
		$res .= "@@H1\nVirmanski promet\n@@N\n";

		$this->filterParams["paymentSubtype"] = 4;
		$result = $this->Sale->reportTaxGroupWithPaymentSubtype($this->filterParams);

		$rss = array();
		$b = 0;
		foreach ($result as $t) {
			$rss[$t["tax_groups"]["name"]] = array();
			$rss[$t["tax_groups"]["name"]]["pdv"] = $t[0]["pdv"];
			$rss[$t["tax_groups"]["name"]]["pnp"] = $t[0]["pnp"];
			$rss[$t["tax_groups"]["name"]]["price"] = $t[0]["group_price"];
			$rss[$t["tax_groups"]["name"]]["ptype"] = $t["payment_types"]["name"];
			$b = 1;
		}

		if ($b)
			$ret[1] = array("text" => $res, "obj" => $rss);

		$res = "@@L\n";
		$res .= "@@H1\nPromet karticama\n@@N\n";


		$this->filterParams["paymentSubtype"] = 1;
		$result = $this->Sale->reportTaxGroupWithPaymentSubtype($this->filterParams);

		$rss = array();
		$b = 0;
		foreach ($result as $t) {
			$rss[$t["tax_groups"]["name"]] = array();
			$rss[$t["tax_groups"]["name"]]["pdv"] = $t[0]["pdv"];
			$rss[$t["tax_groups"]["name"]]["pnp"] = $t[0]["pnp"];
			$rss[$t["tax_groups"]["name"]]["price"] = $t[0]["group_price"];
			$rss[$t["tax_groups"]["name"]]["ptype"] = $t["payment_types"]["name"];
			$b = 1;
		}


		if ($b)
			$ret[0] = array("text" => $res, "obj" => $rss);

		return $ret;

	}

	function json_daily_report_of_sale_with_tax()
	{
		die(json_encode($this->raw_daily_report_of_sale_with_tax(), JSON_FORCE_OBJECT));
		//$doc= new Document;
		//$doc->output();
	}

	function stock_state()
	{

		$doc = new Document;
		$doc->AddPage();

		//header!
		$restName = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.name')
		));
		// $today = date("d-m-Y H:i:s");                      
		// $doc->Cell(0,5,$restName["Setting"]["value"].'                                                                                                                                                                       '.'Datum: '.$today,0,0);	
		// $doc->Ln();
		// $restAddress=$this->Setting->find('first', array(
		// 'conditions' => array('Setting.name' => 'invoice.header')
		// ));
		// $doc->Cell(0,5,$restAddress["Setting"]["value"],0,0);


		// $doc->Ln(10);
		// $doc->Cell(80);
		// $doc->SetFont('Times','B',16); 
		// $doc->Cell(30,10, 'Stanje skladista za svaki dan',0,1,'C');
		// $doc->Ln(10);

		$restpost = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.post')
		));
		$restComm = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.resort')
		));
		$restStreet = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.street')
		));
		$restStrNum = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num')
		));
		$restStrNumMark = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num_mark')
		));
		$restPlaceid = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.placeid')
		));
		$begin = new DateTime('2013-03-02 00:01:00');  // NALUPANO!
		$end = new DateTime('2013-03-05 15:09:00');


		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(70, 5, 'Stanje skladista za svaki dan', 0, 'R');
		$doc->Cell(50);
		$doc->Cell(70, 5, $restName["Setting"]["value"], 0, 2, 'R');
		$doc->Ln(2);

		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(70, 5, 'Razdoblje: od ' . $begin->format("d.m.Y") . ' do ' . $end->format("d.m.Y"), 0, 0, 'L');
		$doc->Cell(50);
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(70, 5, $restpost["Setting"]["value"] . ' ' . $restComm["Setting"]["value"] . ',' . $restStreet["Setting"]["value"] . ' ' . $restStrNum["Setting"]["value"] . $restStrNumMark["Setting"]["value"], 0, 1, 'R');

		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(70, 5, 'Poslovna jedinica: ' . $restPlaceid["Setting"]["value"], 0, 0, 'L');
		$doc->SetFont('ArialCE', 'B', 8);

		$doc->Ln(10);
		$items = $this->Article->find('all', array(
			'conditions' => array('Article.id !=' => 0)
		));
		// print_r($items);
		// die();
		// Column headings

		// Colors, line width and bold font
		$doc->SetFillColor(255, 255, 255); // slova  u headeru

		$header = array('Datum', 'Artikal', 'Stanje', 'Ulaz', 'Prodaja', 'Otpis', 'Povrat', 'Medjuskl.');
		$doc->Cell(190, 0, '', 'T');
		$doc->Ln();
		$w = array(25, 40, 25, 20, 20, 20, 20, 20);
		for ($i = 0; $i < count($header); $i++)
			$doc->Cell($w[$i], 7, $header[$i], 0, 0, 'C', true);
		$doc->Ln();
		$doc->Cell(190, 0, '', 'T');
		$doc->Ln();
		$fill = false;


		$interval = DateInterval::createFromDateString('1 day');
		$period = new DatePeriod($begin, $interval, $end);

		// $priceBuy = 0;
		// $priceSell= 0;
		$doc->SetFont('ArialCE', '', 8);
		foreach ($period as $dt) {
			foreach ($items as $item) {
				$id = $item["Article"]["id"];

				// + sve sto je prodato od danas pa do tog dana dt (bez danas)
				$rezSold = $this->RetailItem->query(
					"SELECT SUM(retail_items.amount) as samount from retail_items "
					. "LEFT JOIN sales ON retail_items.sale_id= sales.id "
					. "LEFT JOIN articles ON retail_items.article_id=articles.id "
					. "WHERE retail_items.article_id='" . $id . "' AND 'sales.date' > '" . $dt->format("Y-m-d 00:00:01") . "' AND 'sales.date' < '" . "2013-03-05 00:00:01" . "' "
					// . "ORDER BY retail_items.article_id "
				);

				// - sve sto je primljeno
				$rezRec = $this->ReceivingItem->query(
					"SELECT SUM(receiving_items.amount) as samount from receiving_items "
					. "LEFT JOIN receivings ON receiving_items.receiving_id= receivings.id "
					. "LEFT JOIN articles ON receiving_items.article_id=articles.id "
					. "WHERE receiving_items.article_id='" . $id . "' "
					. "AND receivings.date > '" . $dt->format("Y-m-d 00:00:01") . "' "
					// . "ORDER BY articles.id "
				);
				// print_r($rezRec);
				// die();
				$rez = $item["Article"]["amount"] + $rezRec[0][0]['samount'] - $rezSold[0][0]['samount'];

				// sve sto je primljeno , samo za taj dan!
				$recOnThisDay = $this->ReceivingItem->query(
					"SELECT SUM(receiving_items.amount) as samount from receiving_items "
					. "LEFT JOIN receivings ON receiving_items.receiving_id= receivings.id "
					. "WHERE receiving_items.article_id='" . $id . "' "
					. "AND receivings.date > '" . $dt->format("Y-m-d 00:00:01") . "' "
					. "AND receivings.date < '" . $dt->format("Y-m-d 23:59:59") . "' "
				);
				// print_r($recOnThisDay);
				// die();

				// sve sto je toga dana (dt) prodato
				$soldOnThisDay = $this->RetailItem->query(
					"SELECT SUM(retail_items.amount) as samount from retail_items "
					. "LEFT JOIN sales ON retail_items.sale_id=sales.id "
					. "WHERE retail_items.article_id='" . $id . "' "
					. "AND sales.date>'" . $dt->format("Y-m-d 00:00:01") . "' "
					. "AND sales.date<'" . $dt->format("Y-m-d 23:59:59") . "' "
				);
				// print_r($soldOnThisDay[0][0]['sdate']);
				// die();

				$doc->Cell($w[0], 6, $dt->format("d.m.Y\n"), 0, 0, 'C', $fill);
				$doc->Cell($w[1], 6, $item["Article"]["display"], 0, 0, 'L', $fill);
				$doc->Cell($w[2], 6, $rez, 0, 0, 'R', $fill);
				$doc->Cell($w[3], 6, number_format($recOnThisDay[0][0]['samount'], 2, '.', ' '), 0, 0, 'R', $fill);
				$doc->Cell($w[4], 6, number_format($soldOnThisDay[0][0]['samount'], 2, '.', ' '), 0, 0, 'R', $fill);
				$doc->Cell($w[5], 6, 0, 0, 0, 'R', $fill);
				$doc->Cell($w[6], 6, 0, 0, 0, 'R', $fill);
				$doc->Cell($w[7], 6, 0, 0, 0, 'R', $fill);
				$doc->Ln();

			}
			// ako hoce crtu posle svakog dana?
			// $doc->Cell(array_sum($w),0,'','T');
			// $doc->Ln();
		}
		// Closing line
		// $doc->Cell(array_sum($w),0,'','T');

		$doc->output();
		die();
	}

	function inventory_books()
	{

		$doc = new Document;
		$doc->AddPage();

		//header!
		$restName = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.name')
		));

		$restpost = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.post')
		));
		$restComm = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.resort')
		));
		$restStreet = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.street')
		));
		$restStrNum = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num')
		));
		$restStrNumMark = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num_mark')
		));
		$restPlaceid = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.placeid')
		));
		// $begin = new DateTime('2013-03-02 00:01:00'); 
		// $end = new DateTime('2013-03-05 15:09:00');


		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(70, 5, 'Stanje zaliha po knjizi popisa', 0, 'R');
		$doc->Cell(50);
		$doc->Cell(70, 5, $restName["Setting"]["value"], 0, 2, 'R');
		$doc->Ln(2);

		$doc->SetFont('ArialCE', '', 8);
		// $doc->Cell(70,5,'Razdoblje: od '.$begin->format("d.m.Y").' do '.$end->format("d.m.Y"),0,0, 'L');
		$doc->Cell(70, 5, 'Poslovna jedinica: ' . $restPlaceid["Setting"]["value"], 0, 0, 'L');
		$doc->Cell(50);
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(70, 5, $restpost["Setting"]["value"] . ' ' . $restComm["Setting"]["value"] . ',' . $restStreet["Setting"]["value"] . ' ' . $restStrNum["Setting"]["value"] . $restStrNumMark["Setting"]["value"], 0, 1, 'R');

		// $doc->SetFont('ArialCE','',8);
		// $doc->Cell(70,5,'Poslovna jedinica: '.$restPlaceid["Setting"]["value"],0,0,'L');
		$doc->SetFont('ArialCE', 'B', 8);

		$doc->Ln(10);
		$items = $this->InventoryBook->find('all', array(
			'conditions' => array('InventoryBook.id !=' => 0)
		));
		// print_r($items);
		// die();

		// Column headings

		// Colors, line width and bold font
		$doc->SetFillColor(255, 255, 255); // slova  u headeru

		$header = array('Red.br.', ' Datum', 'Opis transakcije', 'Broj transakcije', 'Potrazuje', 'Duguje', 'Saldo');
		$doc->Cell(190, 0, '', 'T');
		$doc->Ln();
		$w = array(10, 30, 40, 30, 25, 25, 30);
		for ($i = 0; $i < count($header); $i++)
			$doc->Cell($w[$i], 7, $header[$i], 0, 0, 'C', true);
		$doc->Ln();
		$doc->Cell(190, 0, '', 'T');
		$doc->Ln();
		$fill = false;

		// $interval = DateInterval::createFromDateString('1 day');
		// $period = new DatePeriod($begin, $interval, $end);
		// TREBA DA SE DODA JOS ZA PERIOD
		$doc->SetFont('ArialCE', '', 8);
		$rb = 1;
		$potrazuje = 0;
		$duguje = 0;
		$kumulativ = 0;
		// foreach ( $period as $dt )
		// {
		foreach ($items as $item) {
			$doc->Cell($w[0], 6, $rb, 0, 0, 'C');
			$doc->Cell($w[1], 6, $item["InventoryBook"]["date"], 0, 0, 'C');//$dt->format( "d.m.Y\n" ),0,0,'C',$fill);
			$doc->Cell($w[2], 6, $item["InventoryBook"]["description"], 0, 0, 'L', $fill);
			$doc->Cell($w[3], 6, number_format($item["InventoryBook"]["id"], 2, '.', ' '), 0, 0, 'R', $fill);
			// PROVERITI OVO!!!!!!!!!!!
			$doc->Cell($w[4], 6, number_format($item["InventoryBook"]["credit"], 2, '.', ' '), 0, 0, 'R', $fill);
			$doc->Cell($w[5], 6, number_format($item["InventoryBook"]["debit"], 2, '.', ' '), 0, 0, 'R', $fill);
			$doc->Cell($w[5], 6, number_format($kumulativ + $item["InventoryBook"]["credit"] - $item["InventoryBook"]["debit"], 2, '.', ' '), 0, 0, 'R', $fill); // ni ovo ne znam
			$kumulativ = $kumulativ + $item["InventoryBook"]["credit"] - $item["InventoryBook"]["debit"];
			$doc->Ln();

			$duguje = $duguje + $item["InventoryBook"]["credit"];
			$potrazuje = $potrazuje + $item["InventoryBook"]["debit"];
			$rb = $rb + 1;
		}

		// }
		// Closing line
		$doc->Cell(array_sum($w), 0, '', 'T');
		$doc->Ln();
		$doc->Cell(110);
		$doc->Cell($w[4], 6, number_format($duguje, 2, '.', ' '), 0, 0, 'R', $fill);
		$doc->Cell($w[5], 6, number_format($potrazuje, 2, '.', ' '), 0, 0, 'R', $fill);
		$doc->Ln();
		$doc->Cell(array_sum($w), 0, '', 'T');

		$doc->Ln();
		$doc->output();
		die();
	}




	function set_common_params($id)
	{
		$a_param = array();

		$a_param['destination'] = 'screen';
		$a_param['restName'] = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.name')));
		$a_param['restpost'] = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.post')));
		$a_param['restComm'] = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.resort')));
		$a_param['restStreet'] = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.street')));
		$a_param['restStrNum'] = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num')));
		$a_param['restStrNumMark'] = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num_mark')));
		$a_param['restPlaceid'] = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.placeid')));
		$a_param['rec'] = $this->Receiving->find('first', array('conditions' => array('Receiving.id' => $id)));
		$a_param['items'] = $this->Receiving->ReceivingItem->find('all', array('conditions' => array('ReceivingItem.receiving_id' => $id)));

		return $a_param;
	}

	function print_receiving($id = null)
	{
		$a_param = $this->set_common_params($id);
		$l_do_it = mailer_check_date();

		if ($l_do_it) {
			all_print_receiving($a_param, $id);
		} else {
			all_print_receiving($a_param, 0);
		}
	}

	//otpis
	function print_writeOff($id = null)
	{
		$a_param = $this->set_common_params($id);
		$l_do_it = mailer_check_date();

		if ($l_do_it) {
			all_print_writeOff($a_param, $id);
		} else {
			all_print_writeOff($a_param, 0);
		}
	}

	// povratnica
	function print_returnee($id = null)
	{
		$a_param = $this->set_common_params($id);
		$l_do_it = mailer_check_date();

		if ($l_do_it) {
			all_print_returnee($a_param, $id);
		} else {
			all_print_returnee($a_param, 0);
		}
	}

	// medjuskladisnica
	function print_transfer_note($id = null)
	{
		$a_param = $this->set_common_params($id);
		$l_do_it = mailer_check_date();

		if ($l_do_it) {
			all_print_transfer_note($a_param, $id);
		} else {
			all_print_transfer_note($a_param, 0);
		}
	}

	// inventura
	function print_inventura($id = null)
	{
		$a_param = $this->set_common_params($id);
		$l_do_it = mailer_check_date();

		if ($l_do_it) {
			all_print_inventura($a_param, $id);
		} else {
			all_print_inventura($a_param, 0);
		}
	}

	// skladiste
	function print_skladiste($id = null)
	{
		$a_param = $this->set_common_params($id);
		$l_do_it = mailer_check_date();

		if ($l_do_it) {
			all_print_skladiste($a_param, $id);
		} else {
			all_print_skladiste($a_param, 0);
		}
	}

	// medjuskladisnica proizvodnja
	function print_medjus($id = null)
	{
		$a_param = $this->set_common_params($id);
		$l_do_it = mailer_check_date();

		if ($l_do_it) {
			all_print_medjus($a_param, $id);
		} else {
			all_print_medjus($a_param, 0);
		}
	}

	/*
	   // povratnica
	   function print_returnee($id=null) {
	   
		   $doc=new Document;
		   
		   $doc->AddPage();
		   $restName=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.name')
		   ));
		   
		   $doc->Cell(100);
		   $doc->Cell(0,5,$restName["Setting"]["value"],0,2);
		   $doc->SetFont('ArialCE','',10);
		   
		   $restpost=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.post')
		   ));
		   $restComm=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.resort')
		   ));
		   $restStreet=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.street')
		   ));
		   $restStrNum=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.str_num')
		   ));
		   $restStrNumMark=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.str_num_mark')
		   ));
		   $doc->Cell(0,5,$restpost["Setting"]["value"].' '.$restComm["Setting"]["value"].','.$restStreet["Setting"]["value"].' '.$restStrNum["Setting"]["value"].$restStrNumMark["Setting"]["value"],0,2);
		   
		   $restPlaceid=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.placeid')
		   ));
		   $doc->SetFont('ArialCE','',8);
		   $doc->Cell(0,5,$restPlaceid["Setting"]["value"],0,0);
		   
		   $rec=$this->Receiving->find('first', array(
		   'conditions' => array('Receiving.id' => $id)
		   ));
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,8,$rec["Supplier"]["name"],'LTR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
			   
		   $doc->SetFont('ArialCE','B',10);
		   $doc->Cell(80,8, 'Povrat Robe *'.$rec["Receiving"]["number"],'LTRB',0,'C');

		   
		   $dt = date('d.m.Y', strtotime($rec["Receiving"]["created"]));
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,5,'  ','LR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
		   $doc->SetFont('Courier','',8);
		   $doc->Cell(80,5,"Broj dokumenta:    ".$rec["Receiving"]["number"],'LR',0);
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',8);  
			   $doc->Cell(80,5,$rec["Supplier"]["address"].' '.$rec["Supplier"]["city"],'LR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
		   $doc->SetFont('Courier','',8);
		   $doc->Cell(80,5,"Datum dokumenta:   ".$dt,'LBR',0);
		   $doc->Ln();

		   // $doc->SetFont('ArialCE','B',12);  
		   // $doc->Cell(80,5,'  ','LR',0);
		   // $doc->Cell(20);
		   // $doc->SetFont('Courier','',8);
		   // $doc->Cell(80,5,"Racun:             ".'','LBR',0);
		   // $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','',8);  
			   $doc->Cell(80,5,"OIB: ".$rec["Supplier"]["oib"],'LRB',0,'R');
			   $doc->Ln(10);
		   }
		   else
			   $doc->Ln();
		   
		   $doc->SetFont('ArialCE','B',8);
		   
		   // Column headings
		   
		   // Colors, line width and bold font
			$doc->SetFillColor(255,255,255); // slova  u headeru
	   

		   $header = array('Red.br','Sifra','Naziv artikla/usluge', 'Kolicina', 'Nab. Cj.', 'Nab.Vrijed.', 'MPC' ,'Vrijednost kn');
		   
		   $w = array(10,30,50,20,20,20,20,20);
		   for($i=0;$i<count($header);$i++)
			   $doc->Cell($w[$i],7,$header[$i],0,0,'C',true);
		   $doc->Ln();
	   
		   $fill = false;
		   
		   $items=$this->Receiving->ReceivingItem->find('all', array(
		   'conditions' => array('ReceivingItem.receiving_id' => $id)
		   ));
		   $doc->SetFont('ArialCE','',8);
		   $priceBuy = 0;
		   $priceSell= 0;
		   $fakt =0;
		   $price = 0;
		   $marza = 0;
		   $pdv = 0;
		   $discount = 0;
		   $redbr = 1;
		   foreach($items as $item)    
		   {
			   $doc->Cell($w[0],6,$redbr,0,0,'C',$fill);
			   $doc->Cell($w[1],6,$item["Article"]["barcode"],0,0,'L',$fill);
			   $doc->Cell($w[2],6,$item["Article"]["name"],0,0,'L',$fill);
			   $doc->Cell($w[3],6,number_format(-$item["ReceivingItem"]["amount"],2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[4],6,number_format(-$item["ReceivingItem"]["price_buy"],2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[5],6,number_format(-$item["ReceivingItem"]["price_buy"]*$item["ReceivingItem"]["amount"],2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[6],6,number_format(-$item["ReceivingItem"]["price_sell"],2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[7],6,number_format(-$item["ReceivingItem"]["amount"]*$item["ReceivingItem"]["price_sell"],2, '.', ' '),0,0,'R',$fill);
			   
			   $doc->Ln();
			   
			   $priceBuy = $priceBuy - $item["ReceivingItem"]["price_buy"]*$item["ReceivingItem"]["amount"];
			   $price = $price - $item["ReceivingItem"]["price_sell"]*$item["ReceivingItem"]["amount"];
			   
			   $redbr = $redbr+1;
		   
		   }
		   
		   // Closing line
		   $doc->Cell(array_sum($w),0,'','T');
		   $doc->Ln();
		   $doc->Cell($w[0]+$w[1]+$w[2]+$w[3]+$w[4],6,'',0,0,'L',$fill);
		   $doc->Cell($w[5],6,number_format($priceBuy,2, '.', ' '),0,0,'R',$fill);
		   $doc->Cell($w[6],6,'',0,0,'R',$fill);
		   $doc->Cell($w[7],6,number_format($price,2, '.', ' '),0,0,'R',$fill);
		   
		   $doc->Ln();
		   $doc->Cell(array_sum($w),0,'','T');
		   $doc->Ln();
		   
		   $doc->Cell(10);
		   $doc->Cell(30,20,"Robu Predao",'B',0,'C');
	   
		   $doc->Cell(10);
		   $doc->Cell(30,20,"Robu Primio",'B',0,'C');
		   
		   $doc->Cell(40);
		   $doc->Cell(30,20,"Obradio",'B',0,'C');
		   $doc->Ln();
		   
		   $doc->Cell(10);
		   $doc->Cell(30,4,"",0,0,'C');
	   
		   $doc->Cell(10);
		   $doc->Cell(30,4,"",0,0,'C');
		   
	   
		   $doc->output();
		   die();
	   }
	   */


	/*
	   //otpis
	   function print_writeOff($id=null){
		   
		   $doc=new Document;
		   
		   $doc->AddPage();
		   $restName=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.name')
		   ));
		   
		   $doc->Cell(100);
		   $doc->Cell(0,5,$restName["Setting"]["value"],0,2);
		   $doc->SetFont('ArialCE','',10);
		   
		   $restpost=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.post')
		   ));
		   $restComm=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.resort')
		   ));
		   $restStreet=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.street')
		   ));
		   $restStrNum=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.str_num')
		   ));
		   $restStrNumMark=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.str_num_mark')
		   ));
		   $doc->Cell(0,5,$restpost["Setting"]["value"].' '.$restComm["Setting"]["value"].','.$restStreet["Setting"]["value"].' '.$restStrNum["Setting"]["value"].$restStrNumMark["Setting"]["value"],0,2);
		   
		   $restPlaceid=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.placeid')
		   ));
		   $doc->SetFont('ArialCE','',8);
		   $doc->Cell(0,5,$restPlaceid["Setting"]["value"],0,0);
		   
		   $rec=$this->Receiving->find('first', array(
		   'conditions' => array('Receiving.id' => $id)
		   ));
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,8,$rec["Supplier"]["name"],'LTR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
			   
		   $doc->SetFont('ArialCE','B',10);
		   $doc->Cell(80,8, 'Otpis Robe *'.$rec["Receiving"]["number"],'LTRB',0,'C');

		   $dt = date('d.m.Y', strtotime($rec["Receiving"]["created"]));
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,5,'  ','LR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
		   $doc->SetFont('Courier','',8);
		   $doc->Cell(80,5,"Broj dokumenta:    ".$rec["Receiving"]["number"],'LR',0);
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,5,$rec["Supplier"]["address"].' '.$rec["Supplier"]["city"],'LR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
		   $doc->SetFont('Courier','',8);
		   $doc->Cell(80,5,"Datum dokumenta:   ".$dt,'LBR',0);
		   $doc->Ln();

		   // $doc->SetFont('ArialCE','B',12);  
		   // $doc->Cell(80,5,'  ','LR',0);
		   // $doc->Cell(20);
		   // $doc->SetFont('Courier','',8);
		   // $doc->Cell(80,5,"Racun:             ".'','LBR',0);
		   // $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','',8);  
			   $doc->Cell(80,5,"OIB: ".$rec["Supplier"]["oib"],'LRB',0,'R');
			   $doc->Ln(10);
		   }
		   else
			   $doc->Ln();
		   
		   $doc->SetFont('ArialCE','B',8);
		   
		   // Column headings
		   
		   // Colors, line width and bold font
			$doc->SetFillColor(255,255,255); // slova  u headeru
	   

		   $header = array('Red.br','Sifra','Naziv artikla/usluge', 'Kolicina', 'Nab. Cj.', 'Nab.Vrijed.', 'MPC' ,'Vrijednost kn');
		   
		   $w = array(10,30,50,20,20,20,20,20);
		   for($i=0;$i<count($header);$i++)
			   $doc->Cell($w[$i],7,$header[$i],0,0,'C',true);
		   $doc->Ln();
	   
		   $fill = false;
		   
		   $items=$this->Receiving->ReceivingItem->find('all', array(
		   'conditions' => array('ReceivingItem.receiving_id' => $id)
		   ));
		   $doc->SetFont('ArialCE','',8);
		   $priceBuy = 0;
		   $priceSell= 0;
		   $fakt =0;
		   $price = 0;
		   $marza = 0;
		   $pdv = 0;
		   $discount = 0;
		   $redbr = 1;
		   foreach($items as $item)    
		   {
			   $doc->Cell($w[0],6,$redbr,0,0,'C',$fill);
			   $doc->Cell($w[1],6,$item["Article"]["barcode"],0,0,'L',$fill);
			   $doc->Cell($w[2],6,$item["Article"]["name"],0,0,'L',$fill);
			   $doc->Cell($w[3],6,number_format(-($item["ReceivingItem"]["amount"]),2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[4],6,number_format(-($item["ReceivingItem"]["price_buy"]),2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[5],6,number_format(-($item["ReceivingItem"]["price_buy"]*$item["ReceivingItem"]["amount"]),2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[6],6,number_format(-($item["ReceivingItem"]["price_sell"]),2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[7],6,number_format(-($item["ReceivingItem"]["amount"]*$item["ReceivingItem"]["price_sell"]),2, '.', ' '),0,0,'R',$fill);
			   
			   $doc->Ln();
			   
			   $priceBuy = $priceBuy - $item["ReceivingItem"]["price_buy"]*$item["ReceivingItem"]["amount"];
			   $price = $price - $item["ReceivingItem"]["price_sell"]*$item["ReceivingItem"]["amount"];
			   
			   $redbr = $redbr+1;
		   
		   }
		   
		   // Closing line
		   $doc->Cell(array_sum($w),0,'','T');
		   $doc->Ln();
		   $doc->Cell($w[0]+$w[1]+$w[2]+$w[3]+$w[4],6,'',0,0,'L',$fill);
		   $doc->Cell($w[5],6,number_format($priceBuy,2, '.', ' '),0,0,'R',$fill);
		   $doc->Cell($w[6],6,'',0,0,'R',$fill);
		   $doc->Cell($w[7],6,number_format($price,2, '.', ' '),0,0,'R',$fill);
		   
		   $doc->Ln();
		   $doc->Cell(array_sum($w),0,'','T');
		   $doc->Ln();
	   
		   $doc->Cell(10);
		   $doc->Cell(30,20,"Robu Predao",'B',0,'C');
	   
		   $doc->Cell(10);
		   $doc->Cell(30,20,"Robu Primio",'B',0,'C');
		   
		   $doc->Cell(40);
		   $doc->Cell(30,20,"Obradio",'B',0,'C');
		   $doc->Ln();
		   
		   $doc->Cell(10);
		   $doc->Cell(30,4,"",0,0,'C');
	   
		   $doc->Cell(10);
		   $doc->Cell(30,4,"",0,0,'C');
		   
		   $doc->output();
		   die();
	   }
	   */



	/*
	   // medjuskladisnica
	   function print_transfer_note($id=null) {
	   
		   $doc=new Document;
		   
		   $doc->AddPage('L');
		   $restName=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.name')
		   ));
		   
		   $doc->Cell(100);
		   $doc->Cell(0,5,$restName["Setting"]["value"],0,2);
		   $doc->SetFont('ArialCE','',10);
		   
		   $restpost=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.post')
		   ));
		   $restComm=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.resort')
		   ));
		   $restStreet=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.street')
		   ));
		   $restStrNum=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.str_num')
		   ));
		   $restStrNumMark=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.str_num_mark')
		   ));
		   $doc->Cell(0,5,$restpost["Setting"]["value"].' '.$restComm["Setting"]["value"].','.$restStreet["Setting"]["value"].' '.$restStrNum["Setting"]["value"].$restStrNumMark["Setting"]["value"],0,2);
		   
		   $restPlaceid=$this->Setting->find('first', array(
		   'conditions' => array('Setting.name' => 'general.placeid')
		   ));
		   $doc->SetFont('ArialCE','',8);
		   $doc->Cell(0,5,$restPlaceid["Setting"]["value"],0,0);
		   
		   $rec=$this->Receiving->find('first', array(
		   'conditions' => array('Receiving.id' => $id)
		   ));
		   
		   $doc->Ln();
		   
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,8,$rec["Supplier"]["name"],'LTR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
		   $doc->SetFont('ArialCE','B',10);
		   $doc->Cell(80,8, 'Medjuskladisnica *'.$rec["Receiving"]["number"],'LTRB',0,'C');

		   $dt = date('d.m.Y', strtotime($rec["Receiving"]["created"]));
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,5,'  ','LR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
		   $doc->SetFont('Courier','',8);
		   $doc->Cell(80,5,"Broj dokumenta:    ".$rec["Receiving"]["number"],'LR',0);
		   
		   $doc->Ln();
		   if($rec["Supplier"]["id"] != null)
		   {
			   $doc->SetFont('ArialCE','B',12);  
			   $doc->Cell(80,5,$rec["Supplier"]["address"].' '.$rec["Supplier"]["city"],'LR',0);
			   $doc->Cell(20);
		   }
		   else
		   {
			   $doc->Cell(100);
		   }
		   $doc->SetFont('Courier','',8);
		   $doc->Cell(80,5,"Datum dokumenta:   ".$dt,'LR',0);
		   $doc->Ln();

		   $doc->SetFont('ArialCE','B',12);  
		   $doc->Cell(80,5,'  ','LR',0);
		   $doc->Cell(20);
		   $doc->SetFont('Courier','',8);
		   $doc->Cell(80,5,"Jedinica:             ".$restPlaceid["Setting"]["value"],'LBR',0);
		   $doc->Ln();
		   
		   $doc->SetFont('ArialCE','',8);  
		   $doc->Cell(80,5,"OIB: ".$rec["Supplier"]["oib"],'LRB',0,'R');
		   $doc->Ln(10);
		   
		   $doc->SetFont('ArialCE','B',8);
		   
		   // Column headings
		   
		   // Colors, line width and bold font
			$doc->SetFillColor(255,255,255); // slova  u headeru
	   

		   $header = array('Red.br','Sifra','Naziv artikla/usluge', 'Kolicina', 'Nab. Cj.', 'Nab.Vrijed.', 'VPC', 'Vrijednost Kn', 'MPC','Vrijednost Kn');
		   
		   $w = array(20,40,50,20,20,30,20,30,20,30);
		   for($i=0;$i<count($header);$i++)
			   $doc->Cell($w[$i],7,$header[$i],0,0,'C',true);
		   $doc->Ln();
	   
		   $fill = false;
		   
		   $items=$this->Receiving->ReceivingItem->find('all', array(
		   'conditions' => array('ReceivingItem.receiving_id' => $id)
		   ));
		   $doc->SetFont('ArialCE','',8);
		   $priceBuy = 0;
		   $price = 0;
		   $vpc = 0;
		   $redbr = 1;
		   foreach($items as $item)    
		   {
			   $doc->Cell($w[0],6,$redbr,0,0,'C',$fill);
			   $doc->Cell($w[1],6,$item["Article"]["barcode"],0,0,'L',$fill);
			   $doc->Cell($w[2],6,$item["Article"]["name"],0,0,'L',$fill);
			   $doc->Cell($w[3],6,number_format(-$item["ReceivingItem"]["amount"],2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[4],6,number_format(-$item["ReceivingItem"]["price_buy"],2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[5],6,number_format(-$item["ReceivingItem"]["price_buy"]*$item["ReceivingItem"]["amount"],2, '.', ' '),0,0,'R',$fill);
			   // VPC !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			   $doc->Cell($w[6],6,number_format(0,2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[7],6,number_format(0,2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[8],6,number_format(-$item["ReceivingItem"]["price_sell"],2, '.', ' '),0,0,'R',$fill);
			   $doc->Cell($w[9],6,number_format(-$item["ReceivingItem"]["amount"]*$item["ReceivingItem"]["price_sell"],2, '.', ' '),0,0,'R',$fill);
			   
			   $doc->Ln();
			   
			   $priceBuy = $priceBuy + $item["ReceivingItem"]["price_buy"]*$item["ReceivingItem"]["amount"];
			   $price = $price + $item["ReceivingItem"]["price_sell"]*$item["ReceivingItem"]["amount"];
			   //!!!!!!!!!!
			   $vpc = $vpc + 0;
			   $redbr = $redbr+1;
			   // $fill = !$fill;
		   }
		   
		   // Closing line
		   $doc->Cell(array_sum($w),0,'','T');
		   $doc->Ln();
		   $doc->Cell($w[0]+$w[1]+$w[2]+$w[3]+$w[4],6,'',0,0,'L',$fill);
		   $doc->Cell($w[5],6,number_format($priceBuy,2, '.', ' '),0,0,'R',$fill);
		   $doc->Cell($w[6],6,'',0,0,'R',$fill);
		   $doc->Cell($w[7],6,number_format($vpc,2, '.', ' '),0,0,'R',$fill);
		   $doc->Cell($w[8],6,'',0,0,'R',$fill);
		   $doc->Cell($w[9],6,number_format($price,2, '.', ' '),0,0,'R',$fill);
		   
		   $doc->Ln();
		   $doc->Cell(array_sum($w),0,'','T');
		   $doc->Ln(40);
		   
		   $doc->Cell(110);
		   $doc->Cell(50,20,"Obradio",'B',0,'C');
		   $doc->Ln();
	   
		   $doc->output();
		   die();
	   }
	   */

	function print_receiving_order($id = null)
	{

		$doc = new Document;
		$doc->AddPage();
		$restName = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.name')
		));

		// $restAddress=$this->Setting->find('first', array(
		// 'conditions' => array('Setting.name' => 'invoice.header')
		// ));
		// $doc->Cell(0,5,$restAddress["Setting"]["value"],0,0);



		// $doc->Ln(10);
		// $doc->Cell(80);
		// $doc->SetFont('Times','B',16);  // za naslov
		// $doc->Cell(30,10, 'Narudzba','B',1,'C');


		$rec = $this->ReceivingOrder->find('first', array(
			'conditions' => array('ReceivingOrder.id' => $id)
		));

		$items = $this->ReceivingOrder->ReceivingOrderItem->find('all', array(
			'conditions' => array('ReceivingOrderItem.receiving_order_id' => $id)
		));

		// $doc->SetFont('Courier','I',12);
		// $doc->Cell(0,10,"Broj:              ".$rec["ReceivingOrder"]["number"],0,0);
		// $doc->Ln(8);
		// $doc->Cell(0,10,"Dobavljac:         ".$rec["Supplier"]["name"],0,0);
		// $doc->Ln(8);

		// $doc->Cell(0,10,"Datum kreiranja:   ".$rec["ReceivingOrder"]["created"],0,0);
		// $doc->Ln(8);
		// $doc->Cell(0,10,"Kreirao:           ".$rec["ReceivingOrder"]["created_by"],0,0);
		// $doc->Ln(15); //h

		// $doc->SetFont('Times','B',14);
		// $doc->Cell(0,10, "Artikli",0,1);
		// $doc->Ln(10);
		// $doc->SetFont('Courier','I',12);

		//header
		$doc->Cell(100);
		$doc->Cell(0, 5, $restName["Setting"]["value"], 0, 2);
		$doc->SetFont('ArialCE', '', 10);

		$restpost = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.post')
		));
		$restComm = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.resort')
		));
		$restStreet = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.street')
		));
		$restStrNum = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num')
		));
		$restStrNumMark = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num_mark')
		));
		$doc->Cell(0, 5, $restpost["Setting"]["value"] . ' ' . $restComm["Setting"]["value"] . ',' . $restStreet["Setting"]["value"] . ' ' . $restStrNum["Setting"]["value"] . $restStrNumMark["Setting"]["value"], 0, 2);

		$restPlaceid = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.placeid')
		));
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(0, 5, $restPlaceid["Setting"]["value"], 0, 0);


		$doc->Ln();
		// $doc->Cell(100);
		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(80, 8, $rec["Supplier"]["name"], 'LTR', 0);
		$doc->Cell(20);
		$doc->SetFont('ArialCE', 'B', 10);

		$doc->Cell(80, 8, 'Narudžbe-Dobavljaci *' . $rec["ReceivingOrder"]["number"], 'LTRB', 0, 'C');

		$dt = date('d.m.Y', strtotime($rec["ReceivingOrder"]["created"]));

		$doc->Ln();
		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(80, 5, '  ', 'LR', 0);
		$doc->Cell(20);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(80, 5, "Broj dokumenta:    " . $rec["ReceivingOrder"]["number"], 'LR', 0);

		$doc->Ln();
		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(80, 5, $rec["Supplier"]["address"] . ' ' . $rec["Supplier"]["city"], 'LR', 0);
		$doc->Cell(20);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(80, 5, "Datum dokumenta:   " . $dt, 'LBR', 0);
		$doc->Ln();

		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(80, 5, "OIB: " . $rec["Supplier"]["oib"], 'LRB', 0, 'R');
		$doc->Ln(10);
		$doc->SetFont('ArialCE', 'B', 8);
		// Column headings

		// Colors, line width and bold font
		$doc->SetFillColor(255, 255, 255); // slova  u headeru
		// $doc->SetTextColor(255);
		// $doc->SetDrawColor(128,0,0); // linije tabele
		// $doc->SetLineWidth(.3);
		// $doc->SetFont('','B',12);
		$header = array('RB', 'Sifra', 'Naziv artikla/usluge', 'Kolicina');

		$w = array(10, 55, 100, 25);
		for ($i = 0; $i < count($header); $i++)
			$doc->Cell($w[$i], 7, $header[$i], 0, 0, 'C', true);
		$doc->Ln();
		// Color and font restoration
		// $doc->SetFillColor(221, 247, 169);
		// $doc->SetTextColor(0);
		// $doc->SetFont('');
		// Data
		$fill = false;
		$doc->SetFont('ArialCE', '', 8);
		$rb = 1;
		foreach ($items as $item) {
			$doc->Cell($w[0], 6, $rb, 0, 0, 'C', $fill);
			$doc->Cell($w[1], 6, $item["Article"]["barcode"], 0, 0, 'C', $fill);
			$doc->Cell($w[2], 6, $item["Article"]["name"], 0, 0, 'C', $fill);
			$doc->Cell($w[3], 6, number_format($item["ReceivingOrderItem"]["amount"], 2, '.', ' '), 0, 0, 'C', $fill);
			$doc->Ln();
			$rb = $rb + 1;
			// $fill = !$fill;
		}
		// Closing line
		$doc->Ln();
		$doc->Cell(190, 0, '', 'T');

		$doc->Ln(40);

		$doc->Cell(65);
		$doc->Cell(50, 20, "Obradio", 'B', 0, 'C');
		$doc->Ln();
		$doc->output();
		die();
	}


	function price_changes($doc_id = null)
	{
		$doc = new Document;

		$doc->AddPage();
		$restName = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.name')
		));

		$doc->Cell(100);
		$doc->Cell(0, 5, $restName["Setting"]["value"], 0, 2);
		$doc->SetFont('ArialCE', '', 10);

		$restpost = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.post')
		));
		$restComm = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.resort')
		));
		$restStreet = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.street')
		));
		$restStrNum = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num')
		));
		$restStrNumMark = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.str_num_mark')
		));
		$doc->Cell(0, 5, $restpost["Setting"]["value"] . ' ' . $restComm["Setting"]["value"] . ',' . $restStreet["Setting"]["value"] . ' ' . $restStrNum["Setting"]["value"] . $restStrNumMark["Setting"]["value"], 0, 2);

		$restPlaceid = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.placeid')
		));
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(0, 5, $restPlaceid["Setting"]["value"], 0, 0);

		$inventArt = $this->InventoryArticles->find('all', array(
			'conditions' => array('InventoryArticles.id' => $doc_id)
		));

		$doc->Ln();
		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(100);
		$doc->Cell(90, 8, "Zapisnik o promjeni cijena *" . $doc_id, 'LTRB', 0, 'C');
		$doc->Ln();
		$doc->Cell(100);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(90, 8, "Broj dokumenta:    " . $doc_id, 'LBR', 0, 1);
		// $doc->Cell(80,5,"Datum dokumenta:   ".$inventArt["InventoryArticles"]["date"],'LRB',0,1);
		// nemamo ovaj datum dokumenta
		$doc->Ln(12);
		$doc->SetFont('ArialCE', 'B', 8);

		// Column headings

		// Colors, line width and bold font
		$doc->SetFillColor(255, 255, 255); // slova  u headeru

		$header = array('Red.br', 'Datum', 'Razlog', 'Sifra', 'Naziv artikla/usluge', 'Kolicina', 'Stara PC', 'Nova PC', 'Ukupno');
		$w = array(10, 22, 23, 20, 35, 20, 20, 20, 20);
		for ($i = 0; $i < count($header); $i++)
			$doc->Cell($w[$i], 7, $header[$i], 0, 0, 'C', true);
		$doc->Ln();
		$fill = false;

		$doc->SetFont('ArialCE', '', 8);
		$rb = 1;
		$sum = 0;
		foreach ($inventArt as $item) {
			$article = $this->Article->find('first', array(
				'conditions' => array('Article.barcode' => $item["InventoryArticles"]["article_code"])
			));
			$doc->Cell($w[0], 6, $rb, 0, 0, 'C');
			$dt = date('d.m.Y', strtotime($item["InventoryArticles"]["date"]));
			// U BAZI NEMAMO OVAJ DATUM!!!!!!!
			$doc->Cell($w[1], 6, $dt, 0, 0, 'C', $fill);
			//?? razlog ( string)
			$doc->Cell($w[2], 6, $item["InventoryArticles"]["document_type"], 0, 0, 'L', $fill);
			$doc->Cell($w[3], 6, $item["InventoryArticles"]["article_code"], 0, 0, 'L', $fill);
			$doc->Cell($w[4], 6, $article["Article"]["name"], 0, 0, 'L', $fill);
			$doc->Cell($w[5], 6, number_format($item["InventoryArticles"]["debit_amount"] - $item["InventoryArticles"]["credit_amount"]), 0, 0, 'R', $fill);  // AMOUNT??

			$novaCena = $this->RetailItem->query(
				"select (sum(debit_cash)-sum(credit_cash))/(sum(debit_amount-credit_amount)) as nc from inventory_articles where article_code=" . $item["InventoryArticles"]["article_code"] . " and id<= " . $item["InventoryArticles"]["id"]
			);
			$staraCena = $this->RetailItem->query(
				"select (sum(debit_cash)-sum(credit_cash))/(sum(debit_amount-credit_amount)) as sc from inventory_articles where article_code=" . $item["InventoryArticles"]["article_code"] . " and id< " . $item["InventoryArticles"]["id"]
			);

			$doc->Cell($w[6], 6, number_format($staraCena[0][0]['sc'], 2, '.', ' '), 0, 0, 'R', $fill); //STARA PC??
			$doc->Cell($w[7], 6, number_format($novaCena[0][0]['nc'], 2, '.', ' '), 0, 0, 'R', $fill); //NOVA PC???
			$doc->Cell($w[8], 6, number_format($novaCena[0][0]['nc'] - $staraCena[0][0]['sc'], 2, '.', ' '), 0, 0, 'R', $fill); //ukupno

			$sum = $sum + $novaCena[0][0]['nc'] - $staraCena[0][0]['sc']; // ukupno!
			$rb = $rb + 1;
			$doc->Ln();
		}

		$doc->Cell(array_sum($w), 0, '', 'T');
		$doc->Ln();
		$doc->Cell(array_sum($w) - $w[8]);
		$doc->Cell($w[8], 6, number_format($sum), 0, 0, 'R', $fill);
		$doc->Ln();
		$doc->Cell(array_sum($w), 0, '', 'T');

		$doc->Ln();

		$doc->output();
		die();
	}





	function print_sale($id = null)
	{
		// die();

		$g_v = get_valuta();


		$r = false;
		$rec = $this->Sale->find('first', array(
			'conditions' => array('Sale.id' => $id)
		));

		$restFooter = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'invoice.footer')));
		$restFooterA4 = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'invoice.footerA4')));

		$doc = new Document("", $restFooter["Setting"]["value"], $restFooterA4["Setting"]["value"]);  // bez note dole u footeru

		$doc->AddFont("ArialCE", "B", "6488f5d4657b269b9f5770508e80e299_arialbd.php");
		$doc->AddFont("ArialCE", "", "332cc83ebee36613c19564e6e776c81b_arial.php");
		$doc->AddFont("Helvetica", "B", "6488f5d4657b269b9f5770508e80e299_arialbd.php");
		$doc->AddFont("Helvetica", "", "332cc83ebee36613c19564e6e776c81b_arial.php");
		$doc->AddFont("Courier", "", "cour.php");

		$doc->AddPage();
		$doc->SetFont("ArialCE", "B", 10);

		$restName = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.name')
		));


		$items = $this->Sale->SaleItem->find('all', array(
			'conditions' => array('SaleItem.sale_id' => $id)
		));

		//header


		$has_header = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'invoice.headerYesNo')));
		$l_has_header = $has_header["Setting"]["value"];


		if ($l_has_header == 'yes') {
			$doc->Cell(90);
			$doc->Cell(0, 5, _convert($restName["Setting"]["value"]), 0, 2);
			$doc->SetFont('ArialCE', '', 8);
		}

		/*
			  $restpost=$this->Setting->find('first', array(
			  'conditions' => array('Setting.name' => 'general.post')
			  ));
			  $restComm=$this->Setting->find('first', array(
			  'conditions' => array('Setting.name' => 'general.resort')
			  ));
			  $restStreet=$this->Setting->find('first', array(
			  'conditions' => array('Setting.name' => 'general.street')
			  ));
			  $restStrNum=$this->Setting->find('first', array(
			  'conditions' => array('Setting.name' => 'general.str_num')
			  ));
			  $restStrNumMark=$this->Setting->find('first', array(
			  'conditions' => array('Setting.name' => 'general.str_num_mark')
			  ));
			  if($l_has_header == 'yes'){
				  $doc->Cell(0,5,_convert($restpost["Setting"]["value"].' '.$restComm["Setting"]["value"].','.$restStreet["Setting"]["value"].' '.
					  $restStrNum["Setting"]["value"].$restStrNumMark["Setting"]["value"]),0,2);
			  }
			  */

		/*
			  $restOib=$this->Setting->find('first', array(
			  'conditions' => array('Setting.name' => 'general.oib')
			  ));
			  
			  if($l_has_header == 'yes'){
				  $doc->Cell(150,5,'OIB: '._convert($restOib["Setting"]["value"]),0,2);
			  }
			  */
		$restHeaderBasic = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'invoice.header')
		));

		$doc->MultiCell(100, 5, _convert($restHeaderBasic["Setting"]["value"]), 0, 2);

		$restHeader = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'invoice.headerA4')
		));

		if ($l_has_header == 'yes') {
			$doc->SetFont('ArialCE', '', 8);
			$doc->Cell(0, 6, _convert($restHeader["Setting"]["value"]), 0, 0);
		}

		if ($l_has_header != 'yes') {
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
			$doc->Cell(0, 5, _convert(''), 0, 2);
		}


		$doc->Ln(2);
		file_put_contents('tmppdfcode.png', $this->getBarcodeForDocument($rec, 'racuni'));
		$doc->Image('tmppdfcode.png', 10, 10, 50, 0, 'PNG');
		unlink('tmppdfcode.png');

		//------------------------------------------------ R1
		if ($rec["Sale"]["customer_id"] != null) {
			$doc->Ln();
			// $doc->Cell(100);


			//$doc->SetFont('ArialCE','B',12);
			//$doc->Cell(80,8,_convert($rec["Customer"]["name"]),'LTR',0);

			$doc->SetFont('ArialCE', 'B', 11);
			$la_name_lines = presijeci_tekst($rec["Customer"]["name"], 20);

			$doc->Cell(80, 8, _convert($la_name_lines[0]), 'LTR', 0);


			$doc->Cell(10);
			$doc->SetFont('ArialCE', 'B', 10);
			$y = date('Y', strtotime($rec["Sale"]["created"]));

			$restR = $this->Setting->find('first', array(
				'conditions' => array('Setting.name' => 'general.R')
			));

			//$doc->Cell(100,8, 'Racun R'.$restR["Setting"]["value"].' * '.$rec["Sale"]["number"],'LTRB',0,'C');

			if (isset($_GET['url']) && strstr($_GET['url'], '/o/1')) {
				$doc->Cell(100, 8, 'Otpremnica: ' . _convert($rec["Sale"]["number"]), 'LTRB', 0, 'C');
			} else {
				$doc->Cell(100, 8, 'Racun: ' . _convert($rec["Sale"]["number"]), 'LTRB', 0, 'C');
			}


			$dt = date('d.m.Y. H:i:s', strtotime($rec["Sale"]["created"]));

			$doc->Ln();
			$doc->SetFont('ArialCE', 'B', 11);
			$doc->Cell(80, 5, _convert($la_name_lines[1]), 'LR', 0);
			$doc->SetFont('ArialCE', 'B', 8);
			$doc->Cell(10);
			$doc->SetFont('Courier', '', 8);
			$doc->Cell(100, 5, "Broj dokumenta:  " . _convert($rec["Sale"]["number"]), 'LR', 0);

			$doc->Ln();
			$doc->SetFont('ArialCE', 'B', 8);
			$doc->Cell(80, 5, _convert($rec["Customer"]["zip"] . ' ' . $rec["Customer"]["city"] . ', ' . $rec["Customer"]["address"]), 'LR', 0);
			$doc->Cell(10);
			$doc->SetFont('Courier', '', 8);
			$restIssue = $this->Setting->find('first', array(
				'conditions' => array('Setting.name' => 'general.place_of_issue')
			));
			$doc->Cell(100, 5, _convert("Datum dokumenta: " . $dt . ", " . $restIssue["Setting"]["value"]), 'LR', 0);
			$doc->Ln();

			$komentar = $rec["Sale"]["note"];
			if ($komentar == null)
				$komentar = $rec["Customer"]["note"];

			if ($rec["Customer"]["bank_account"] != null)
				$bankaZarez = $rec["Customer"]["bank_account"] . ', ';
			else
				$bankaZarez = '';


			if ($rec["Sale"]["jir"] != null) {
				$doc->SetFont('ArialCE', '', 8);
				$doc->Cell(80, 5, _convert($bankaZarez . $rec["Customer"]["phone"]), 'LR', 0, 'L');
				$doc->Cell(10);
				$doc->SetFont('Courier', '', 8);
				$doc->Cell(100, 5, "JIR:             " . _convert($rec["Sale"]["jir"]), 'LR', 0);
				$doc->Ln();

				if ($rec["Sale"]["kod"] != null) { // ima jira ima koda
					$doc->SetFont('ArialCE', '', 8);
					$doc->Cell(80, 5, _convert(''), 'LR', 0, 'L');
					$doc->Cell(10);
					$doc->SetFont('Courier', '', 8);
					$doc->Cell(100, 5, "Zastitni kod:    " . _convert($rec["Sale"]["kod"]), 'LR', 0);
					$doc->Ln();
				} else // ima jira nema koda
				{
					$doc->Cell(80, 5, _convert(''), 'LR', 0, 'L');
					$doc->Cell(10);
					$doc->Cell(100, 5, '', 'LR', 0);
					$doc->Ln();
				}
			} else {
				if ($rec["Sale"]["kod"] != null) { // nema jira ima koda
					$doc->SetFont('ArialCE', '', 8);
					$doc->Cell(80, 5, _convert($bankaZarez . $rec["Customer"]["phone"]), 'LR', 0, 'L');
					$doc->Cell(10);
					$doc->SetFont('Courier', '', 8);
					$doc->Cell(100, 5, "Zastitni kod:    " . _convert($rec["Sale"]["kod"]), 'LR', 0);
					$doc->Ln();

					$doc->SetFont('ArialCE', '', 8);
					$doc->Cell(80, 5, _convert(''), 'LR', 0, 'L');
					$doc->Cell(10);
					$doc->Cell(100, 5, '', 'LR', 0);
					$doc->Ln();
				} else // nema jira nema koda
				{
					$doc->SetFont('ArialCE', '', 8);
					$doc->Cell(80, 5, _convert($bankaZarez . $rec["Customer"]["phone"]), 'LR', 0, 0, 'L');
					$doc->Ln();
					$doc->Cell(80, 5, _convert(''), 'LR', 0, 'L');
					$doc->Ln();
				}
			}

			// if($rec["Sale"]["note"]!= null)
			// {

			// if($rec["Sale"]["note"]!= $rec["Customer"]["note"])
			// {
			// $doc->SetFont('ArialCE','',8);  
			// $doc->Cell(80,5,$rec["Sale"]["note"], 'LR', 0,'L');
			// $doc->Cell(10);
			// if($rec["Sale"]["sale_id_storno"]!= null) // ima note ima storno
			// {
			// $doc->Cell(90);
			// $numS = $this->Sale->find('all', array(
			// 'conditions' => array('Sale.id' => $rec["Sale"]["sale_id_storno"])
			// ));

			// $doc->Cell(100,5,"Veza storno racun br: ".$numS[0]["Sale"]["number"],'LR',0);
			// }
			// else
			// {
			// $doc->Cell(100,5,"",'LR',0);
			// }
			// }

			// $doc->SetFont('ArialCE','',8);  
			// $doc->Cell(80,5,"OIB: ".$rec["Customer"]["oib"],'LRB',0,'R');
			// $doc->Cell(10);
			// $doc->SetFont('Courier','',8);
			// if($rec["Sale"]["paragon"]!= null)
			// {
			// $doc->Cell(100,5,"Paragon broj:    ".$rec["Sale"]["paragon"],'LR',0);

			// }
			// else
			// $doc->Cell(100,5,"",'LR',0);

			// $doc->Ln();
			// }
			// else // nema note

			// {
			$doc->SetFont('ArialCE', '', 8);
			$doc->Cell(80, 5, "OIB: " . _convert($rec["Customer"]["oib"]), 'LRB', 0, 'R');
			$doc->Cell(10);
			$doc->SetFont('Courier', '', 8);

			if ($rec["Sale"]["sale_id_storno"] != null) // OIB & storno
			{
				$numS = $this->Sale->find('all', array(
					'conditions' => array('Sale.id' => $rec["Sale"]["sale_id_storno"])
				));

				$doc->Cell(100, 5, "Veza storno racun br: " . _convert($numS[0]["Sale"]["number"]), 'LR', 0);
			} else // oib & nista
			{
				$doc->Cell(100, 5, "", 'LR', 0);
			}


			if ($rec["Sale"]["paragon"] != null) {
				$doc->Ln();
				$doc->Cell(90);
				$doc->SetFont('Courier', '', 8);
				$doc->Cell(100, 5, "Paragon broj:    " . _convert($rec["Sale"]["paragon"]), 'LR', 0);

			}

			$doc->Ln();

			// }

			$doc->Cell(80, 1, '', 0, 0, 'R');
			$doc->Cell(10);
			$doc->Cell(100, 1, '', 'LRB', 0);
			$doc->Ln(2);




			//$doc->SetFont('ArialCE','',8);
			//$doc->Cell(80,5,_convert($komentar == '' ? "" : "Napomena: ".$komentar),'',0,'L');
			//$doc->Ln(10);




			$doc->SetFont('ArialCE', 'B', 8);
		} else

		// bez kupca---------------------------------------
		{
			$doc->Ln();
			//$doc->Cell(100);

			$doc->SetFont('ArialCE', 'B', 8);
			$doc->Cell(80, 5, '  ', 0, 0);
			$doc->Cell(10);
			$doc->SetFont('ArialCE', 'B', 10);


			if (isset($_GET['url']) && strstr($_GET['url'], '/o/1')) {
				$doc->Cell(100, 8, 'Otpremnica: ' . _convert($rec["Sale"]["number"]), 'LTRB', 0, 'C');
			} else {
				$doc->Cell(100, 8, 'Racun: ' . _convert($rec["Sale"]["number"]), 'LTRB', 0, 'C');
			}

			$dt = date('d.m.Y. H:i:s', strtotime($rec["Sale"]["created"]));


			$doc->Ln();
			$doc->SetFont('ArialCE', 'B', 8);
			$doc->Cell(80, 5, '  ', 0, 0);
			$doc->Cell(10);
			$doc->SetFont('Courier', '', 8);
			$doc->Cell(100, 5, "Broj dokumenta:  " . _convert($rec["Sale"]["number"]), 'LR', 0);

			$doc->Ln();
			$doc->Cell(80, 5, '  ', 0, 0);
			$doc->Cell(10);
			$doc->SetFont('Courier', '', 8);
			$restIssue = $this->Setting->find('first', array(
				'conditions' => array('Setting.name' => 'general.place_of_issue')
			));
			$doc->Cell(100, 5, _convert("Datum dokumenta: " . $dt . ", " . $restIssue["Setting"]["value"]), 'LR', 0);

			$doc->Ln();

			if ($rec["Sale"]["jir"] != null) {
				$doc->Cell(80, 5, '  ', 0, 0);
				$doc->Cell(10);
				$doc->SetFont('Courier', '', 8);
				$doc->Cell(100, 5, "JIR:             " . _convert($rec["Sale"]["jir"]), 'LR', 0);
				$doc->Ln();
			}

			if ($rec["Sale"]["kod"] != null) {
				$doc->Cell(80, 5, '  ', 0, 0);
				$doc->Cell(10);
				$doc->SetFont('Courier', '', 8);
				$doc->Cell(100, 5, "Zastitni kod:    " . _convert($rec["Sale"]["kod"]), 'LR', 0);
				$doc->Ln();
			}

			$doc->Cell(80, 5, '  ', 0, 0);
			$doc->Cell(10);
			$doc->SetFont('Courier', '', 8);
			if ($rec["Sale"]["sale_id_storno"] != null) {
				$numS = $this->Sale->find('all', array(
					'conditions' => array('Sale.id' => $rec["Sale"]["sale_id_storno"])
				));

				$doc->Cell(100, 5, "Veza storno racun br: " . _convert($numS[0]["Sale"]["number"]), 'LR', 0);
			} else {
				$doc->Cell(100, 5, "", 'LR', 0);
			}
			$doc->Ln();


			/*
					 if($rec["Sale"]["note"]!= null){
						 $doc->Cell(80,5,'',0,0,'R');
						 $doc->Cell(10);
						 $doc->Cell(100,5,"Napomena:        "._convert($rec["Sale"]["note"]),'LR',0);
						 $doc->Ln();
					 }
					 */



			if ($rec["Sale"]["paragon"] != null) {
				$doc->Cell(80, 5, '', 0, 0, 'R');
				$doc->Cell(10);
				$doc->Cell(100, 5, "Paragon broj:    " . _convert($rec["Sale"]["paragon"]), 'LR', 0);
				$doc->Ln();
			}


			$doc->Cell(80, 1, '', 0, 0, 'R');
			$doc->Cell(10);
			$doc->Cell(100, 1, '', 'LRB', 0);
			$doc->Ln(3);




			/*
					 if($rec["Sale"]["note"]!= null){
						 $doc->SetFont('ArialCE','',8);
						 //$doc->Cell(1);
						 $doc->Cell(100,5,"Napomena: "._convert($rec["Sale"]["note"]),'',0);
						 $doc->Ln(10);
					 }else{
						 $doc->Ln(7);
					 }
					 
					 */



			$doc->SetFont('ArialCE', 'B', 8);

		}
		// Column headings

		// Colors, line width and bold font
		$doc->SetFillColor(255, 255, 255); // slova  u headeru




		$l_pdv = get_item('select value from settings where name = "duty.free" ');

		if ($l_pdv == 'no') {
			$l_pdv = 'false';
		}

		if ($l_pdv == 'false') {
			// nema pdv-a
		} else {
			// ima pdv-a
		}





		if (isset($_GET['url']) && strstr($_GET['url'], '/vp/1')) {

			$header = array('RB', 'Sifra', 'Naziv artikla/usluge', 'Kolicina', 'VPC', 'Popust %', 'Vr.Popust', 'Iz. Popust', 'Cijena ' . $g_v, 'Vrijednost ' . $g_v);
			$w = array(10, 30, 40, 13, 15, 15, 15, 15, 17, 20);
			for ($i = 0; $i < count($header); $i++) {
				$doc->Cell($w[$i], 8, _convert($header[$i]), 'TB', 0, 'C', true);
			}

		} else {
			if (isset($_GET['url']) && strstr($_GET['url'], '/o/1')) {

				$header = array('RB', 'Sifra', 'Naziv artikla/usluge', 'Kolicina');
				$w = array(10, 30, 45, 15);
				for ($i = 0; $i < count($header); $i++) {
					$doc->Cell($w[$i], 8, _convert($header[$i]), 'TB', 0, 'L', true);
				}

			} else {

				if (isset($_GET['url']) && strstr($_GET['url'], '/skraceno/1')) {
					$header = array('RB', '', 'Naziv artikla/usluge', 'Kolicina', '', '', '', '', '', 'Vrijednost ' . $g_v);
					$w = array(10, 10, 88, 14, 1, 1, 1, 1, 42, 22);
					for ($i = 0; $i < count($header); $i++) {
						$doc->Cell($w[$i], 8, _convert($header[$i]), 'TB', 0, 'L', true);
					}
				} else {
					$header = array('RB', 'Sifra', 'Naziv artikla/usluge', 'Kolicina', 'MPC', 'Popust %', 'Vr.Popust', 'Iz. Popust', 'Cijena ' . $g_v, 'Vrijednost ' . $g_v);
					$w = array(10, 30, 40, 13, 15, 15, 15, 15, 17, 20);
					for ($i = 0; $i < count($header); $i++) {
						$doc->Cell($w[$i], 8, _convert($header[$i]), 'TB', 0, 'C', true);
					}
				}

			}
		}


		$doc->Ln();

		// Color and font restoration
		$doc->SetFillColor(221, 247, 169);
		$doc->SetTextColor(0);
		$doc->SetFont('');
		$fill = false;

		$items = $this->Sale->RetailItem->find('all', array(
			'conditions' => array('RetailItem.sale_id' => $id)
		));
		if ($items)
			$r = true;
		else {
			$items = $this->Sale->SaleItem->find('all', array(
				'conditions' => array('SaleItem.sale_id' => $id)
			));
		}
		;


		//print_r($items);
		//exit;


		$l_euro_info = ($this->get_item('select value from settings where name = "general.euro" limit 1 ')) == 'yes';
		$l_euro_exchange_rate = $this->get_item('select value from settings where name = "general.euro_exchange_rate" limit 1 ');

		$l_old_year = get_item('select value from settings where name = "general.old_year" ');


		$restPDV = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'duty.free')
		));


		$doc->SetFont('ArialCE', '', 8);
		$rb = 1;
		$sumPrice = 0;
		$sumPrice_bez_popust = 0;
		$sum_popust = 0;
		if ($r) {
			foreach ($items as $item) {
				$doc->Cell($w[0], 6, $rb, 0, 0, 'C', $fill);
				if (isset($_GET['url']) && strstr($_GET['url'], '/skraceno/1')) {
					$doc->Cell($w[1], 6, '', 0, 0, 'L', $fill);
				} else {
					$doc->Cell($w[1], 5, _convert($item["Article"]["barcode"]), 0, 0, 'L', $fill);
				}
				$posY = $doc->GetY();
				$posX = $doc->GetX();
				$nl = 0;
				if (strlen($item["Article"]["name"]) > 24) {
					$temptext = str_split($item["Article"]["name"], 24);
					foreach ($temptext as $newline) {
						$doc->Cell($w[2], 3, _convert($newline), 0, 2, 'L');
						$nl += 1;
					}
					$posX += $w[2];
					$doc->SetY($posY);
					$posY += $nl * 3; // pozicija sledeceg reda
				} else {
					$doc->Cell($w[2], 5, _convert($item["Article"]["name"]), 0, 0, 'L', $fill);
					$posX = $doc->GetX();
					$posY += 6;
				}













				if (isset($_GET['url']) && strstr($_GET['url'], '/vp/1')) {

					if ($restPDV["Setting"]["value"] == 'yes') { // AKO JESTE U PDV
						$l_pdv_podijeli = $item["RetailItem"]['tax_1'] / 100;
					} else {
						$l_pdv_podijeli = 0;
					}


					$doc->SetX($posX);

					$doc->Cell($w[3], 6, number_format($item["RetailItem"]["amount"], 2, '.', ' '), 0, 0, 'R', $fill);

					$l_iznos = $item["RetailItem"]["base_price"] / (1 + $l_pdv_podijeli);
					$doc->Cell($w[4], 6, number_format($l_iznos, 2, '.', ' '), 0, 0, 'R', $fill);

					$doc->Cell($w[5], 6, number_format($item["RetailItem"]["discount_percent"], 2), 0, 0, 'R', $fill);

					$doc->Cell($w[6], 6, number_format($l_iznos * $item["RetailItem"]["discount_percent"] / 100, 2), 0, 0, 'R', $fill);

					$doc->Cell($w[7], 6, number_format($item["RetailItem"]["amount"] * $l_iznos * $item["RetailItem"]["discount_percent"] / 100, 2), 0, 0, 'R', $fill);

					$doc->Cell($w[8], 6, number_format($l_iznos - ($l_iznos * $item["RetailItem"]["discount_percent"] / 100), 2, '.', ' '), 0, 0, 'R', $fill);

					$l_ukup = ($item["RetailItem"]["price"] - $item["RetailItem"]["feedback_compensation"]) / (1 + $l_pdv_podijeli);
					$doc->Cell($w[9], 6, number_format($l_ukup, 2, '.', ' '), 0, 0, 'R', $fill);


					$doc->Ln();
					$rb = $rb + 1;

					$sumPrice += $l_ukup;
					$sum_popust += $item["RetailItem"]["discount_percent"] * $l_iznos * $item["RetailItem"]["amount"] / 100;

					$doc->SetY($posY);

				} else {

					if (isset($_GET['url']) && strstr($_GET['url'], '/o/1')) {

						$doc->SetX($posX);

						$doc->Cell($w[3], 6, number_format($item["RetailItem"]["amount"], 2, '.', ' '), 0, 0, 'R', $fill);

						$doc->Ln();
						$rb = $rb + 1;

						$doc->SetY($posY);

					} else {

						if (isset($_GET['url']) && strstr($_GET['url'], '/skraceno/1')) {
							//pe('222');
							$doc->SetX($posX);
							$doc->Cell($w[3], 6, number_format($item["RetailItem"]["amount"], 2, '.', ' '), 0, 0, 'R', $fill);
							$doc->Cell($w[4], 6, '', 0, 0, 'R', $fill);
							$doc->Cell($w[5], 6, '', 0, 0, 'R', $fill);
							$doc->Cell($w[6], 6, '', 0, 0, 'R', $fill);
							$doc->Cell($w[7], 6, '', 0, 0, 'R', $fill);
							$doc->Cell($w[8], 6, '', 0, 0, 'R', $fill);
							$doc->Cell($w[9], 6, number_format($item["RetailItem"]["price"], 2, '.', ' '), 0, 0, 'R', $fill);
							$doc->Ln();
							if (1 == 0 && $l_euro_info) {
								$doc->SetFont('ArialCE', '', 7);
								$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8], 3, '', 0, 0, 'L', $fill);
								$doc->Cell($w[9], 3, number_format($item["RetailItem"]["price"] / $l_euro_exchange_rate, 2) . ' EUR', 0, 0, 'R', $fill);
								$doc->Ln();
								$doc->SetFont('ArialCE', '', 2);
								$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8] + $w[9], 1, '', 0, 0, 'L', $fill);
								$doc->Ln();
								$doc->SetFont('ArialCE', '', 8);
								$posY += 4;
							}
							$rb = $rb + 1;
							$sumPrice += $item["RetailItem"]["price"];
							$sumPrice_bez_popust += $item["RetailItem"]["price"] * ((100.0 / (100.0 - $item["RetailItem"]["discount_percent"])));

							$doc->SetY($posY);
						} else {
							$doc->SetX($posX);
							$doc->Cell($w[3], 5, number_format($item["RetailItem"]["amount"], 2, '.', ' '), 0, 0, 'R', $fill);
							$doc->Cell($w[4], 5, number_format($item["RetailItem"]["base_price"] + $item["RetailItem"]["base_feedback_compensation"], 2, '.', ' '), 0, 0, 'R', $fill);
							$doc->Cell($w[5], 5, number_format($item["RetailItem"]["discount_percent"], 2), 0, 0, 'R', $fill);
							$doc->Cell($w[6], 5, number_format($item["RetailItem"]["discount_percent"] * $item["RetailItem"]["base_price"] / 100, 2), 0, 0, 'R', $fill);
							$doc->Cell($w[7], 5, number_format($item["RetailItem"]["discount_percent"] * $item["RetailItem"]["base_price"] * $item["RetailItem"]["amount"] / 100, 2), 0, 0, 'R', $fill);
							$doc->Cell($w[8], 5, number_format($item["RetailItem"]["price"] / $item["RetailItem"]["amount"], 2, '.', ' '), 0, 0, 'R', $fill);
							$doc->Cell($w[9], 5, number_format($item["RetailItem"]["price"], 2, '.', ' '), 0, 0, 'R', $fill);

							if (1 == 0 && $l_euro_info) {
								$doc->Ln();
								//$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8], 3,'',0,0,'L',$fill);
								//$doc->Cell($w[9],3,'(EUR: '.number_format($item["SaleItem"]["price"] / $l_euro_exchange_rate,2).')',0,0,'R',$fill);

								$doc->Cell($w[0] + $w[1], 4, "", 0, 0, 'C', $fill);
								$doc->Cell($w[2], 4, _convert('EUR: '), 0, 0, 'L', $fill);
								//$doc->Cell($w[3],4,number_format($item["SaleItem"]["amount"], 4),0,0,'R',$fill);
								$doc->Cell($w[3] + $w[4], 5, number_format(($item["RetailItem"]["base_price"] + $item["RetailItem"]["base_feedback_compensation"]) / $l_euro_exchange_rate, 2, '.', ' '), 0, 0, 'R', $fill);
								$doc->Cell($w[5], 5, number_format($item["RetailItem"]["discount_percent"] / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
								$doc->Cell($w[6], 5, number_format($item["RetailItem"]["discount_percent"] * $item["RetailItem"]["base_price"] / 100 / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
								$doc->Cell($w[7], 5, number_format($item["RetailItem"]["discount_percent"] * $item["RetailItem"]["base_price"] * $item["RetailItem"]["amount"] / 100 / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
								$doc->Cell($w[8], 5, number_format($item["RetailItem"]["price"] / $item["RetailItem"]["amount"] / $l_euro_exchange_rate, 2, '.', ' '), 0, 0, 'R', $fill);
								$doc->Cell($w[9], 5, number_format($item["RetailItem"]["price"] / $l_euro_exchange_rate, 2, '.', ' ') . '     ', 0, 0, 'R', $fill);

								$doc->Ln();
								$posY += 4;
							}

							$doc->Ln();
							$rb = $rb + 1;
							$sumPrice += $item["RetailItem"]["price"];
							$sumPrice_bez_popust += $item["RetailItem"]["price"] * ((100.0 / (100.0 - $item["RetailItem"]["discount_percent"])));

							$doc->SetY($posY);
						}

					}


				}

			}
		} else {

			if (isset($_GET['url']) && strstr($_GET['url'], '/skraceno/1')) {
				foreach ($items as $item) {
					$rb = $rb + 1;
					$sumPrice += $item["SaleItem"]["price"];
					$sumPrice_bez_popust += $item["SaleItem"]["price"] * ((100.0 / (100.0 - $item["SaleItem"]["discount_percent"])));
				}
				$doc->Cell($w[0], 6, '1', 0, 0, 'L', $fill);
				$doc->Cell($w[1], 6, "", 0, 0, 'C', $fill);
				$doc->Cell($w[2], 6, _convert('Konzumacija jela i pića'), 0, 0, 'L', $fill);
				$doc->Cell($w[3], 6, number_format(1), 0, 0, 'C', $fill);
				$doc->Cell($w[4], 6, '', 0, 0, 'R', $fill);
				$doc->Cell($w[5], 6, '', 0, 0, 'R', $fill);
				$doc->Cell($w[6], 6, '', 0, 0, 'R', $fill);
				$doc->Cell($w[7], 6, '', 0, 0, 'R', $fill);
				$doc->Cell($w[8], 6, '', 0, 0, 'R', $fill);
				$doc->Cell($w[9], 6, number_format($sumPrice, 2), 0, 0, 'R', $fill);
				$doc->Ln();
				if (1 == 0 && $l_euro_info) {
					$doc->SetFont('ArialCE', '', 7);
					$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8], 3, '', 0, 0, 'L', $fill);
					$doc->Cell($w[9], 3, number_format($sumPrice / $l_euro_exchange_rate, 2) . ' EUR', 0, 0, 'R', $fill);
					$doc->Ln();
					$doc->SetFont('ArialCE', '', 2);
					$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8] + $w[9], 1, '', 0, 0, 'L', $fill);
					$doc->Ln();
					$doc->SetFont('ArialCE', '', 8);
				}
			} else {
				if ($l_euro_info) {
					$doc->SetFont('ArialCE', '', 5);
					$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8] + $w[9], 3, '', 0, 0, 'L', $fill);
					$doc->Ln();
					$doc->SetFont('ArialCE', '', 8);
				}
				foreach ($items as $item) {
					$doc->Cell($w[0], 5, $rb, 0, 0, 'C', $fill);
					$doc->Cell($w[1], 5, "", 0, 0, 'C', $fill);
					$doc->Cell($w[2], 5, _convert(substr($item["Product"]["name_long"], 0, 27)), 0, 0, 'L', $fill);
					$doc->Cell($w[3], 5, number_format($item["SaleItem"]["amount"], 4), 0, 0, 'R', $fill);
					$doc->Cell($w[4], 5, number_format($item["SaleItem"]["price"] / $item["SaleItem"]["amount"] * ((100.0 / (100.0 - $item["SaleItem"]["discount_percent"]))), 2), 0, 0, 'R', $fill);
					$doc->Cell($w[5], 5, number_format($item["SaleItem"]["discount_percent"], 2), 0, 0, 'R', $fill);
					$doc->Cell($w[6], 5, number_format($item["SaleItem"]["discount_percent"] * $item["SaleItem"]["base_price"] / 100, 2), 0, 0, 'R', $fill);
					$doc->Cell($w[7], 5, number_format($item["SaleItem"]["discount_percent"] * $item["SaleItem"]["base_price"] * $item["SaleItem"]["amount"] / 100, 2), 0, 0, 'R', $fill);
					$doc->Cell($w[8], 5, number_format($item["SaleItem"]["price"] / $item["SaleItem"]["amount"], 2), 0, 0, 'R', $fill);
					$doc->Cell($w[9], 5, number_format($item["SaleItem"]["price"], 2), 0, 0, 'R', $fill);
					if (1 == 0 && $l_euro_info) {
						$doc->Ln();
						//$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8], 3,'',0,0,'L',$fill);
						$doc->Cell($w[0] + $w[1], 4, "", 0, 0, 'C', $fill);
						$doc->Cell($w[2], 4, _convert('EUR: '), 0, 0, 'L', $fill);
						//$doc->Cell($w[3],4,number_format($item["SaleItem"]["amount"], 4),0,0,'R',$fill);
						$doc->Cell($w[3] + $w[4], 4, number_format($item["SaleItem"]["price"] / $item["SaleItem"]["amount"] * ((100.0 / (100.0 - $item["SaleItem"]["discount_percent"]))) / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
						$doc->Cell($w[5], 4, number_format($item["SaleItem"]["discount_percent"] / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
						$doc->Cell($w[6], 4, number_format($item["SaleItem"]["discount_percent"] * $item["SaleItem"]["base_price"] / 100 / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
						$doc->Cell($w[7], 4, number_format($item["SaleItem"]["discount_percent"] * $item["SaleItem"]["base_price"] * $item["SaleItem"]["amount"] / 100 / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
						$doc->Cell($w[8], 4, number_format($item["SaleItem"]["price"] / $item["SaleItem"]["amount"] / $l_euro_exchange_rate, 2), 0, 0, 'R', $fill);
						$doc->Cell($w[9], 3, number_format($item["SaleItem"]["price"] / $l_euro_exchange_rate, 2) . '     ', 0, 0, 'R', $fill);
						$doc->Ln();
					}
					$doc->Ln();
					$doc->SetFont('ArialCE', '', 8);
					$rb = $rb + 1;
					$sumPrice += $item["SaleItem"]["price"];
					$sumPrice_bez_popust += $item["SaleItem"]["price"] * ((100.0 / (100.0 - $item["SaleItem"]["discount_percent"])));
					//$fill = !$fill;
				}
			}
		}

		// Closing line
		$doc->Cell(array_sum($w), 0, '', 'T');
		$doc->Ln();

		// Napomena (general_note)
		if (!empty($rec["Sale"]["general_note"])) {
			$doc->Ln(3);
			$doc->SetFont('ArialCE', '', 8);
			$doc->Cell(0, 5, "Napomena: " . _convert($rec["Sale"]["general_note"]), '', 0);
			$doc->Ln();
		}

		if (isset($_GET['url']) && strstr($_GET['url'], '/vp/1')) {

			$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
			$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
			$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
			$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
			$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
			$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
			$doc->Cell(40, 5, 'Iznos ' . $g_v . ':', 0, 0, 'R', $fill);
			$doc->Cell(20, 5, number_format($sumPrice, 2, '.', ' '), 0, 0, 'R', $fill);
			$doc->Ln();
			//$doc->Cell(25,6,'',0,0,'R',$fill);
			//$doc->Cell(35,6,number_format($sumPrice,2, '.', ' '),0,0,'R',$fill);

			/*
					 $doc->Cell(10,5,'',0,0,'L',$fill);
					 $doc->Cell(10,5,'',0,0,'R',$fill);
					 $doc->Cell(35,5,'',0,0,'R',$fill);
					 $doc->Cell(25,5,'',0,0,'R',$fill);
					 $doc->Cell(25,5,'',0,0,'R',$fill);
					 $doc->Cell(25,5,'',0,0,'R',$fill);
					 $doc->Cell(40,5, 'Popust Kn:',0,0,'R',$fill);
					 $doc->Cell(20,5, number_format($sum_popust,2, '.', ' '),0,0,'R',$fill);
					 $doc->Ln();
					 
					 $doc->SetFont('ArialCE','B',9);
					 $doc->Cell(10,5,'',0,0,'L',$fill);
					 $doc->Cell(10,5,'',0,0,'R',$fill);
					 $doc->Cell(35,5,'',0,0,'R',$fill);
					 $doc->Cell(25,5,'',0,0,'R',$fill);
					 $doc->Cell(25,5,'',0,0,'R',$fill);
					 $doc->Cell(25,5,'',0,0,'R',$fill);
					 $doc->Cell(40,5, 'Ukupno Kn:',0,0,'R',$fill);
					 $doc->Cell(20,5, number_format(round($sumPrice, 2) + round($sum_popust, 2),2, '.', ' '),0,0,'R',$fill);
					 $doc->Ln();
					 */


			$doc->SetFont('ArialCE', '', 8);

		} else {
			if (isset($_GET['url']) && strstr($_GET['url'], '/o/1')) {

			} else {

				if (isset($_GET['url']) && strstr($_GET['url'], '/skraceno/1')) {
				} else {
					$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
					$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(40, 5, 'Iznos bez popusta ' . $g_v . ':', 0, 0, 'R', $fill);
					$doc->Cell(20, 5, number_format($sumPrice_bez_popust, 2, '.', ' '), 0, 0, 'R', $fill);
					//$doc->Cell(25,6,'',0,0,'R',$fill);
					//$doc->Cell(35,6,number_format($sumPrice,2, '.', ' '),0,0,'R',$fill);
					$doc->Ln();

					$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
					$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
					$doc->Cell(40, 5, 'Popust ' . $g_v . ':', 0, 0, 'R', $fill);
					$doc->Cell(20, 5, number_format($sumPrice - $sumPrice_bez_popust, 2, '.', ' '), 0, 0, 'R', $fill);
					$doc->Ln();
				}

				$doc->SetFont('ArialCE', 'B', 9);
				$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
				$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(40, 5, 'Ukupno ' . $g_v . ':', 0, 0, 'R', $fill);
				$doc->Cell(20, 5, number_format($sumPrice, 2, '.', ' '), 0, 0, 'R', $fill);
				$doc->Ln();

				if (isset($_GET['url']) && strstr($_GET['url'], '/skraceno/1')) {
					if ($l_euro_info) {
						$doc->SetFont('ArialCE', 'B', 9);
						$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
						$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						//$doc->Cell(40,5, 'TOTAL EUR: ',0,0,'R',$fill);
						//$doc->Cell(20,5, number_format($sumPrice / $l_euro_exchange_rate,2, '.', ' '),0,0,'R',$fill);
						$doc->Ln();
					}
				} else {
					if ($l_euro_info) {
						$doc->SetFont('ArialCE', 'B', 9);
						$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
						$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						//$doc->Cell(40,5, 'TOTAL EUR: ',0,0,'R',$fill);
						//$doc->Cell(20,5, number_format($sumPrice / $l_euro_exchange_rate,2, '.', ' '),0,0,'R',$fill);
						$doc->Ln();
					}
				}

				$doc->SetFont('ArialCE', '', 8);
			}
		}


		if ($rec["Sale"]["note"] != null || $rec["Customer"]["note"] != null) {
			$doc->SetFont('ArialCE', '', 8);
			//$doc->Cell(1);
			if ($rec["Sale"]["note"] != null) {
				$doc->Cell(100, 5, "Napomena: " . _convert($rec["Sale"]["note"]), '', 0);
			} else {
				if ($rec["Customer"]["note"] != null) {
					$doc->Cell(100, 5, "Napomena: " . _convert($rec["Customer"]["note"]), '', 0);
				}
			}
			$doc->Ln(10);
		} else {
			$doc->Ln(7);
		}




		if ($l_euro_info) {
			if (isset($_GET['url']) && !(strstr($_GET['url'], '/vp/1'))) {
				/*
							if($l_old_year == 'yes'){
								$doc->Cell(0,5,_convert('1 EUR = '.$l_euro_exchange_rate.' Kn (Ukupno EUR: '.number_format($sumPrice / $l_euro_exchange_rate,2, '.', ' ').')'),0,0);
							}else{
								$doc->Cell(0,5,_convert('1 EUR = '.$l_euro_exchange_rate.' Kn (Ukupno Kn: '.number_format($sumPrice * $l_euro_exchange_rate,2, '.', ' ').')'),0,0);
							}
							*/
				$doc->Ln();
				$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8] + $w[9], 1, '', 0, 0, 'L', $fill);
				$doc->Ln();
			}
		}



		if (isset($_GET['url']) && strstr($_GET['url'], '/vp/1')) {

			if ($r) {


				if ($restPDV["Setting"]["value"] == 'yes') { // AKO JESTE U PDV


					$doc->SetFillColor(255, 255, 255);

					$doc->Ln();
					$doc->Ln();
					$doc->SetX(148);
					$header = array('TBR', 'Stopa', 'Osnovica', 'Iznos PDV-a');
					$w = array(10, 10, 15, 15);
					for ($i = 0; $i < count($header); $i++)
						$doc->Cell($w[$i], 5, _convert($header[$i]), 0, 0, 'C', true);
					$doc->Ln();

					$doc->SetFont('ArialCE', '', 7);
					$rb = 1;
					$sumPDV = 0;
					$povn = 0;

					$porezi = $this->RetailItem->query(
						"SELECT (tax_1+tax_2) as stopa ,100*(sum(price)-sum(feedback_compensation))/(100+tax_1+tax_2) as osnovica,
							(tax_1+tax_2)*(sum(price)-sum(feedback_compensation))/(100+tax_1+tax_2) as porez,sum(feedback_compensation) as povrat 
			
							FROM `retail_items`   WHERE sale_id=" . $id . "   
							group by (tax_1+tax_2)"
					);

					foreach ($porezi as $porez) {
						//print_r($porez);
						//die();
						$doc->SetX(150);
						$doc->Cell($w[0], 6, $rb, 0, 0, 'C', $fill);
						$doc->Cell($w[1], 6, number_format($porez[0]["stopa"], 2) . "%", 0, 0, 'R', $fill);
						$doc->Cell($w[2], 6, number_format($porez[0]["osnovica"], 2), 0, 0, 'R', $fill);
						$doc->Cell($w[3], 6, number_format($porez[0]["porez"], 2), 0, 0, 'R', $fill);
						$doc->Ln();
						$rb = $rb + 1;
						$sumPDV += $porez[0]["porez"];
						$povn += $porez[0]["povrat"];

					}


					$doc->SetX(150);
					// Closing line
					$doc->Cell(array_sum($w), 0, '', 'T');
					$doc->Ln();
					$doc->SetX(150);
					$doc->Cell(10, 6, 'UKUPNO PDV', 0, 0, 'L', $fill);
					$doc->Cell(10, 6, '', 0, 0, 'R', $fill);
					$doc->Cell(15, 6, '', 0, 0, 'R', $fill);
					$doc->Cell(15, 6, number_format($sumPDV, 2), 0, 0, 'R', $fill);

					$doc->Ln();

					$doc->SetX(150);
					$doc->Cell(array_sum($w), 0, '', 'T');

					$l_povn_xpos = 165;

				} else {


					$porezi = $this->RetailItem->query(
						"SELECT sum(feedback_compensation) as povrat 
			
							FROM `retail_items`   WHERE sale_id=" . $id . "   
							"
					);

					foreach ($porezi as $porez) {
						$povn += $porez[0]["povrat"];

					}

					$l_povn_xpos = 161;
				}



				$doc->Ln();

				if ($povn != null) {
					$doc->SetX($l_povn_xpos);
					$doc->Cell(10, 6, 'POVRATNA NAKNADA: ' . number_format($povn, 2), 0, 0);
					$doc->Ln();
				}



				$doc->SetFont('ArialCE', 'B', 9);
				$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
				$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
				$doc->Cell(40, 5, 'Ukupno ' . $g_v . ':', 0, 0, 'R', $fill);
				$doc->Cell(20, 5, number_format($sumPrice + $sumPDV + $povn, 2, '.', ' '), 0, 0, 'R', $fill);
				$doc->Ln();


				if ($l_euro_info) {
					if (isset($_GET['url']) && strstr($_GET['url'], '/vp/1')) {


						$doc->SetFont('ArialCE', 'B', 9);
						$doc->Cell(10, 5, '', 0, 0, 'L', $fill);
						$doc->Cell(10, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(35, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						$doc->Cell(25, 5, '', 0, 0, 'R', $fill);
						//$doc->Cell(40,5, 'TOTAL EUR: ',0,0,'R',$fill);
						//$doc->Cell(20,5, number_format(($sumPrice + $sumPDV + $povn) / $l_euro_exchange_rate,2, '.', ' '),0,0,'R',$fill);
						$doc->Ln();


						$doc->SetFont('ArialCE', '', 8);
						/*
												if($l_old_year == 'yes'){
													$doc->Cell(0,5,_convert('1 EUR = '.$l_euro_exchange_rate.' Kn (Ukupno EUR: '.number_format(($sumPrice + $sumPDV + $povn) / $l_euro_exchange_rate,2, '.', ' ').')'),0,0);
												}else{
													$doc->Cell(0,5,_convert('1 EUR = '.$l_euro_exchange_rate.' Kn (Ukupno Kn: '.number_format(($sumPrice + $sumPDV + $povn) * $l_euro_exchange_rate,2, '.', ' ').')'),0,0);
												}
												*/

						$doc->Ln();
						$doc->Cell($w[0] + $w[1] + $w[2] + $w[3] + $w[4] + $w[5] + $w[6] + $w[7] + $w[8] + $w[9], 1, '', 0, 0, 'L', $fill);
						$doc->Ln();

					}
				}



				$doc->Ln();
				$doc->SetFont('ArialCE', '', 8);
				$doc->SetFillColor(255, 255, 255);
				$doc->Cell(50, 5, _convert("Način plaćanja: " . $rec["PaymentType"]["full_name"]), 0, 0, 'L');
				$doc->Ln();
				$doc->Ln();


				if ($restPDV["Setting"]["value"] != 'yes') {

					$dutyComment = $this->Setting->find('first', array(
						'conditions' => array('Setting.name' => 'duty.comment')
					));

					$doc->Ln();
					$doc->SetFont('ArialCE', '', 8);
					$doc->Cell(0, 5, _convert($dutyComment["Setting"]["value"]), 0, 0);
					$doc->Ln();

				}



			}




		} else {

			if (isset($_GET['url']) && strstr($_GET['url'], '/o/1')) {


			} else {

				$doc->SetFillColor(255, 255, 255);

				//QR Code
				//$qrCodeURL = "https://porezna.gov.hr/rn?zki=12345678123412341234123456789012&datv=20210205_0801&izn=510";
				if ($rec["Sale"]["kod"] != null) {
					$yyy = $doc->getY();
					$datv = date('Ymd_Hm', strtotime($rec['Sale']['date']));
					$izn = round($rec['Sale']['price'] * 100);
					$qrCodeURL = 'https://porezna.gov.hr/rn?zki=' . $rec["Sale"]["kod"] . '&datv=' . $datv . '&izn=' . $izn;
					$barcodeobj = new TCPDF2DBarcode($qrCodeURL, 'QRCODE,L');
					file_put_contents('tmpqrcode.png', $barcodeobj->getBarcodePngData());
					$doc->Image('tmpqrcode.png', 175, $yyy + 5, 25, 0, 'PNG');
					unlink('tmpqrcode.png');
				}

				$doc->Cell(50, 5, _convert("Način plaćanja: " . $rec["PaymentType"]["full_name"]), 0, 0, 'L');
				if ($rec["User"]["full_name"] != null) {
					$doc->Ln();
					$doc->SetFont('ArialCE', '', 8);
					$doc->Cell(50, 5, "Operater         : " . _convert($rec["User"]["full_name"]), 0, 0, 'L');

				}
				$doc->Ln(10);

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

				if ($restPDV["Setting"]["value"] == 'yes') // AKO JESTE U PDV
				{

					//print_r($porez);
					//die();

					$l_duty_remark = $this->get_item('select value from settings where name = "duty.remark" limit 1 ');

					$doc->Cell(50, 5, "Rekapitulacija obracunatog poreza", 0, 0, 'L');
					$doc->Cell(150, 5, _convert($l_duty_remark), 0, 0, 'C');
					$doc->Ln();


					if ($r) {

						$header = array('TBR', 'Stopa', 'Osnovica', 'Iznos PDV-a');
						$w = array(10, 10, 15, 15);
						for ($i = 0; $i < count($header); $i++)
							$doc->Cell($w[$i], 8, _convert($header[$i]), 0, 0, 'C', true);
						$doc->Ln();

						$doc->SetFont('ArialCE', '', 7);
						$rb = 1;
						$sumPDV = 0;
						$povn = 0;

						$porezi = $this->RetailItem->query(
							"SELECT (tax_1+tax_2) as stopa ,100*(sum(price)-sum(feedback_compensation))/(100+tax_1+tax_2) as osnovica,
						(tax_1+tax_2)*(sum(price)-sum(feedback_compensation))/(100+tax_1+tax_2) as porez,sum(feedback_compensation) as povrat 
		
						FROM `retail_items`   WHERE sale_id=" . $id . "   
						group by (tax_1+tax_2)"
						);

						foreach ($porezi as $porez) {
							//print_r($porez);
							//die();
							$doc->Cell($w[0], 6, $rb, 0, 0, 'C', $fill);
							$doc->Cell($w[1], 6, number_format($porez[0]["stopa"], 2) . "%", 0, 0, 'R', $fill);
							$doc->Cell($w[2], 6, number_format($porez[0]["osnovica"], 2), 0, 0, 'R', $fill);
							$doc->Cell($w[3], 6, number_format($porez[0]["porez"], 2), 0, 0, 'R', $fill);
							$doc->Ln();
							$rb = $rb + 1;
							$sumPDV += $porez[0]["porez"];
							$povn += $porez[0]["povrat"];

						}

					} else {
						$doc->SetFont('ArialCE', '', 5);
						$rb = 1;
						$sumPDV = 0;
						$povn = 0;

						$la_ukupno = array();

						foreach ($items as $item) {
							if (empty($la_ukupno[$item['SaleItem']['tax_1']][$item['SaleItem']['tax_1']])) {
								$la_ukupno[$item['SaleItem']['tax_1']][$item['SaleItem']['tax_1']] = 0;
							}
							$la_ukupno[$item['SaleItem']['tax_1']][$item['SaleItem']['tax_1']] += $item['SaleItem']['price'];

							if (empty($la_ukupno[$item['SaleItem']['tax_1']][$item['SaleItem']['tax_2']])) {
								$la_ukupno[$item['SaleItem']['tax_1']][$item['SaleItem']['tax_2']] = 0;
							}
							$la_ukupno[$item['SaleItem']['tax_1']][$item['SaleItem']['tax_2']] += $item['SaleItem']['price'];
						}

						foreach ($la_ukupno as $key => $value) {
							foreach ($value as $key2 => $value2) {
								if ($key2 == $key) {
									continue;
								}
								if (empty($la_ukupno[$key]['pdv']['ukup'])) {
									$la_ukupno[$key]['pdv']['ukup'] = 0;
								}
								if (empty($la_ukupno[$key]['pnp']['ukup'])) {
									$la_ukupno[$key]['pnp']['ukup'] = 0;
								}
								$la_ukupno[$key]['osnovica'][$key2] = $value2 / (1 + ($key + $key2) / 100);
								$la_ukupno[$key]['pdv'][$key2] = $la_ukupno[$key]['osnovica'][$key2] * $key / 100;
								$la_ukupno[$key]['pdv']['ukup'] += $la_ukupno[$key]['osnovica'][$key2] * $key / 100;
								$la_ukupno[$key]['pnp'][$key2] = $la_ukupno[$key]['osnovica'][$key2] * $key2 / 100;
								$la_ukupno[$key]['pnp']['ukup'] += $la_ukupno[$key]['osnovica'][$key2] * $key2 / 100;
							}
						}

						$la_w = array(25, 15, 15);

						$doc->SetFont("ArialCE", "", 8);
						foreach ($la_ukupno as $key => $value) {

							$doc->Cell(18, 4, $this->_convert('PDV ' . $key . '%:'), 0, 0);
							$doc->Cell(30, 4, $this->_convert(sprintf('%01.2f', $value['pdv']['ukup']) . ' ' . $g_v), 0, 0);

							$doc->Ln();

							$l_cnt_w = 0;
							$doc->Cell($la_w[$l_cnt_w++], 4, $this->_convert('Osnovica'), 0, 0);
							$doc->Cell($la_w[$l_cnt_w++], 4, $this->_convert('PDV'), 0, 0);
							$doc->Cell($la_w[$l_cnt_w++], 4, $this->_convert('PNP'), 0, 0);
							$doc->Ln();

							foreach ($value['osnovica'] as $key2 => $value2) {
								$l_cnt_w = 0;
								$doc->Cell($la_w[$l_cnt_w++], 4, $this->_convert(sprintf('%01.2f', $value2)), 0, 0);
								$doc->Cell($la_w[$l_cnt_w++], 4, $this->_convert(sprintf('%01.2f', $value['pdv'][$key2])), 0, 0);
								$doc->Cell($la_w[$l_cnt_w++], 4, $this->_convert(sprintf('%01.2f', $value['pnp'][$key2])), 0, 0);
								$doc->Ln();
							}

							//$l_cnt++;
							$doc->Ln();
						}
						$doc->Ln();
						$doc->Ln();


						/*
										  foreach($items as $item){		
											  //print_r($item);
											  //die();
											  $doc->Cell($w[0],6,$rb,0,0,'C',$fill);
											  $doc->Cell($w[1],6,number_format(100.0*($item["SaleItem"]["price"]-($item["SaleItem"]["base_price"])*$item["SaleItem"]["amount"]*(1-$item["SaleItem"]["discount_percent"]/100))/($item["SaleItem"]["price"]),2)."%",0,0,'R',$fill);	
											  $doc->Cell($w[2],6,number_format($item["SaleItem"]["base_price"]*$item["SaleItem"]["amount"]*(1-$item["SaleItem"]["discount_percent"]/100),2),0,0,'R',$fill);	
											  $doc->Cell($w[3],6,number_format($item["SaleItem"]["price"]-$item["SaleItem"]["base_price"]*$item["SaleItem"]["amount"]*(1-$item["SaleItem"]["discount_percent"]/100),2),0,0,'R',$fill);
											  $doc->Ln();
											  $rb = $rb+1;
											  $sumPDV+=($item["SaleItem"]["price"]-$item["SaleItem"]["base_price"]*$item["SaleItem"]["amount"]*(1-$item["SaleItem"]["discount_percent"]/100));
											  
											  //print ($item["SaleItem"]["price"]-$item["SaleItem"]["base_price"]*$item["SaleItem"]["amount"]*(1-$item["SaleItem"]["discount_percent"]/100))."\n";
											  
										  }
										  */
					}



					if ($r) {
						// Closing line
						$doc->Cell(array_sum($w), 0, '', 'T');
						$doc->Ln();
						$doc->Cell(10, 6, 'UKUPNO', 0, 0, 'L', $fill);
						$doc->Cell(10, 6, '', 0, 0, 'R', $fill);
						$doc->Cell(15, 6, '', 0, 0, 'R', $fill);
						$doc->Cell(15, 6, number_format($sumPDV, 2), 0, 0, 'R', $fill);

						$doc->Ln();

						$doc->Cell(array_sum($w), 0, '', 'T');

						$doc->Ln();
					}

					/*
					 */

					if ($povn != null) {
						$doc->Cell(10, 6, 'POVRATNA NAKNADA: ' . number_format($povn, 2), 0, 0);
						$doc->Ln();
					}

				} else {

					$povn = 0;
					$porezi = $this->RetailItem->query(
						"SELECT sum(feedback_compensation) as povrat 
	
					FROM `retail_items`   WHERE sale_id=" . $id . "   
					"
					);

					foreach ($porezi as $porez) {
						$povn += $porez[0]["povrat"];
					}

					if ($povn != null) {
						$doc->Cell(10, 6, 'POVRATNA NAKNADA: ' . number_format($povn, 2), 0, 0);
						$doc->Ln();
					}

					$dutyComment = $this->Setting->find('first', array(
						'conditions' => array('Setting.name' => 'duty.comment')
					));

					$doc->Cell(0, 5, _convert($dutyComment["Setting"]["value"]), 0, 0);
					$doc->Ln();

				}
				//---------------------------------------------------------------------


			}
		}





		//$doc->Cell(10);
		//$doc->Cell(30,20,"Robu Predao",'B',0,'C');
		//$doc->Cell(30,20,"",'',0,'C');

		//		$doc->Ln();
//		$doc->Ln();
//		file_put_contents('tmppdfcode.png', $this->getBarcodeForDocument($rec, 'racuni'));
//		$doc->Image('tmppdfcode.png', null, $doc->getY()-10, 50, 0, 'PNG');
//		unlink('tmppdfcode.png');
//		$doc->Ln();
//		$doc->Write(12, '2D Kod za placanje');
//		$doc->Ln();

		$doc->Cell(10);
		//$doc->Cell(30,20,"Robu Primio",'B',0,'C');
		$doc->Cell(30, 20, "Kupac", 'B', 0, 'C');

		$doc->Cell(80);
		$doc->Cell(30, 20, "Obradio", 'B', 0, 'C');
		$doc->Ln();

		$doc->Cell(10);
		$doc->Cell(30, 4, "", 0, 0, 'C');

		$doc->Cell(10);
		$doc->Cell(30, 4, "", 0, 0, 'C');

		$doc->Cell(40);
		$doc->Cell(30, 4, "(" . _convert($rec["User"]["full_name"]) . ")", 0, 0, 'C');
		$doc->Ln();

		$doc->output();
		die();

	}

	function print_offer($id = null, $with_notes = 0, $save_to_file = false)
	{
		$with_notes = (int)$with_notes;
		$g_v = get_valuta();

		$restFooter = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'invoice.footer')));

		$doc = new Document("", $restFooter["Setting"]["value"], "");
		$doc->AddPage();
		$restName = $this->Setting->find('first', array(
			'conditions' => array('Setting.name' => 'general.name')
		));

		$rec = $this->Offer->find('first', array(
			'conditions' => array('Offer.id' => $id)
		));

		// Učitaj stavke s relacijama za Automobil i Uredjaj
		$this->Offer->OfferItem->bindModel(array(
			'belongsTo' => array(
				'Automobil' => array('className' => 'Automobil', 'foreignKey' => 'automobil_id'),
				'Uredjaj' => array('className' => 'Uredjaj', 'foreignKey' => 'uredjaj_id')
			)
		));
		$items = $this->Offer->OfferItem->find('all', array(
			'conditions' => array('OfferItem.offer_id' => $id),
			'contain' => array('Article.TaxGroup', 'Automobil', 'Uredjaj')
		));

		// Dohvati sve postavke
		$restpost = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.post')));
		$restComm = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.resort')));
		$restStreet = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.street')));
		$restStrNum = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num')));
		$restStrNumMark = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num_mark')));
		$restPlaceid = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.placeid')));
		
		$adresa = $restpost["Setting"]["value"] . ' ' . $restComm["Setting"]["value"] . ', ' . 
			$restStreet["Setting"]["value"] . ' ' . $restStrNum["Setting"]["value"] . $restStrNumMark["Setting"]["value"];

		// ===== HEADER - Naziv firme (desno) =====
		$doc->SetFont('ArialCE', 'B', 14);
		$doc->Cell(100);
		$doc->Cell(90, 6, $this->_utf8ToIso($restName["Setting"]["value"]), 0, 1, 'R');
		$doc->SetFont('ArialCE', '', 9);
		$doc->Cell(100);
		$doc->Cell(90, 5, $this->_utf8ToIso($adresa), 0, 1, 'R');
		$doc->Cell(100);
		$doc->Cell(90, 5, $this->_utf8ToIso($restPlaceid["Setting"]["value"]), 0, 1, 'R');

		$doc->Ln(10);

		// ===== KUPAC I DOKUMENT =====
		$doc->SetFillColor(41, 128, 185); // Plava boja
		$doc->SetTextColor(255, 255, 255);
		$doc->SetFont('ArialCE', 'B', 11);
		$doc->Cell(95, 8, ' KUPAC', 1, 0, 'L', true);
		$doc->Cell(95, 8, ' PONUDA #' . $rec["Offer"]["number"], 1, 1, 'L', true);
		$doc->SetTextColor(0, 0, 0);
		
		$doc->SetFont('ArialCE', 'B', 10);
		$doc->Cell(95, 6, ' ' . $this->_utf8ToIso($rec["Customer"]["name"]), 'LR', 0, 'L');
		$doc->SetFont('ArialCE', '', 9);
		$doc->Cell(95, 6, ' Broj dokumenta: ' . $rec["Offer"]["number"], 'LR', 1, 'L');
		
		$doc->SetFont('ArialCE', '', 9);
		$doc->Cell(95, 5, ' ' . $this->_utf8ToIso($rec["Customer"]["address"]), 'LR', 0, 'L');
		$dt = date('d.m.Y', strtotime($rec["Offer"]["created"]));
		$vrijediDo = !empty($rec["Offer"]["vrijedi_do"]) && $rec["Offer"]["vrijedi_do"] != '0000-00-00' ? date('d.m.Y', strtotime($rec["Offer"]["vrijedi_do"])) : '-';
		$doc->Cell(95, 5, ' Datum: ' . $dt . '   Vrijedi do: ' . $vrijediDo, 'LR', 1, 'L');
		
		$doc->Cell(95, 5, ' ' . $this->_utf8ToIso($rec["Customer"]["city"]), 'LR', 0, 'L');
		$doc->Cell(95, 5, ' Valuta: EUR', 'LR', 1, 'L');
		
		$doc->Cell(95, 5, ' OIB: ' . $rec["Customer"]["oib"], 'LRB', 0, 'L');
		$statusPonude = !empty($rec["Offer"]["status"]) ? $this->_utf8ToIso($rec["Offer"]["status"]) : '-';
		$doc->Cell(95, 5, ' Status: ' . $statusPonude, 'LRB', 1, 'L');
		$doc->Ln(5);

		// ===== NAPOMENA PONUDE =====
		if (!empty($rec['Offer']['note'])) {
			$doc->SetFillColor(240, 240, 240);
			$doc->SetFont('ArialCE', 'B', 9);
			$doc->Cell(190, 6, ' NAPOMENA', 1, 1, 'L', true);
			$doc->SetFont('ArialCE', '', 8);
			$doc->MultiCell(190, 5, $this->_utf8ToIso($rec['Offer']['note']), 'LRB', 'L');
			$doc->Ln(3);
		}

		// ===== TABLICA STAVKI =====
		$doc->SetFillColor(52, 73, 94); // Tamno siva
		$doc->SetTextColor(255, 255, 255);
		$doc->SetFont('ArialCE', 'B', 8);
		
		$header = array('RB', 'Naziv artikla/usluge', 'Kol.', 'Cijena', 'Rabat', 'Neto', 'Ukupno ' . $g_v);
		$w = array(10, 72, 18, 22, 16, 22, 30);
		
		for ($i = 0; $i < count($header); $i++) {
			$doc->Cell($w[$i], 7, $header[$i], 1, 0, 'C', true);
		}
		$doc->Ln();
		$doc->SetTextColor(0, 0, 0);

		// Data
		$fill = false;
		$doc->SetFont('ArialCE', '', 8);
		$rb = 1;
		$uk = 0;
		$uk_osnovica = 0;
		$uk_pdv = 0;
		foreach ($items as $item) {
			// Odredi tip stavke i naziv
			$tipStavke = isset($item["OfferItem"]["tip_stavke"]) ? $item["OfferItem"]["tip_stavke"] : 'artikl';
			$naziv = '';
			$sifra = '';
			
			if ($tipStavke == 'automobil' && !empty($item["Automobil"]["id"])) {
				$tipLabel = 'Auto';
				$naziv = $item["Automobil"]["marka"] . ' ' . $item["Automobil"]["model"];
				$sifra = isset($item["Automobil"]["registracija"]) ? $item["Automobil"]["registracija"] : '';
			} elseif ($tipStavke == 'uredjaj' && !empty($item["Uredjaj"]["id"])) {
				$tipLabel = 'Uredjaj';
				$naziv = isset($item["Uredjaj"]["naziv"]) ? $item["Uredjaj"]["naziv"] : '';
				$sifra = isset($item["Uredjaj"]["serijski_broj"]) ? $item["Uredjaj"]["serijski_broj"] : '';
			} else {
				$tipLabel = 'Artikl';
				$naziv = isset($item["Article"]["name"]) ? $item["Article"]["name"] : '';
				$sifra = isset($item["Article"]["barcode"]) ? $item["Article"]["barcode"] : '';
			}
			
			// Konvertiraj UTF-8 za FPDF
			$naziv = $this->_utf8ToIso($naziv);
			
			// Dodaj napomenu ako treba
			if ($with_notes && !empty($item["OfferItem"]["napomena"])) {
				$naziv .= "\n" . $this->_utf8ToIso($item["OfferItem"]["napomena"]);
			}
			
			$doc->Cell($w[0], 6, $rb, 0, 0, 'C', $fill);

			$posY = $doc->GetY();
			$posX = $doc->GetX();
			$nl = 0;
			
			// Provjeri ima li napomenu (višeredni tekst)
			if (strpos($naziv, "\n") !== false) {
				$lines = explode("\n", $naziv);
				foreach ($lines as $lineIdx => $line) {
					if ($lineIdx == 0) {
						$doc->Cell($w[1], 4, $line, 0, 2, 'L');
					} else {
						$doc->SetFont('ArialCE', 'I', 7);
						$doc->Cell($w[1], 3, $line, 0, 2, 'L');
						$doc->SetFont('ArialCE', '', 8);
					}
					$nl += 1;
				}
				$posX += $w[1];
				$doc->SetY($posY);
				$posY += $nl * 3 + 3;
			} elseif (strlen($naziv) > 50) {
				$temptext = str_split($naziv, 50);
				foreach ($temptext as $newline) {
					$doc->Cell($w[1], 3, $newline, 0, 2, 'L');
					$nl += 1;
				}
				$posX += $w[1];
				$doc->SetY($posY);
				$posY += $nl * 3;
			} else {
				$doc->Cell($w[1], 6, $naziv, 0, 0, 'L', $fill);
				$posX = $doc->GetX();
				$posY += 6;
			}

			$doc->SetX($posX);


			$doc->Cell($w[2], 6, number_format($item["OfferItem"]["amount"], 2, '.', ' '), 0, 0, 'R', $fill);
			$doc->Cell($w[3], 6, number_format($item["OfferItem"]["price_sell"], 2, '.', ' '), 0, 0, 'R', $fill);
			$doc->Cell($w[4], 6, number_format($item["OfferItem"]["discount"], 2, '.', ' '), 0, 0, 'R', $fill);
			$doc->Cell($w[5], 6, number_format($item["OfferItem"]["price_sell"] * (1 - $item["OfferItem"]["discount"] / 100), 2), 0, 0, 'R', $fill);
			$doc->Cell($w[6], 6, number_format($item["OfferItem"]["price_sell"] * $item["OfferItem"]["amount"] * (1 - $item["OfferItem"]["discount"] / 100), 2, '.', ' '), 0, 0, 'R', $fill);
			$doc->Ln();
			$rb = $rb + 1;
			
			// Izračunaj ukupno, osnovicu i PDV za stavku
			$ukupno_stavka = $item["OfferItem"]["price_sell"] * $item["OfferItem"]["amount"] * (1 - $item["OfferItem"]["discount"] / 100);
			$pdv_stopa = isset($item["Article"]["TaxGroup"]["tax_1"]) ? floatval($item["Article"]["TaxGroup"]["tax_1"]) : 25;
			$osnovica_stavka = $ukupno_stavka / (1 + $pdv_stopa / 100);
			$pdv_stavka = $ukupno_stavka - $osnovica_stavka;
			
			$uk += $ukupno_stavka;
			$uk_osnovica += $osnovica_stavka;
			$uk_pdv += $pdv_stavka;
			
			$doc->SetY($posY);
		}
		// Closing line

		$doc->Cell(190, 0, '', 'T');
		$doc->Ln();
		
		// Prikaz osnovice, PDV-a i ukupnog iznosa
		$doc->SetFont('ArialCE', '', 9);
		$doc->Cell(160, 6, 'Osnovica:', 0, 0, 'R');
		$doc->Cell(30, 6, number_format($uk_osnovica, 2, '.', ' ') . ' ' . $g_v, 0, 1, 'R');
		
		$doc->Cell(160, 6, 'PDV (25%):', 0, 0, 'R');
		$doc->Cell(30, 6, number_format($uk_pdv, 2, '.', ' ') . ' ' . $g_v, 0, 1, 'R');
		
		$doc->SetFont('ArialCE', 'B', 10);
		$doc->Cell(160, 7, 'UKUPNO:', 0, 0, 'R');
		$doc->Cell(30, 7, number_format($uk, 2, '.', ' ') . ' ' . $g_v, 0, 1, 'R');

		$doc->Ln(5);

		// ===== POTPIS =====
		$doc->Ln(10);
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(95, 5, '________________________________', 0, 0, 'C');
		$doc->Cell(95, 5, '________________________________', 0, 1, 'C');
		$doc->Cell(95, 5, 'Izradio', 0, 0, 'C');
		$doc->Cell(95, 5, 'Odobrio', 0, 1, 'C');
		
		// ===== FOOTER: BARCODE (lijevo) + QR KOD (desno) =====
		$doc->Ln(10);
		$footerStartY = $doc->GetY();
		
		// Barcode (lijevo)
		file_put_contents('tmppdfcode.png', $this->getBarcodeForDocument($rec, 'ponude'));
		$doc->Image('tmppdfcode.png', 10, $footerStartY, 50, 15, 'PNG');
		unlink('tmppdfcode.png');
		
		// QR kod za plaćanje (desno)
		$qrContent = $this->getQRCodeContent($rec, 'ponude');
		if (!empty($qrContent)) {
			$qrFile = 'tmpqrcode_' . uniqid() . '.png';
			file_put_contents($qrFile, $this->getQRCodeImage($qrContent));
			
			// Okvir za QR kod (desno)
			$doc->SetFillColor(248, 249, 250);
			$doc->SetDrawColor(200, 200, 200);
			$doc->Rect(110, $footerStartY - 2, 90, 38, 'DF');
			
			$doc->SetFont('ArialCE', 'B', 8);
			$doc->SetXY(112, $footerStartY);
			$doc->Cell(85, 4, 'QR kod za placanje', 0, 1);
			
			$doc->Image($qrFile, 115, $footerStartY + 5, 28, 28, 'PNG');
			
			$doc->SetXY(145, $footerStartY + 7);
			$doc->SetFont('ArialCE', '', 7);
			$doc->MultiCell(50, 4, "Skenirajte QR kod\nmobilnom aplikacijom\nVase banke za\nbrzo placanje.", 0, 'L');
			
			unlink($qrFile);
		}
		
		$doc->SetY($footerStartY + 40);
		
		if ($save_to_file) {
			// Spremi PDF u fajl
			$pdfPath = WWW_ROOT . 'res' . DS . 'files' . DS;
			$pdfFile = 'ponuda.pdf';
			$doc->Output($pdfPath . $pdfFile, 'F');
			// NE pozivaj die() - vrati se u kontroler
			return;
		} else {
			$doc->output();
			die();
		}
	}
	
	// Spremi PDF ponude u fajl
	function save_offer_pdf($id = null) {
		$this->autoRender = false;
		$this->layout = false;
		
		if (!$id) {
			echo "Nema ID";
			return;
		}
		
		$g_v = get_valuta();
		$restFooter = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'invoice.footer')));
		
		$doc = new Document("", $restFooter["Setting"]["value"], "");
		$doc->AddPage();
		
		$restName = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.name')));
		$rec = $this->Offer->find('first', array('conditions' => array('Offer.id' => $id)));
		
		if (!$rec) {
			echo "Ponuda nije pronađena";
			return;
		}
		
		// Učitaj stavke
		$this->Offer->OfferItem->bindModel(array(
			'belongsTo' => array(
				'Automobil' => array('className' => 'Automobil', 'foreignKey' => 'automobil_id'),
				'Uredjaj' => array('className' => 'Uredjaj', 'foreignKey' => 'uredjaj_id')
			)
		));
		$items = $this->Offer->OfferItem->find('all', array(
			'conditions' => array('OfferItem.offer_id' => $id),
			'contain' => array('Article', 'Automobil', 'Uredjaj')
		));
		
		// Header
		$doc->Cell(100);
		$doc->Cell(0, 5, $this->_utf8ToIso($restName["Setting"]["value"]), 0, 2);
		$doc->SetFont('ArialCE', '', 8);
		
		$restpost = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.post')));
		$restComm = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.resort')));
		$restStreet = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.street')));
		$restStrNum = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num')));
		$restStrNumMark = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num_mark')));
		$adresa = $restpost["Setting"]["value"] . ' ' . $restComm["Setting"]["value"] . ',' . $restStreet["Setting"]["value"] . ' ' . $restStrNum["Setting"]["value"] . $restStrNumMark["Setting"]["value"];
		$doc->Cell(0, 5, $this->_utf8ToIso($adresa), 0, 2);
		
		$restPlaceid = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.placeid')));
		$doc->Cell(0, 5, $this->_utf8ToIso($restPlaceid["Setting"]["value"]), 0, 0);
		$doc->Ln(6);
		
		// Kupac i ponuda
		$doc->Ln();
		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(80, 8, $this->_utf8ToIso($rec["Customer"]["name"]), 'LTR', 0);
		$doc->Cell(20);
		$doc->SetFont('ArialCE', 'B', 10);
		$doc->Cell(80, 8, 'Ponuda *' . $rec["Offer"]["number"], 'LTRB', 0, 'C');
		
		$dt = date('d.m.Y', strtotime($rec["Offer"]["created"]));
		
		$doc->Ln();
		$doc->SetFont('ArialCE', 'B', 8);
		$doc->Cell(80, 5, '  ', 'LR', 0);
		$doc->Cell(20);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(80, 5, "Broj dokumenta:    " . $rec["Offer"]["number"], 'LR', 0);
		
		$doc->Ln();
		$doc->SetFont('ArialCE', 'B', 8);
		$doc->Cell(80, 5, $this->_utf8ToIso($rec["Customer"]["address"] . ' ' . $rec["Customer"]["city"]), 'LR', 0);
		$doc->Cell(20);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(80, 5, "Datum dokumenta:   " . $dt, 'LBR', 0);
		$doc->Ln();
		
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(80, 5, "OIB: " . $rec["Customer"]["oib"], 'LRB', 0, 'R');
		$doc->Ln(10);
		
		// Tablica
		$doc->SetFont('ArialCE', 'B', 8);
		$doc->SetFillColor(255, 255, 255);
		$header = array('RB', 'Naziv artikla/usluge', 'Kolicina', 'PC', 'Rabat %', 'Cijena', 'Vrijednost ' . $g_v);
		$w = array(10, 70, 22, 22, 18, 22, 26);
		for ($i = 0; $i < count($header); $i++)
			$doc->Cell($w[$i], 7, $header[$i], 0, 0, 'C', true);
		$doc->Ln();
		
		// Stavke
		$doc->SetFont('ArialCE', '', 8);
		$rb = 1;
		$uk = 0;
		foreach ($items as $item) {
			$tipStavke = isset($item["OfferItem"]["tip_stavke"]) ? $item["OfferItem"]["tip_stavke"] : 'artikl';
			$naziv = '';
			if ($tipStavke == 'automobil' && !empty($item["Automobil"]["id"])) {
				$naziv = $item["Automobil"]["marka"] . ' ' . $item["Automobil"]["model"];
			} elseif ($tipStavke == 'uredjaj' && !empty($item["Uredjaj"]["id"])) {
				$naziv = isset($item["Uredjaj"]["naziv"]) ? $item["Uredjaj"]["naziv"] : '';
			} else {
				$naziv = isset($item["Article"]["name"]) ? $item["Article"]["name"] : '';
			}
			$naziv = $this->_utf8ToIso($naziv);
			
			$doc->Cell($w[0], 6, $rb, 0, 0, 'C');
			$doc->Cell($w[1], 6, $naziv, 0, 0, 'L');
			$doc->Cell($w[2], 6, number_format($item["OfferItem"]["amount"], 2, '.', ' '), 0, 0, 'R');
			$doc->Cell($w[3], 6, number_format($item["OfferItem"]["price_sell"], 2, '.', ' '), 0, 0, 'R');
			$doc->Cell($w[4], 6, number_format($item["OfferItem"]["discount"], 2, '.', ' '), 0, 0, 'R');
			$doc->Cell($w[5], 6, number_format($item["OfferItem"]["price_sell"] * (1 - $item["OfferItem"]["discount"] / 100), 2), 0, 0, 'R');
			$doc->Cell($w[6], 6, number_format($item["OfferItem"]["price_sell"] * $item["OfferItem"]["amount"] * (1 - $item["OfferItem"]["discount"] / 100), 2, '.', ' '), 0, 0, 'R');
			$doc->Ln();
			$rb++;
			$uk += $item["OfferItem"]["price_sell"] * $item["OfferItem"]["amount"] * (1 - $item["OfferItem"]["discount"] / 100);
		}
		
		// Ukupno
		$doc->Cell(190, 0, '', 'T');
		$doc->Ln();
		$doc->Cell(190 - $w[6]);
		$doc->Cell($w[6], 6, number_format($uk, 2, '.', ' '), 0, 0, 'R');
		
		$doc->Ln(20);
		$doc->Cell(65);
		$doc->Cell(50, 20, "Obradio", 'B', 0, 'C');
		
		// Spremi PDF u datoteku
		$pdfPath = 'C:/wamp/www/malo/app/webroot/res/files/';
		$pdfFile = 'ponuda.pdf';
		
		$doc->Output($pdfPath . $pdfFile, 'F');
		
		echo "OK - PDF spremljen: " . $pdfPath . $pdfFile;
		echo "<br><br><a href='/malo/res/files/ponuda.pdf' target='_blank'>Otvori PDF</a>";
	}

	function print_work_order($id = null, $with_notes = 0)
	{
		$with_notes = (int)$with_notes;
		$g_v = get_valuta();

		$restFooter = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'invoice.footer')));

		$doc = new Document("", $restFooter["Setting"]["value"], "");
		$doc->AddPage();
		
		// Dohvati postavke
		$restName = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.name')));
		$restpost = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.post')));
		$restComm = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.resort')));
		$restStreet = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.street')));
		$restStrNum = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num')));
		$restStrNumMark = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.str_num_mark')));
		$restPlaceid = $this->Setting->find('first', array('conditions' => array('Setting.name' => 'general.placeid')));

		// Dohvati radni nalog
		$this->RadniNalog->recursive = 2;
		$rec = $this->RadniNalog->find('first', array(
			'conditions' => array('RadniNalog.id' => $id),
			'contain' => array('Customer', 'RadniNalogStatus', 'Automobil', 'Uredjaj')
		));
		
		// Debug - provjeri da li su podaci dohvaćeni
		// error_log(print_r($rec['RadniNalog'], true));
		
		// Dohvati stavke (artikle) s Article podacima
		$this->loadModel('RadniNalogStavka');
		$stavke = $this->RadniNalogStavka->find('all', array(
			'conditions' => array('RadniNalogStavka.radni_nalog_id' => $id),
			'contain' => array('Article')
		));

		// Helper za konverziju hrvatskih znakova (ručna zamjena za FPDF)
		$conv = function($text) {
			if (empty($text)) return '';
			$search = array('č', 'ć', 'š', 'ž', 'đ', 'Č', 'Ć', 'Š', 'Ž', 'Đ');
			$replace = array(chr(232), chr(230), chr(154), chr(158), chr(240), chr(200), chr(198), chr(138), chr(142), chr(208));
			return str_replace($search, $replace, $text);
		};

		// ===== HEADER - Naziv firme =====
		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(100);
		$doc->Cell(0, 5, $conv($restName["Setting"]["value"]), 0, 2);
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(0, 5, $conv($restpost["Setting"]["value"] . ' ' . $restComm["Setting"]["value"] . ', ' . $restStreet["Setting"]["value"] . ' ' . $restStrNum["Setting"]["value"] . $restStrNumMark["Setting"]["value"]), 0, 2);
		$doc->Cell(0, 5, $conv($restPlaceid["Setting"]["value"]), 0, 0);
		$doc->Ln(10);

		// ===== KUPAC I BROJ DOKUMENTA =====
		$doc->SetFont('ArialCE', 'B', 12);
		$doc->Cell(90, 8, $conv($rec["Customer"]["name"]), 'LTR', 0);
		$doc->Cell(10);
		$doc->SetFont('ArialCE', 'B', 11);
		$doc->Cell(90, 8, 'RADNI NALOG #' . $rec["RadniNalog"]["number"], 'LTRB', 0, 'C');
		$doc->Ln();

		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(90, 5, $conv($rec["Customer"]["address"] . ', ' . $rec["Customer"]["city"]), 'LR', 0);
		$doc->Cell(10);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(90, 5, "Broj dokumenta:  " . $rec["RadniNalog"]["number"], 'LR', 0);
		$doc->Ln();

		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(90, 5, "OIB: " . $rec["Customer"]["oib"], 'LRB', 0);
		$doc->Cell(10);
		$doc->SetFont('Courier', '', 8);
		$dtRnDoc = !empty($rec["RadniNalog"]["datum_rn"]) && $rec["RadniNalog"]["datum_rn"] != '0000-00-00' ? date('d.m.Y', strtotime($rec["RadniNalog"]["datum_rn"])) : '-';
		$doc->Cell(90, 5, "Datum RN: " . $dtRnDoc, 'LRB', 0);
		$doc->Ln(10);

		// ===== OSNOVNI PODACI =====
		$doc->SetFillColor(240, 240, 240);
		$doc->SetFont('ArialCE', 'B', 9);
		$doc->Cell(190, 6, ' OSNOVNI PODACI', 1, 1, 'L', true);
		
		$doc->SetFont('ArialCE', '', 8);
		$dtObecan = !empty($rec["RadniNalog"]["datum_obecan"]) && $rec["RadniNalog"]["datum_obecan"] != '0000-00-00' ? date('d.m.Y', strtotime($rec["RadniNalog"]["datum_obecan"])) : '-';
		$dtGotovo = !empty($rec["RadniNalog"]["datum_gotovo"]) && $rec["RadniNalog"]["datum_gotovo"] != '0000-00-00' ? date('d.m.Y', strtotime($rec["RadniNalog"]["datum_gotovo"])) : '-';
		
		$doc->Cell(45, 5, 'Datum dogovoren:', 'L', 0);
		$doc->Cell(50, 5, $dtObecan, 'R', 0);
		$doc->Cell(45, 5, 'Status:', 'L', 0);
		$doc->Cell(50, 5, $conv(!empty($rec['RadniNalogStatus']['naziv']) ? $rec['RadniNalogStatus']['naziv'] : '-'), 'R', 1);
		
		$doc->Cell(45, 5, 'Datum gotovo:', 'L', 0);
		$doc->Cell(50, 5, $dtGotovo, 'R', 1);
		
		$doc->Cell(45, 5, $conv('Kilometraža:'), 'LB', 0);
		$doc->Cell(50, 5, (!empty($rec["RadniNalog"]["km"]) ? number_format($rec["RadniNalog"]["km"], 0, ',', '.') . ' km' : '-'), 'RB', 0);
		$doc->Cell(45, 5, 'Broj RH:', 'LB', 0);
		$doc->Cell(50, 5, (!empty($rec["RadniNalog"]["broj_rh"]) ? $rec["RadniNalog"]["broj_rh"] : '-'), 'RB', 1);
		$doc->Ln(3);

		// ===== PREDMET RADNOG NALOGA (Automobil ili Uređaj) =====
		if (!empty($rec['Automobil']['id']) || !empty($rec['Uredjaj']['id'])) {
			$doc->SetFont('ArialCE', 'B', 9);
			$doc->Cell(190, 6, ' PREDMET RADNOG NALOGA', 1, 1, 'L', true);
			
			if (!empty($rec['Automobil']['id'])) {
				// Dohvati gorivo
				$this->loadModel('Gorivo');
				$gorivo = '';
				if (!empty($rec['Automobil']['gorivo_id'])) {
					$g = $this->Gorivo->find('first', array('conditions' => array('Gorivo.id' => $rec['Automobil']['gorivo_id'])));
					$gorivo = !empty($g['Gorivo']['naziv']) ? $g['Gorivo']['naziv'] : '';
				}
				
				$doc->SetFont('ArialCE', 'B', 8);
				$doc->SetFillColor(230, 245, 255);
				$doc->Cell(190, 5, ' AUTOMOBIL', 'LR', 1, 'L', true);
				
				$doc->SetFont('ArialCE', '', 8);
				$doc->Cell(45, 5, 'Marka / Model:', 'L', 0);
				$doc->Cell(50, 5, $conv($rec['Automobil']['marka'] . ' ' . $rec['Automobil']['tip']), 'R', 0);
				$doc->Cell(45, 5, 'Reg. oznaka:', 'L', 0);
				$doc->Cell(50, 5, $rec['Automobil']['registarska_oznaka'], 'R', 1);
				
				$doc->Cell(45, 5, 'VIN:', 'L', 0);
				$doc->Cell(50, 5, $rec['Automobil']['vin'], 'R', 0);
				$doc->Cell(45, 5, 'Gorivo:', 'L', 0);
				$doc->Cell(50, 5, $conv($gorivo), 'R', 1);
				
				$doc->Cell(45, 5, 'God. proizvodnje:', 'LB', 0);
				$doc->Cell(50, 5, $rec['Automobil']['god_proizvodnje'], 'RB', 0);
				$doc->Cell(45, 5, 'Boja:', 'LB', 0);
				$doc->Cell(50, 5, $conv($rec['Automobil']['boja']), 'RB', 1);
			}
			
			if (!empty($rec['Uredjaj']['id'])) {
				$doc->SetFont('ArialCE', 'B', 8);
				$doc->SetFillColor(255, 245, 230);
				$doc->Cell(190, 5, $conv(' UREDAJ'), 'LR', 1, 'L', true);
				
				$doc->SetFont('ArialCE', '', 8);
				$doc->Cell(45, 5, $conv('Naziv uredaja:'), 'L', 0);
				$doc->Cell(50, 5, $conv($rec['Uredjaj']['naziv_uredjaja']), 'R', 0);
				$doc->Cell(45, 5, 'Serijski broj:', 'L', 0);
				$doc->Cell(50, 5, $rec['Uredjaj']['serijski_broj'], 'R', 1);
				
				$doc->Cell(45, 5, $conv('Tvornicki broj:'), 'L', 0);
				$doc->Cell(50, 5, $rec['Uredjaj']['tvornicki_broj'], 'R', 0);
				$doc->Cell(45, 5, $conv('Proizvodac:'), 'L', 0);
				$doc->Cell(50, 5, $conv($rec['Uredjaj']['proizvodjac']), 'R', 1);
				
				$doc->Cell(45, 5, 'Tip stroja:', 'LB', 0);
				$doc->Cell(145, 5, $conv($rec['Uredjaj']['tip_stroja']), 'RB', 1);
			}
			$doc->Ln(3);
		}

		// ===== NAPOMENA RN I NAPOMENA UZ PONUDU =====
		if (!empty($rec['RadniNalog']['napomena_rn']) || !empty($rec['RadniNalog']['napomena_ponuda'])) {
			$doc->SetFont('ArialCE', 'B', 9);
			$doc->Cell(190, 6, ' NAPOMENE', 1, 1, 'L', true);
			$doc->SetFont('ArialCE', '', 8);
			
			if (!empty($rec['RadniNalog']['napomena_rn'])) {
				$doc->SetFont('ArialCE', 'B', 8);
				$doc->Cell(190, 5, 'Napomena RN:', 'LR', 1, 'L');
				$doc->SetFont('ArialCE', '', 8);
				$doc->MultiCell(190, 5, $conv($rec['RadniNalog']['napomena_rn']), 'LR', 'L');
			}
			if (!empty($rec['RadniNalog']['napomena_ponuda'])) {
				$doc->SetFont('ArialCE', 'B', 8);
				$doc->Cell(190, 5, 'Napomena uz ponudu:', 'LR', 1, 'L');
				$doc->SetFont('ArialCE', '', 8);
				$doc->MultiCell(190, 5, $conv($rec['RadniNalog']['napomena_ponuda']), 'LRB', 'L');
			} else {
				$doc->Cell(190, 0, '', 'T', 1);
			}
			$doc->Ln(3);
		}

		// ===== STAVKE RADNOG NALOGA (Artikli/Usluge) =====
		if (!empty($stavke)) {
			$doc->SetFont('ArialCE', 'B', 9);
			$doc->Cell(190, 6, ' STAVKE RADNOG NALOGA (' . count($stavke) . ')', 1, 1, 'L', true);
			$doc->Ln(2);
			
			// Header tablice
			$doc->SetFont('ArialCE', 'B', 8);
			$doc->SetFillColor(245, 245, 245);
			$doc->Cell(10, 6, 'RB', 1, 0, 'C', true);
			$doc->Cell(155, 6, 'Artikl / Usluga', 1, 0, 'C', true);
			$doc->Cell(25, 6, $conv('Kolicina'), 1, 1, 'C', true);
			
			$doc->SetFont('ArialCE', '', 8);
			$rb = 1;
			$ukupno = 0;
			foreach ($stavke as $stavka) {
				$artiklNaziv = !empty($stavka['Article']['name']) ? $stavka['Article']['name'] : 'Nepoznat artikl';
				$kolicina = floatval($stavka['RadniNalogStavka']['amount']);
				$cijena = !empty($stavka['Article']['price_sell']) ? floatval($stavka['Article']['price_sell']) : 0;
				$popust = floatval($stavka['RadniNalogStavka']['discount']);
				$iznos = $kolicina * $cijena * (1 - $popust / 100);
				$ukupno += $iznos;
				
				$doc->Cell(10, 5, $rb, 'LR', 0, 'C');
				$doc->Cell(155, 5, $conv($artiklNaziv), 0, 0, 'L');
				$doc->Cell(25, 5, number_format($kolicina, 2, ',', '.'), 'R', 1, 'C');
				
				// Ispis napomene ako je uključeno i postoji
				if ($with_notes && !empty($stavka['RadniNalogStavka']['napomena'])) {
					$doc->SetFont('ArialCE', 'I', 7);
					$doc->SetTextColor(100, 100, 100);
					$doc->Cell(10, 4, '', 'LR', 0, 'C');
					$doc->Cell(180, 4, '   ' . $conv($stavka['RadniNalogStavka']['napomena']), 'R', 1, 'L');
					$doc->SetTextColor(0, 0, 0);
					$doc->SetFont('ArialCE', '', 8);
				}
				
				// Horizontalna linija ispod stavke
				$doc->Cell(190, 0, '', 'T', 1);
				
				$rb++;
			}
			$doc->Ln(3);
		}

		// ===== POTPIS =====
		$doc->Ln(10);
		$doc->SetFont('ArialCE', '', 8);
		$doc->Cell(95, 5, '_______________________________', 0, 0, 'C');
		$doc->Cell(95, 5, '_______________________________', 0, 1, 'C');
		$doc->Cell(95, 5, 'Izradio', 0, 0, 'C');
		$doc->Cell(95, 5, 'Odobrio', 0, 1, 'C');

		$doc->output();
		die();
	}


	function daily_report_of_sale_with_tax()
	{
		$this->raw_daily_report_of_sale_with_tax();
		//$doc= new Document;
		//$doc->output();
		die();
	}

	function json_report_normativ()
	{

		$ret = array();

		@$res = "Pregled prodaje po normativu\n@@N\n\n";

		if (!empty($this->filterParams["user"]))
			$res .= "Filter po zaposlenom: " . $this->Sale->getUsername((int) $this->filterParams["user"]) . "\n\n";

		$result = $this->Sale->reportNormativ($this->filterParams);

		$rss = array();
		foreach ($result as $t) {
			$rss[$t["p"]["name"]] = array();
			$rss[$t["p"]["name"]]["amount"] = $t[0]["amount"];
			$rss[$t["p"]["name"]]["price"] = $t[0]["price"];
			$rss[$t["p"]["name"]]["total_price"] = $t[0]["total_price"];
		}

		$ret[0] = array("text" => $res, "obj" => $rss);


		die(json_encode($ret, JSON_FORCE_OBJECT));
		//$doc= new Document;

		//$doc->output();

	}


	function json_report_articles()
	{

		$ret = array();

		@$res = "Pregled prodaje po artiklima\n@@N\n\n";

		if (!empty($this->filterParams["user"]))
			$res .= "Filter po zaposlenom: " . $this->Sale->getUsername((int) $this->filterParams["user"]) . "\n\n";

		$result = $this->Sale->reportArticlesNew($this->filterParams);

		$rss = array();
		foreach ($result as $t) {
			$rss[$t["a"]["name"]] = array();
			$rss[$t["a"]["name"]]["amount"] = $t[0]["amount"];
			$rss[$t["a"]["name"]]["unit"] = $t["a"]["unit"];
			$rss[$t["a"]["name"]]["price"] = $t["a"]["price"];
			$rss[$t["a"]["name"]]["total_price"] = $t[0]["price_total"];
		}

		$ret[0] = array("text" => $res, "obj" => $rss);


		die(json_encode($ret, JSON_FORCE_OBJECT));

	}

	function json_report_storage()
	{

		$ret = array();

		@$res = "Stanje skladišta\n@@N\n\n";

		$result = $this->Sale->reportArticlesStorage();

		$rss = array();
		foreach ($result as $t) {
			$rss[$t["articles"]["id"]] = array();
			$rss[$t["articles"]["id"]]["name"] = $t["articles"]["name"];
			$rss[$t["articles"]["id"]]["amount"] = $t["articles"]["amount"];
			$rss[$t["articles"]["id"]]["unit"] = $t["articles"]["unit"];
		}

		$ret[0] = array("text" => $res, "obj" => $result);

		die(json_encode($ret, JSON_FORCE_OBJECT));
	}


	function json_report_tax_group_for_period()
	{

		$ret = array();

		@$res = "Rekapitulacija prometa\n@@N\n\n";

		$result = $this->Sale->reportTaxGroupForPeriod($this->filterParams);

		$rss = array();
		foreach ($result as $t) {
			//die(json_encode($t, JSON_FORCE_OBJECT));	
			$rss[$t["tg"]["name"]] = array();
			$rss[$t["tg"]["name"]]["base_price"] = $t[0]["base_price"];
			$rss[$t["tg"]["name"]]["pdv"] = $t[0]["pdv"];
			$rss[$t["tg"]["name"]]["pnp"] = $t[0]["pnp"];
			$rss[$t["tg"]["name"]]["tax_total"] = $t[0]["tax_total"];
			$rss[$t["tg"]["name"]]["price_total"] = $t[0]["price_total"];


		}

		$ret[0] = array("text" => $res, "obj" => $rss);


		die(json_encode($ret, JSON_FORCE_OBJECT));
	}

	function json_pnp_group_for_period()
	{

		$ret = array();

		@$res = "Mjesečno izvješće o obračunu i uplati poreza na potrošnju\nZa razdoblje\nod: " . date_format(date_create_from_format('Y-m-d', $this->filterParams["date_start"]), "d-m-Y") . " do " . date_format(date_create_from_format('Y-m-d', $this->filterParams["date_end"]), "d-m-Y") . "@@N\n\n";

		$result = $this->Sale->reportPNP($this->filterParams);

		$rss = array();
		foreach ($result as $t) {
			//die(json_encode($t, JSON_FORCE_OBJECT));	
			$rss[$t["t"]["id"]] = array();
			$rss[$t["t"]["id"]]["name"] = $t["t"]["name"];
			$rss[$t["t"]["id"]]["base"] = $t[0]["base"];
			$rss[$t["t"]["id"]]["tax"] = $t["t"]["tax_2"];
			$rss[$t["t"]["id"]]["pnp"] = $t[0]["pnp"];
		}

		$ret[0] = array("text" => $res, "obj" => $rss);


		die(json_encode($ret, JSON_FORCE_OBJECT));
	}

	protected function getBarcodeForDocument($record, $docType)
	{
		$sale = $record['Sale'];
		$customer = $record['Customer'];

		$allSettings = $this->Setting->find('all');
		$allSettings = array_map(function ($a) {
			return $a['Setting'];
		}, $allSettings);
		$allSettings = array_column($allSettings, 'value', 'name');
		$settings = [
			'company_name' => $allSettings['general.name'],
			'company_address' => $allSettings['general.street'] . ' ' . $allSettings['general.str_num'] . ' ' . $allSettings['general.str_num_mark'],
			'company_postcode' => $allSettings['general.post'],
			'company_city' => $allSettings['general.community'],
			'company_iban' => $allSettings['general.iban'],
		];


		$docName = '';
		$docBroj = '';
		switch ($docType) {
			case 'ponude':
				$docBroj = $sale['number'] . '/' . date('y', strtotime($sale['date']));
				$docName = 'Ponudi';
				break;
			case 'racuni':
				$docBroj = $sale['number'];
				$docName = 'Računu';
				break;
		}

		$content = [
			'Zaglavlje' => 'HRVHUB30',
			'Valuta' => 'EUR',
			'Iznos' => str_pad((intval($sale['price'] * 100)), 15, '0', STR_PAD_LEFT),
			'Platitelj' => mb_strimwidth($customer['name'], 0, 30),
			'Adresa platitelja (ulica i broj)' => mb_strimwidth($customer['address'], 0, 27),
			'Adresa platitelja (poštanski broj i mjesto)' => mb_strimwidth($customer['zip'] . ' ' . $customer['city'], 0, 27),
			'Primatelj (naziv/ime i prezime)' => mb_strimwidth($settings['company_name'], 0, 25),
			'Adresa primatelja (ulica i broj)' => mb_strimwidth($settings['company_address'], 0, 25),
			'Adresa primatelja (poštanski broj i mjesto)' => mb_strimwidth($settings['company_postcode'] . ' ' . $settings['company_city'], 0, 27),
			'Broj računa primatelja (IBAN)' => mb_strimwidth($settings['company_iban'], 0, 21),
			'Model kontrole poziva na broj primatelja' => 'HR00',
			'Poziv na broj primatelja' => mb_strimwidth($sale['id'] . '-' . date('dmY', strtotime($sale['date'])), 0, 22),
			'Šifra namjene' => 'GDSV',
			'Opis plaćanja' => mb_strimwidth('Plaćanje po ' . $docName . ' ' . $docBroj, 0, 35),
		];

		$str = implode("\n", $content) . "\n";

		return $this->get2DCode($str);
	}

	private function get2DCode($content)
	{
		// PDF417 (ISO/IEC 15438:2006)
		/*
			   The $type parameter can be simple 'PDF417' or 'PDF417' followed by a
			   number of comma-separated options:

			   'PDF417,a,e,t,s,f,o0,o1,o2,o3,o4,o5,o6'

			   Possible options are:

				   a  = aspect ratio (width/height);
				   e  = error correction level (0-8);

				   Macro Control Block options:

				   t  = total number of macro segments;
				   s  = macro segment index (0-99998);
				   f  = file ID;
				   o0 = File Name (text);
				   o1 = Segment Count (numeric);
				   o2 = Time Stamp (numeric);
				   o3 = Sender (text);
				   o4 = Addressee (text);
				   o5 = File Size (numeric);
				   o6 = Checksum (numeric).

			   Parameters t, s and f are required for a Macro Control Block, all other parametrs are optional.
			   To use a comma character ',' on text options, replace it with the character 255: "\xff".
			  */
		$type = 'PDF417,3,4';
		$barcodeobj = new TCPDF2DBarcode($content, $type);
		return $barcodeobj->getBarcodePngData();
	}

	/**
	 * Konvertira UTF-8 tekst u Windows-1250 za FPDF
	 * Podržava hrvatske znakove: č, ć, š, ž, đ
	 */
	private function _utf8ToIso($text) {
		if (empty($text)) return '';
		// Konvertiraj UTF-8 u Windows-1250 za hrvatske znakove
		$converted = @iconv('UTF-8', 'WINDOWS-1250//TRANSLIT', $text);
		if ($converted === false) {
			// Fallback na ručnu zamjenu ako iconv ne radi
			$search = array('č', 'ć', 'š', 'ž', 'đ', 'Č', 'Ć', 'Š', 'Ž', 'Đ');
			$replace = array('c', 'c', 's', 'z', 'd', 'C', 'C', 'S', 'Z', 'D');
			return str_replace($search, $replace, $text);
		}
		return $converted;
	}

	/**
	 * Generira sadržaj za QR kod (HUB3 format)
	 * Format: https://www.hub.hr/sites/default/files/inline-files/2dbc_0.pdf
	 */
	protected function getQRCodeContent($record, $docType) {
		// Za ponude koristimo Offer podatke
		if ($docType == 'ponude') {
			$sale = $record['Offer'];
		} else {
			$sale = $record['Sale'];
		}
		$customer = $record['Customer'];

		$allSettings = $this->Setting->find('all');
		$allSettings = array_map(function ($a) {
			return $a['Setting'];
		}, $allSettings);
		$allSettings = array_column($allSettings, 'value', 'name');
		
		$settings = [
			'company_name' => isset($allSettings['general.name']) ? $allSettings['general.name'] : '',
			'company_address' => (isset($allSettings['general.street']) ? $allSettings['general.street'] : '') . ' ' . 
				(isset($allSettings['general.str_num']) ? $allSettings['general.str_num'] : '') . 
				(isset($allSettings['general.str_num_mark']) ? $allSettings['general.str_num_mark'] : ''),
			'company_postcode' => isset($allSettings['general.post']) ? $allSettings['general.post'] : '',
			'company_city' => isset($allSettings['general.community']) ? $allSettings['general.community'] : '',
			'company_iban' => isset($allSettings['general.iban']) ? $allSettings['general.iban'] : '',
		];

		// Izračunaj ukupnu cijenu
		$totalPrice = 0;
		if (!empty($record['OfferItem'])) {
			foreach ($record['OfferItem'] as $item) {
				$totalPrice += $item['price_sell'] * $item['amount'] * (1 - $item['discount'] / 100);
			}
		}

		$docBroj = $sale['number'];
		$docName = ($docType == 'ponude') ? 'Ponudi' : 'Racunu';
		$dateField = isset($sale['date']) ? $sale['date'] : (isset($sale['created']) ? $sale['created'] : date('Y-m-d'));
		
		// Poziv na broj - bez specijalnih znakova
		$pozivNaBroj = $sale['id'] . '-' . date('dmY', strtotime($dateField));
		
		// Pripremi podatke - ukloni dijakritike za QR
		$platiteljIme = $this->_removeAccents($customer['name']);
		$platiteljAdresa = $this->_removeAccents($customer['address']);
		$platiteljMjesto = $this->_removeAccents((isset($customer['zip']) ? $customer['zip'] : '') . ' ' . $customer['city']);
		$primateljIme = $this->_removeAccents($settings['company_name']);
		$primateljAdresa = $this->_removeAccents($settings['company_address']);
		$primateljMjesto = $this->_removeAccents($settings['company_postcode'] . ' ' . $settings['company_city']);
		$opisPlacanja = $this->_removeAccents('Placanje po ' . $docName . ' ' . $docBroj);

		// HUB3 format prema specifikaciji
		// https://www.hub.hr/sites/default/files/inline-files/2dbc_0.pdf
		$lines = array();
		$lines[] = 'HRVHUB30';                                           // 1. Zaglavlje (8 znakova)
		$lines[] = 'EUR';                                                 // 2. Valuta (3 znaka)
		$lines[] = str_pad(intval(round($totalPrice * 100)), 15, '0', STR_PAD_LEFT); // 3. Iznos u centima (15 znakova)
		$lines[] = mb_substr($platiteljIme, 0, 30);                       // 4. Platitelj - ime (max 30)
		$lines[] = mb_substr($platiteljAdresa, 0, 27);                    // 5. Platitelj - ulica (max 27)
		$lines[] = mb_substr($platiteljMjesto, 0, 27);                    // 6. Platitelj - mjesto (max 27)
		$lines[] = mb_substr($primateljIme, 0, 25);                       // 7. Primatelj - ime (max 25)
		$lines[] = mb_substr($primateljAdresa, 0, 25);                    // 8. Primatelj - ulica (max 25)
		$lines[] = mb_substr($primateljMjesto, 0, 27);                    // 9. Primatelj - mjesto (max 27)
		$iban = !empty($settings['company_iban']) ? $settings['company_iban'] : 'HR0000000000000000000';
		$lines[] = $iban;                                                 // 10. IBAN primatelja (21 znak)
		$lines[] = 'HR00';                                                // 11. Model placanja (4 znaka)
		$lines[] = mb_substr($pozivNaBroj, 0, 22);                        // 12. Poziv na broj (max 22)
		$lines[] = 'COST';                                                // 13. Sifra namjene (4 znaka)
		$lines[] = mb_substr($opisPlacanja, 0, 35);                       // 14. Opis placanja (max 35)

		// Spoji s LF (\n) separatorom
		return implode("\n", $lines);
	}
	
	/**
	 * Uklanja dijakritike iz teksta (za QR kod)
	 */
	private function _removeAccents($text) {
		if (empty($text)) return '';
		$search = array('č', 'ć', 'š', 'ž', 'đ', 'Č', 'Ć', 'Š', 'Ž', 'Đ');
		$replace = array('c', 'c', 's', 'z', 'd', 'C', 'C', 'S', 'Z', 'D');
		return str_replace($search, $replace, $text);
	}

	/**
	 * Generira QR kod sliku kao PNG binary
	 */
	protected function getQRCodeImage($content) {
		$type = 'QRCODE,H'; // H = High error correction
		$barcodeobj = new TCPDF2DBarcode($content, $type);
		return $barcodeobj->getBarcodePngData(3, 3);
	}

}
