<?php
if (! defined('sugarEntry') || ! sugarEntry)
	die('Not A Valid Entry Point');
/**
 * ***************************************************************************
 * The contents of this file are subject to the RECIPROCAL PUBLIC LICENSE
 * Version 1.1 ("License"); You may not use this file except in compliance
 * with the License.
 * You may obtain a copy of the License at
 * http://opensource.org/licenses/rpl.php. Software distributed under the
 * License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied.
 *
 * You may:
 * a) Use and distribute this code exactly as you received without payment or
 * a royalty or other fee.
 * b) Create extensions for this code, provided that you make the extensions
 * publicly available and document your modifications clearly.
 * c) Charge for a fee for warranty or support or for accepting liability
 * obligations for your customers.
 *
 * You may NOT:
 * a) Charge for the use of the original code or extensions, including in
 * electronic distribution models, such as ASP (Application Service
 * Provider).
 * b) Charge for the original source code or your extensions other than a
 * nominal fee to cover distribution costs where such distribution
 * involves PHYSICAL media.
 * c) Modify or delete any pre-existing copyright notices, change notices,
 * or License text in the Licensed Software
 * d) Assert any patent claims against the Licensor or Contributors, or
 * which would in any way restrict the ability of any third party to use the
 * Licensed Software.
 *
 * You must:
 * a) Document any modifications you make to this code including the nature of
 * the change, the authors of the change, and the date of the change.
 * b) Make the source code for any extensions you deploy available via an
 * Electronic Distribution Mechanism such as FTP or HTTP download.
 * c) Notify the licensor of the availability of source code to your extensions
 * and include instructions on how to acquire the source code and updates.
 * d) Grant Licensor a world-wide, non-exclusive, royalty-free license to use,
 * reproduce, perform, modify, sublicense, and distribute your extensions.
 *
 * The Original Code is: CommuniCore
 * Olavo Farias
 * 2006-04-7 olavo.farias@gmail.com
 *
 * The Initial Developer of the Original Code is CommuniCore.
 * Portions created by CommuniCore are Copyright (C) 2005 CommuniCore Ltda
 * All Rights Reserved.
 * ******************************************************************************
 */
require_once('data/SugarBean.php');
require_once('include/utils.php');
class EcmInvoiceOut extends SugarBean
{
	var $field_name_map = array();
	// STANDARD FIELDS
	var $id;
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $assigned_user_id;
	var $name;
	var $description;
	// TABLE COLUMNS
	var $number;
	var $document_no;
	var $parent_type;
	var $parent_name;
	var $parent_nip;
	var $sell_date;
	var $payment_date;
	var $payment_date_days;
	var $payment_method;
	var $pdf_type;
	var $wz_id;
	var $wz_name;
	var $parent_id;
	var $type;
	var $status;
	var $register_date;
	var $parent_address_street;
	var $parent_address_city;
	var $parent_address_postalcode;
	var $parent_address_country;
	var $subtotal;
	var $total;
	var $discount;
	var $to_vatid;
	var $ecmlanguage;
	var $to_is_vat_free;
	var $header_text;
	var $footer_text;
	var $ads_text;
	var $template_id;
	var $template_name;
	var $email_id;
	var $parent_name_copy;
	var $parent_contact_name;
	var $parent_contact_title;
	var $ecmpaymentcondition_id;
	var $ecmpaymentcondition_name;
	var $ecmpaymentcondition_text;
	var $ecmdeliverycondition_id;
	var $ecmdeliverycondition_name;
	var $ecmdeliverycondition_text;
	var $validtill_date;
	var $order_origin;
	var $contact_id;
	var $contact_name;
	var $show_images_on_offers;
	var $currency_symbol;
	var $currency_id;
	var $show_ean;
	var $template;
	var $pdf;
	var $position_list;
	var $parser;
	var $account;
	var $contact;
	var $user;
	var $mfp;
	var $so_id;
	// added 4.03.2009
	var $pricebook_id;
	var $show_recipient_code;
	// RELATED FIELDS
	var $created_by;
	var $created_by_name;
	var $modified_by_name;
	var $assigned_user_name;
	// SUBPANELS RELATED
	// MODULE OBJECT DETAILS
	var $module_dir = "EcmInvoiceOuts";
	var $table_name = "ecminvoiceouts";
	var $object_name = "EcmInvoiceOut";
	// RELATED TABLE NAMES
	// USED TO RETRIEVE RELATED FIELDS FROM FORM POSTS.
	var $additional_column_fields = array(
		'assigned_user_name',
		'assigned_user_id',
		'modified_user_id',
		'created_by'
	);
	// RELATIONSHIP FIELDS
	var $relationship_fields = array(
			'note_id' => 'notes',
			'email_id' => 'emails'
		)
		// 'account_id' => 'account',
		// 'contact_id' => 'contact',
	;
	function EcmInvoiceOut()
	{
		parent::SugarBean();
		$this->setupCustomFields('EcmInvoiceOuts');
		foreach ($this->field_defs as $field) {
			$this->field_name_map[$field['name']] = $field;
		}
	}
	var $new_schema = true;
	function get_summary_text()
	{
		return "$this->name";
	}
	function create_list_query($order_by, $where, $show_deleted = 0)
	{
		// Fill in the assigned_user_name[pl]
		$custom_join = $this->custom_fields->getJOIN();
		$query = "SELECT ";
		$query .= "ecminvoiceouts.*
                  ,users.user_name as assigned_user_name";
		if ($custom_join) {
			$query .= $custom_join['select'];
		}
		$query .= " FROM ecminvoiceouts 
                   LEFT JOIN users
                   ON ecminvoiceouts.assigned_user_id=users.id";
		$query .= "  ";
		if ($custom_join) {
			$query .= $custom_join['join'];
		}
		$where_auto = '1=1';
		if ($show_deleted == 0) {
			$where_auto = " $this->table_name.deleted=0 ";
		} else if ($show_deleted == 1) {
			$where_auto = " $this->table_name.deleted=1 ";
		}
		if ($where != "")
			$query .= "where $where AND " . $where_auto;
		else
			$query .= "where " . $where_auto;
		if (substr_count($order_by, '.') > 0) {
			$query .= " ORDER BY $order_by";
		} else if ($order_by != "")
			$query .= " ORDER BY $order_by";
		else
			$query .= " ORDER BY ecminvoiceouts.name";
		echo $query;
		return $query;
	}
	function create_export_query($order_by, $where)
	{
		$custom_join = $this->custom_fields->getJOIN();
		$query = "SELECT
                      ecminvoiceouts.*,
                      users.user_name assigned_user_name";
		if ($custom_join) {
			$query .= $custom_join['select'];
		}
		$query .= " FROM ecminvoiceouts ";
		$query .= " LEFT JOIN users
                  ON ecminvoiceouts.assigned_user_id=users.id";
		if ($custom_join) {
			$query .= $custom_join['join'];
		}
		$query .= "";
		$where_auto = " ecminvoiceouts.deleted=0 
                    ";
		if ($where != "")
			$query .= " where $where AND " . $where_auto;
		else
			$query .= " where " . $where_auto;
		if ($order_by != "")
			$query .= " ORDER BY $order_by";
		else
			$query .= " ORDER BY ecminvoiceouts.name";
		return $query;
	}
	function fill_in_additional_list_fields() {}
	function check_mail_addresses()
	{
		$sea = new SugarEmailAddress;
		$addresses = $sea->getAddressesByGUID($this->parent_id, 'Accounts');
		$check = 0;
		foreach ($addresses as $address) {
			if ($address['email_address'] != '' && $address['opt_out'] == 1) {
				$check = 1;
			}
		}
		return $check;
	}
	function fill_in_additional_detail_fields()
	{
		// FILL IN THE ASSIGNED_USER_NAME
		$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
		$this->created_by_name = get_assigned_user_name($this->created_by);
		$this->modified_by_name = get_assigned_user_name($this->modified_user_id);
		//$this->document_autoincrement=date("Y-m-d",strtotime($this->register_date)).' '.date('H:i:s',strtotime($this->date_entered));
		//echo $this->document_autoincrement.'<br>';
		/*
		 * $result = $this->db->query ( "SELECT status, parent_id, contact_id, template_id, assigned_user_id FROM ecminvoiceouts WHERE id='$this->id'" );
		 * if (is_resource ( $result )) {
		 * $row = $this->db->fetchByAssoc ( $result );
		 * if ($row) {
		 * $this->status = $row ['status'];
		 * $this->parent_id = $row ['parent_id'];
		 * $this->contact_id = $row ['contact_id'];
		 * $this->template_id = $row ['template_id'];
		 * $this->assigned_user_id = $row ['assigned_user_id'];
		 * }
		 * }
		 */
		/*
		 * $query = "select `number`, `template_id` from `ecminvoiceouts` where `id`='$this->id' limit 1"; $r = $this->db->query($query); if($r) { $r = $this->db->fetchByAssoc($r); $this->template_id = $r['template_id']; $this->number = $r['number']; $this->setTemplate(); $this->document_no = $this->formatNumber(); }
		 */
	}
	function get_list_view_data()
	{
		global $current_language;
		$this->fill_in_additional_detail_fields();
		$app_list_strings = return_app_list_strings_language($current_language);
		$mod_strings = return_module_language($current_language, 'EcmInvoiceOuts');
		$the_array = parent::get_list_view_data();
		// THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL
		// THE COLUMNS SO WE NEED THESE CHECKS.
		if ($this->ecmproduct_id != '') {
			//add subpanel data
			$tmp = $this->getPriceFromDocument($this->ecmproduct_id);

			$the_array['QUANTITY'] = format_number($tmp['quantity']);
			$the_array['PRICE_NETTO'] = format_number($tmp['price_netto']);
			$the_array['TOTAL_NETTO'] = $tmp['total_netto'];
		}
		//
		$this->retrieve($this->id);
		$the_array['PARENT_NAME'] = '<a href="index.php?module=Accounts&action=DetailView&record=' . $this->parent_id . '">' . $this->parent_name . '</a>';
		$the_array['NUMBER'] = '<a href="index.php?module=EcmInvoiceOuts&action=DetailView&record=' . $this->id . '">' . $this->document_no . '</a>';
		$the_array['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
		$type = $this->type == 'normal' ? 'F' : 'K';
		$the_array['TYPE'] = $type;
		$c = new Currency();
		$c->retrieve($this->currency_id);
		$the_array['CURRENCY'] = $c->name;
		//$the_array['DOCUMENT_AUTOINCREMENT']=date('d.m.Y',strtotime($this->register_date));
		unset($c);
		//$the_array ['PARENT_NAME'] = '<a href="index.php?module=Accounts&action=DetailView&record=' . $this->parent_id . '">' . $this->parent_name . '</a>';
		// $the_array ['TOTAL'] = format_number ( $this->total_netto );
		// create image options
		$op = '<a href="index.php?module=EcmInvoiceOuts&action=createPDF&pdf_type=0&to_pdf=1&show_img=1&show_ean=0&show_ean2=0&show_recipient_code=0&record=' . $this->id . '" target="new"/><img src="modules/EcmInvoiceOuts/images/pdf.gif"/></a>';
		$the_array['OPTIONS'] = $op;

		$a = new EcmSale();
		$a->retrieve($this->so_id);
		$the_array['ZS_NO'] = "<a  target='_blank'  href='index.php?module=EcmSales&action=DetailView&record=$a->id'>" . $a->document_no . "</a>";

		$zap = $this->db->query("select id,document_no from ecmstockdocouts where id in ('" . implode("','", explode("@", $this->wz_id)) . "')");
		$array = [];
		while ($wz = $this->db->fetchByAssoc($zap)) {

			$array[] = "<a  target='_blank'  href='index.php?module=EcmStockDocOuts&action=DetailView&record=" . $wz['id'] . "'>" . $wz['document_no'] . "</a>";
		}


		$the_array['WZ_NO'] = implode(',', $array);
		//pp 30.10.2015
		$r = $this->db->query("select `settled` from `ecmtransactions` where `record_id`='$this->id' and deleted=0");
		$r = $this->db->fetchByAssoc($r);
		if ($r['settled'] == 1) {
			$the_array['SETTLED'] = '<font color="green">Zapłacona</font>';
		} elseif ($r['settled'] == 0) {
			$the_array['SETTLED'] = '<font color="red">Niezapłacona</font>';
		}
		if ($this->sended == '1') {
			$the_array['EMAIL'] = '<img src="themes/Sugar5/images/accept.png" width="12px">';
		} else {
			$the_array['EMAIL'] = '<img src="themes/Sugar5/images/cancel.png" width="12px" >';
		}

		//

		return $the_array;
	}
	function getPriceFromDocument($product)
	{
		$zap = $this->db->query("select quantity,price_netto,total_netto from ecminvoiceoutitems where id='" . $product . "'");
		$dane = $this->db->fetchByAssoc($zap);
		return $dane;
	}
	function getStatusMenuInfo($inJSON = true)
	{
		global $app_list_strings;
		$arr = array();
		foreach ($app_list_strings['ecminvoiceouts_status_dom'] as $key => $value) {
			$arr[$key] = array(
				'enabled' => '<div><img src="modules/EcmInvoiceOuts/images/' . $key . '.gif" />' . $value . '</div>',
				'disabled' => '<div><img src="modules/EcmInvoiceOuts/images/' . $key . '.gif" />' . $value . '</div>'
			);
		}
		$json = getJSONobj();
		if ($inJSON)
			return str_replace('&quot;', '\"', $json->encode($arr));
		else
			return $arr;
	}
	function create_new_list_query($order_by, $where, $filter = array(), $params = array(), $show_deleted = 0, $join_type = '', $return_array = false, $parentbean = null, $singleSelect = false)
	{
		echo '<script type="text/javascript" src="include/ECM/EcmPreviewPDF/EcmPreviewPDF.js"></script>';
		echo '<script language="javascript"> var EcmInvoiceOutsStatusMenu = ' . $this->getStatusMenuInfo() . '; </script>';
		return parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect);
	}
	static function CreateImgStatus($id, $status)
	{
		global $app_list_strings;
		return '<span id="statusListEcmInvoiceOut_' . $id . '" style="display:inline;"><img src="modules/EcmInvoiceOuts/images/' . $status . '.gif" title="' . $app_list_strings['ecminvoiceouts_status_dom'][$status] . '" /></span>';
	}

	/**
	 * BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR.
	 * DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED.
	 */
	function build_generic_where_clause($the_query_string)
	{
		$where_clauses = array();
		$the_query_string = PearDatabase::quote(from_html($the_query_string));
		array_push($where_clauses, "ecminvoiceouts.name like '$the_query_string%'");
		$the_where = "";
		foreach ($where_clauses as $clause) {
			if ($the_where != "")
				$the_where .= " or ";
			$the_where .= $clause;
		}
		return $the_where;
	}
	function set_notification_body($xtpl, $simplemodule)
	{
		global $mod_strings, $app_list_strings;
		$xtpl->assign("NAME", $simplemodule->name);
		$xtpl->assign("DESCRIPTION", $simplemodule->description);
		return $xtpl;
	}
	function bean_implements($interface)
	{
		switch ($interface) {
			case 'ACL':
				return true;
		}
		return false;
	}
	function save($check_notify = FALSE)
	{
		// add mz 2015-03-13
		if ($this->type == 'correct') {
			$_REQUEST['is_correct'] = 'true';
		}
		global $current_user;

		//add mz 
		//get number format 2015-04-23
		require_once('modules/EcmSysInfos/EcmSysInfo.php');
		$EcmSysInfo = new EcmSysInfo();
		$template = $EcmSysInfo->getFormatNumberForModule('EcmInvoiceOuts');

		$current_id = $this->id;

		if (! $this->id || $this->id == '') {
			// generate number
			if ($template != "") {
				require_once('include/ECM/EcmDocumentNumberGenerator/EcmDocumentNumberGenerator.inc.php');
				$dng = new EcmDocumentNumberGenerator('EcmInvoiceOuts', $this->register_date);
				$this->document_no =  $dng->parseNormalNumber($template, $this->stock_id);
			}
			if ($this->paid_val == '')
				$this->paid_val = 0;
		}
		if ($_REQUEST['is_correct'] != '') {


			if ($_REQUEST['correctEdit'] != "true") {
				if ($template != "") {

					require_once('include/ECM/EcmDocumentNumberGenerator/EcmDocumentNumberGenerator.inc.php');
					$dng = new EcmDocumentNumberGenerator('EcmInvoiceOuts', $this->register_date, $EcmSysInfo->getDatabaseName());
					$this->document_no =   $dng->parseCorrectNumber($template, $this->stock_id);
				}
				$this->ecminvoiceout_id = $this->id;
				$r = $this->db->query("select document_no from ecminvoiceouts where id='" . $this->id . "'");
				$w = $this->db->fetchByAssoc($r);
				$this->ecminvoiceout_name = $w['document_no'];
				$this->id = null;
			}
		}
		unset($EcmSysInfo);

		if ($this->type == 'normal') $this->operation_type = '';
		$this->vats_summary = $this->vats_summary;
		$db = $this->db;
		$aa = explode('/', $this->document_no);
		$this->document_autoincrement = date("Ymd", strtotime($this->register_date)) . '' . sprintf('%04d', (string)((int)$aa[0]));

		$return_id = parent::save($check_notify);

		if ($current_id == '') {
			if ($this->type == 'normal')
				$this->savePositions($return_id);

			$total_brutto = $this->calculateTotals($return_id);

			$this->updatePurchasePrice($return_id);
		} else {
			if ($_REQUEST['is_correct'] != '') {

				if ($this->type == 'correct') {
					$this->saveCorrectPositions($return_id);

					$total_brutto = $this->calculateCorrectTotals($return_id);
					$this->updatePurchasePrice($return_id);
				}
			} else {
				$this->db->query("delete from ecminvoiceout_pdf where id='" . $return_id . "'");

				$this->savePositions($return_id, '', true);

				$total_brutto = $this->calculateTotals($return_id);
			}
		}



		$res_count = $this->db->query("select id from ecmtransactions where record_id='" . $return_id . "' and deleted='0'");

		$count = $res_count->num_rows;

		if ($count == 0) {
			$this->saveTransaction($return_id, $total_brutto);
		} else {
			$z = $this->db->query("select r.id from ecmtransactions_rel r
inner join ecmtransactions t on (t.id = r.ecmtransaction_a_id or t.id=r.ecmtransaction_b_id)
where t.record_id='" . $return_id . "'");
			while ($rett = $this->db->fetchByAssoc($z)) {
				if ($rett['id'] != '') {
					$this->db->query("delete from ecmtransactions_rel where id='" . $rett['id'] . "'");
				}
			}
			if ($this->parent_payer_nip != "") {
				$a = new Account();
				$a->retrieve_by_string_fields(['to_vatid' => $this->parent_payer_nip]);
				$this->db->query("update ecmtransactions set value='" . $total_brutto . "',settled=0,payment_date='" . date('Y-m-d', strtotime($this->payment_date)) . "',parent_id='" . $a->id . "',parent_name='" . $a->name . "' where record_id='" . $return_id . "'");
			} else {
				$this->db->query("update ecmtransactions set value='" . $total_brutto . "',settled=0,payment_date='" . date('Y-m-d', strtotime($this->payment_date)) . "',parent_id='" . $this->parent_id . "',parent_name='" . $this->parent_name . "' where record_id='" . $return_id . "'");
			}
		}

		if ($this->so_id != '') {
			$this->comparePositionList();
		}

		/*
		if($this->stock_id!=''){
		    require_once 'modules/EcmStockDocCorrects/correctToKs.php';
		    $t=new correctToKs($this->id);
		     
		} */

		return $return_id;
	}

	function updatePurchasePrice($return_id)
	{
		$GLOBALS['db']->query("update ecminvoiceouts set purchase_price=(select round(sum(quantity*price_purchase),2) as sum from ecminvoiceoutitems
	    where  ecminvoiceout_id='" . $return_id . "') where id='" . $return_id . "'");
	}

	function saveTransaction($id, $total_brutto)
	{
		global $current_user;

		if ($this->parent_payer_nip != "") {
			$a = new Account();
			$a->retrieve_by_string_fields(['to_vatid' => $this->parent_payer_nip]);
			$t = new EcmTransaction();
			$t->name = 'Faktura ' . $this->document_no;
			$t->record_type = 'EcmInvoiceOuts';
			$t->record_id = $id;
			$t->created_by = $current_user->id;
			$t->deleted = 0;
			$t->type3 = '2';
			$t->assigned_user_id = $this->assigned_user_id;
			$t->parent_name = $a->name;
			$t->parent_id = $a->id;
			$t->payment_date = $this->payment_date;
			$t->type = 0;
			$t->register_date = $this->register_date;
			$t->currency_id = $this->currency_id;
			$t->currency_value = $this->currency_value;
			$t->value = $total_brutto;
			$t->save(true);
		} else {
			$t = new EcmTransaction();
			$t->name = 'Faktura ' . $this->document_no;
			$t->record_type = 'EcmInvoiceOuts';
			$t->record_id = $id;
			$t->created_by = $current_user->id;
			$t->deleted = 0;
			$t->assigned_user_id = $this->assigned_user_id;
			$t->parent_name = $this->parent_name;
			$t->parent_id = $this->parent_id;
			$t->payment_date = $this->payment_date;
			$t->type = 0;
			$t->type3 = '2';
			$t->register_date = $this->register_date;
			$t->currency_id = $this->currency_id;
			$t->currency_value = $this->currency_value;
			$t->value = $total_brutto;
			$t->save(true);
		}
	}
	function calculateCorrectTotals($id)
	{
		$vats_summary = '';
		$total_netto = 0;
		$total_brutto = 0;
		$total_vat = 0;
		$vats = array();
		$res = $GLOBALS['db']->query("select
	total_netto,ecmvat_id,ecmvat_value,ecmvat_name
 from ecminvoiceoutitems n
where
    n.ecminvoiceout_id = '" . $id . "'");
		while ($cc = $GLOBALS['db']->fetchByAssoc($res)) {
			$vats[$cc['ecmvat_id']]['jest']['total_netto'] += $cc['total_netto'];
			$vats[$cc['ecmvat_id']]['ecmvat_value'] = $cc['ecmvat_value'];
			$vats[$cc['ecmvat_id']]['ecmvat_name'] = $cc['ecmvat_name'];
		}
		$res = $GLOBALS['db']->query(" select
	n.total_netto,n.ecmvat_id,n.ecmvat_value,n.ecmvat_name
 from ecminvoiceoutitems n
inner join ecminvoiceoutitems o on o.old_ecminvoiceoutitem_id=n.id
where
    o.ecminvoiceout_id = '" . $id . "'");

		while ($cc = $GLOBALS['db']->fetchByAssoc($res)) {
			$vats[$cc['ecmvat_id']]['bylo']['total_netto'] += $cc['total_netto'];
			$vats[$cc['ecmvat_id']]['ecmvat_value'] = $cc['ecmvat_value'];
			$vats[$cc['ecmvat_id']]['ecmvat_name'] = $cc['ecmvat_name'];
		}
		$vats_now = array();

		foreach ($vats as $key => $val) {
			if ($vats[$key]['jest']['total_netto'] == '') {
				$vats[$key]['jest']['total_netto'] = 0;
			}
			if ($vats[$key]['bylo']['total_netto'] == '') {
				$vats[$key]['bylo']['total_netto'] = 0;
			}
			$total_netto += $vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto'];
			$total_vat += (($vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto']) * $vats[$key]['ecmvat_value']) / 100;
			$total_brutto += ((($vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto']) * $vats[$key]['ecmvat_value']) / 100) + ($vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto']);
			$vats_summary .= $vats[$key]['ecmvat_name'] . ':' . round($vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto'], 2)
				. ':' . round((($vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto']) * $vats[$key]['ecmvat_value']) / 100, 2) . ':'
				. round(((($vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto']) * $vats[$key]['ecmvat_value']) / 100) + ($vats[$key]['jest']['total_netto'] - $vats[$key]['bylo']['total_netto']), 2) . ',';
		}
		$res = $GLOBALS['db']->query("update ecminvoiceouts set vats_summary='" . $vats_summary . "',total_netto='" . round($total_netto, 2) . "',total_vat='" . round($total_vat, 2) . "',
	           total_brutto='" . round($total_brutto, 2) . "' where id='" . $id . "'");
		return round($total_brutto, 2);
	}
	function calculateTotals($id)
	{
		$vats_summary = '';
		$total_netto = 0;
		$total_brutto = 0;
		$total_vat = 0;
		if (gettype($GLOBALS['superGlobalDb']) == 'object') {
			$db = $GLOBALS['superGlobalDb'];
		} else {
			$db = $GLOBALS['db'];
		}
		$res = $db->query("select ROUND(sum(total_netto),2) AS total_netto,ROUND(sum((total_netto*ecmvat_value)/100),2) AS total_vat,
ROUND(sum(((total_netto*ecmvat_value)/100)+total_netto),2) AS total_brutto,ecmvat_value,ecmvat_name
from ecminvoiceoutitems where ecminvoiceout_id='" . $id . "' group by ecmvat_id");
		while ($cc = $db->fetchByAssoc($res)) {
			$total_netto += $cc['total_netto'];
			$total_brutto += $cc['total_brutto'];
			$total_vat += $cc['total_vat'];
			if ($cc['ecmvat_name'] == 'OO') {
				$cc['ecmvat_value'] = $cc['ecmvat_name'];
			} else {
				$cc['ecmvat_value'] = $cc['ecmvat_name'];
			}
			$vats_summary .= $cc['ecmvat_value'] . ':' . $cc['total_netto'] . ':' . $cc['total_vat'] . ':' . $cc['total_brutto'] . ',';
		}
		$res = $db->query("update ecminvoiceouts set vats_summary='" . $vats_summary . "',total_netto='" . $total_netto . "',total_vat='" . $total_vat . "',
	           total_brutto='" . $total_brutto . "' where id='" . $id . "'");
		return $total_brutto;
	}

	// ***************************Start Managing Positions*************************//
	function constructInsertQuery($data, $table = '')
	{
		if ($table == '' && isset($this->object_name) && $this->object_name != '') {
			$table = strtolower($this->object_name) . "items";
		} else
			return "";
		$keys = array();
		$values = array();
		foreach ($data as $key => $value) {
			$keys[] = $key;
			if (is_array($value))
				$values[] = $value[1] . str_replace("'", "\'", $value[0]) . $value[1];
			else
				$values[] = "'" . str_replace("'", "\'", $value) . "'";
		}
		$q = "insert into `$table` (`";
		$q .= implode('`, `', $keys);
		$q .= "`) values (";
		$q .= implode(", ", $values);
		$q .= ");";
		return $q;
	}
	function savePositions($id = null, $position_list = null, $edit = false)
	{
		global $current_user, $timedate;
		if ($position_list == null)
			$position_list = $this->position_list;
		if ($id == null)
			$id = $this->id;
		if (count($position_list) > 0)
			$this->deleteAssignedPositions($id);
		$arr = array();
		$position = 0;
		$counter = 0;

		if ($this->wz_id != "") {
			$cenaz = $this->db->query("select * from ecmstockdocoutitems where ecmstockdocout_id='" . $this->wz_id . "' order by position asc");
			$ceny = [];
			while ($cenyz = $this->db->fetchByAssoc($cenaz)) {
				$ceny[] = $cenyz['price'];
			}


			foreach ($position_list as $key => $pos) {

				$position_list[$key]['price_purchase'] = round($ceny[$key], 2);
			}
		}
		for ($i = 0; $i < count($position_list); $i++) {
			if ($position_list[$i]['name'] == '')
				continue;
			$p = $position_list[$i];
			if (! empty($p['category_id']) || $p['category_id'] == '') {
				require_once("modules/EcmProducts/EcmProduct.php");
				$pr = new EcmProduct();
				$pr->retrieve($p['id']);
				$p['category_id'] = $pr->product_category_id;
			}

			$item_id = create_guid();
			$arr = array(
				'id' => $item_id,
				'date_entered' => array(
					'NOW()',
					''
				),
				'date_modified' => array(
					'NOW()',
					''
				),
				'modified_user_id' => $current_user->id,
				'assigned_user_id' => $current_user->id,
				'created_by' => $current_user->id,
				'deleted' => '0',
				strtolower($this->object_name) . '_id' => $id,
				'ecmproduct_id' => $p['product_id'],
				'position' => $position,
				'code' => $p['product_code'],
				'name' => $p['name'],
				'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
				'price_start' => ((empty($p['price_start']) || $p['price_start'] == '') ? 0 : $p['price_start']),
				'price_netto' => ((empty($p['price_netto']) || $p['price_netto'] == '') ? 0 : $p['price_netto']),
				'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
				'total_netto' => ((empty($p['total_netto']) || $p['total_netto'] == '') ? 0 : $p['total_netto']),
				'total_brutto' => ((empty($p['total_brutto']) || $p['total_brutto'] == '') ? ($p['total_netto'] * ($p['ecmvat_value'] / 100)) + $p['total_netto'] : $p['total_brutto']),
				'total_vat' => ((empty($p['total_vat']) || $p['total_vat'] == '') ? ($p['total_netto'] * ($p['ecmvat_value'] / 100)) : $p['total_vat']),
				'price_brutto' => ((empty($p['price_brutto']) || $p['price_brutto'] == '') ? ($p['price_netto'] * ($p['ecmvat_value'] / 100)) + $p['price_netto'] : $p['price_brutto']),
				'dd_unit_id' => $p['unit_id'],
				'dd_unit_name' => $p['unit_name'],
				'ecmvat_id' => $p['ecmvat_id'],
				'ecmvat_name' => $p['ecmvat_name'],
				'ecmvat_value' => $p['ecmvat_value'],
				'parent_doc_id' => $p['product_parent_doc_id'],
				'parent_doc_type' => $p['product_parent_doc_type'],
				'parent_doc_item_id' => $p['product_parent_doc_item_id'],
				'ecmproductcategory_id' => $p['category_id'],
				'product_consignment_id' => $p['product_consignment_id'],
				'recipient_code' => $p['recipient_code'],
				'price_purchase' => $p['price_purchase'],
			);

			$this->db->query($this->constructInsertQuery($arr));
			if ($edit == false) {


				if ($this->stock_id != '' && $this->wz_id == '' && $pr->ks_group != '3') {
					if (! $p['product_consignment_id'] || $p['product_consignment_id'] == "")
						$this->addProducts($arr, $id, $item_id);
					else
						$this->deleteProductsFromStockWithConsignment($arr, $id, $item_id);
				}
			}
			$position++;
		}
	}


	function saveCorrectPositions($id = null, $position_list = null)
	{

		global $current_user, $timedate;
		if ($position_list == null)
			$position_list = $this->position_list;
		if ($id == null)
			$id = $this->id;
		if (count($position_list) > 0)
			$this->deleteAssignedPositions($id);
		$arr = array();
		$position = 0;
		$counter = 0;
		for ($i = 0; $i < count($position_list); $i++) {
			if ($position_list[$i]['name'] == '')
				continue;
			$p = $position_list[$i];
			if (! empty($p['category_id']) || $p['category_id'] == '') {
				require_once("modules/EcmProducts/EcmProduct.php");
				$pr = new EcmProduct();
				$pr->retrieve($p['id']);
				$p['category_id'] = $pr->product_category_id;
			}

			//  $GLOBALS['db']->query("INSERT INTO log VALUES ('".serialize($position_list[$i]['product_itemold_id'])."')");
			if ($p['product_corrected'] == "true")
				continue;

			//take it clear
			if (
				$position_list[$i]['quantity'] == $position_list[$i + 1]['quantity']
				&& $position_list[$i]['price_start'] == $position_list[$i + 1]['price_start']
				&& $position_list[$i]['price_netto'] == $position_list[$i + 1]['price_netto'] && $position_list[$i]['total_vat'] == $position_list[$i + 1]['total_vat']
			)
				continue;
			$item_id = create_guid();
			$arr = array(
				'id' => $item_id,
				'date_entered' => array(
					'NOW()',
					''
				),
				'date_modified' => array(
					'NOW()',
					''
				),
				'modified_user_id' => $current_user->id,
				'assigned_user_id' => $current_user->id,
				'created_by' => $current_user->id,
				'deleted' => '0',
				strtolower($this->object_name) . '_id' => $id,
				'ecmproduct_id' => $p['product_id'],
				'position' => $counter,
				'code' => $p['product_code'],
				'name' => $p['name'],
				'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
				'price_start' => ((empty($p['price_start']) || $p['price_start'] == '') ? 0 : $p['price_start']),
				'price_netto' => ((empty($p['price_netto']) || $p['price_netto'] == '') ? 0 : $p['price_netto']),
				'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
				'total_netto' => ((empty($p['total_netto']) || $p['total_netto'] == '') ? 0 : $p['total_netto']),
				'total_brutto' => ((empty($p['total_brutto']) || $p['total_brutto'] == '') ? 0 : $p['total_brutto']),
				'total_vat' => ((empty($p['total_vat']) || $p['total_vat'] == '') ? 0 : $p['total_vat']),
				'price_brutto' => ((empty($p['price_brutto']) || $p['price_brutto'] == '') ? 0 : $p['price_brutto']),
				'dd_unit_id' => $p['unit_id'],
				'dd_unit_name' => $p['unit_name'],
				'ecmvat_id' => $p['ecmvat_id'],
				'ecmvat_name' => $p['ecmvat_name'],
				'ecmvat_value' => $p['ecmvat_value'],
				'ecmproductcategory_id' => $p['category_id'],
				'recipient_code' => $p['recipient_code'],
				'ecminvoiceoutitem_id' => $p['product_item_id'],
				'old_ecminvoiceoutitem_id' => $p['product_itemold_id'],
				'old_total_netto' => $position_list[$i + 1]['total_netto'],
				'old_total_vat' => $position_list[$i + 1]['total_vat'],
				'old_total_brutto' => $position_list[$i + 1]['total_brutto'],
				'old_quantity' => $position_list[$i + 1]['quantity'],
				'product_consignment_id' => $p['product_consignment_id'],
				'parent_doc_id' => $p['product_parent_doc_id'],
				'parent_doc_type' => $p['product_parent_doc_type'],
				'parent_doc_item_id' => $p['product_parent_doc_item_id'],
				'quantity_corrected' => round(floatval($position_list[$i]['quantity']) - floatval($position_list[$i + 1]['quantity']), 2),
				'total_netto_corrected' => round(floatval($position_list[$i]['total_netto']) - floatval($position_list[$i + 1]['total_netto']), 2),
				'total_brutto_corrected' => round(floatval($position_list[$i]['total_brutto']) - floatval($position_list[$i + 1]['total_brutto']), 2),
			);
			$this->db->query($this->constructInsertQuery($arr));
			// mz@bim-it.pl 11.04.2024
			// disable stock operations
			//if($arr['quantity_corrected']<0){
			//	$this->insertProductsToStock ( $p, $id, $this->stock_id, $item_id,$arr['quantity_corrected']);
			//}
			// end mz
			$counter++;
		}
	}

	function insertProductsToStock($pl, $return_id, $stock_id, $itemid, $quantity)
	{
		require_once("modules/EcmStockOperations/EcmStockOperation.php");
		$o = new EcmStockOperation();
		global $app_list_strings;
		require_once("modules/EcmProducts/EcmProduct.php");
		$o->product_id = $pl['product_id'];
		$p = new EcmProduct();
		$p->retrieve($pl['product_id']);
		$o->product_code = $p->code;
		$o->product_name = $p->name;

		require_once("modules/EcmStocks/EcmStock.php");
		$o->stock_id = $stock_id;
		$s = new EcmStock();
		$s->retrieve($stock_id);
		$o->stock_name = $s->name;

		$o->parent_id = $return_id;

		$o->parent_name = $this->document_no;
		$o->parent_type = "EcmInvoiceOuts";

		//consignment
		if ($pl['product_consignment_id'] != '') {
			$o->part_no = $pl['product_consignment_part'];

			$query = "select price from ecmstockoperations where product_id='" . $pl['product_id'] . "' and id='" . $pl['product_consignment_id'] . "'";

			$zzz = $GLOBALS['db']->query($query);
			$price = $GLOBALS['db']->fetchByAssoc($zzz);
		} else {
			$cinv = new EcmInvoiceOut();
			$cinv->retrieve($this->ecminvoiceout_id);

			if ($cinv->wz_id == '') {
				$query = "select (sum(price*quantity)/(sum(quantity))) as price from ecmstockoperations where parent_id='" . $this->ecminvoiceout_id . "' and product_id='" . $pl['product_id'] . "'";
			} else {

				if (strpos($cinv->wz_id, '@') > -1) {
					$query = "select (sum(price*quantity)/(sum(quantity))) as price from ecmstockoperations where product_id='" . $pl['product_id'] . "' and parent_id in('" . implode("','", explode("@", $cinv->wz_id)) . "')";
				} else {
					$query = "select (sum(price*quantity)/(sum(quantity))) as price from ecmstockoperations where product_id='" . $pl['product_id'] . "' and parent_id in('" . $cinv->wz_id . "')";
				}
			}

			$zzz = $GLOBALS['db']->query($query);
			$price = $GLOBALS['db']->fetchByAssoc($zzz);
		}
		$o->quantity = abs($quantity);

		$o->price = $price['price'];
		$GLOBALS['db']->query("update ecminvoiceoutitems set price_purchase='" . $price['price'] . "' where id='" . $itemid . "'");
		$o->documentitem_id = $itemid;
		$o->type = 0;
		$oid = $o->save();
		$GLOBALS['db']->query("update ecmstockoperations set price='" . $price['price'] . "' where id='" . $oid . "'");

		require_once("modules/EcmStockStates/EcmStockState.php");
		$ss = new EcmStockState();
		$ss->UpdateStockState($o->stock_id, $o->product_id);
	}

	function getPosition($position, $createCorrect = "false", $correctedItem = false)
	{
		if (! is_array($position))
			return '';
		global $timedate, $app_list_strings;
		$n = new EcmProduct();
		$n->retrieve($position['ecmproduct_id']);
		$return_array = array();
		$rec = $this->db->query("select recipient_code from ecmsaleitems where ecmsale_id='" . $this->so_id . "' and deleted=0 and ecmproduct_id='" . $position['ecmproduct_id'] . "'");
		$dd = $this->db->fetchByAssoc($rec);

		$return_array['recipient_code'] = $dd['recipient_code'];
		$return_array['product_record_id'] = $position['id'];
		$return_array['product_id'] = $position['ecmproduct_id'];
		$return_array['position'] = $position['position'];
		$return_array['product_code'] = $position['code'];
		$return_array['name'] = $position['name'];
		$return_array['quantity'] = $position['quantity'];
		$return_array['price_start'] = $position['price_start'];
		$return_array['price_netto'] = $position['price_netto'];
		$return_array['discount'] = $position['discount'];
		$return_array['total_netto'] = $position['total_netto'];
		$return_array['product_category_id'] = $n->product_category_id;
		$return_array['product_ks_group'] = $n->ks_group;
		$return_array['unit_id'] = $position['dd_unit_id'];
		$return_array['unit_name'] = $position['dd_unit_name'];
		$return_array['ecmvat_id'] = $position['ecmvat_id'];
		$return_array['ecmvat_name'] = $position['ecmvat_name'];
		$return_array['ecmvat_value'] = $position['ecmvat_value'];
		$return_array['real_vat_id'] = $n->vat_id;
		$return_array['real_vat_name'] = $n->vat_name;
		$return_array['real_vat_value'] = $n->vat_value;

		$return_array['remarks'] = $position['remarks'];
		$return_array['old_ecminvoiceoutitem_id'] = $position['old_ecminvoiceoutitem_id'];
		$return_array['old_total_netto'] = $position['old_total_netto'];
		$return_array['old_total_brutto'] = $position['old_total_brutto'];
		$return_array['old_quantity'] = $position['old_quantity'];
		$return_array['old_total_vat'] = $position['old_total_vat'];
		$return_array['ecminvoiceoutitem_id'] = $position['ecminvoiceoutitem_id'];
		$return_array['total_vat'] = $position['total_vat'];
		$return_array['total_brutto'] = $position['total_brutto'];
		$return_array['price_purchase'] = $position['price_purchase'];

		$return_array['unit_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$position['dd_unit_id']];
		$return_array['product_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$position['dd_unit_id']];


		/* pobieram informacje o partii z operacji magazynowych 
	     */
		$part = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select id,quantity,part_no,in_id from ecmstockoperations where documentitem_id='" . ($position['parent_doc_item_id'] == '' ? $position['id'] : $position['parent_doc_item_id']) . "'"));
		$return_array['product_consignment_id'] = $part['in_id'];
		$return_array['product_consignment_part'] = $part['part_no'];
		unset($n);
		//TODO zrobić save do bazy!
		if ($position['old_ecminvoiceoutitem_id'] && $position['old_ecminvoiceoutitem_id']) {
			$tmp = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT price_netto FROM ecminvoiceoutitems WHERE id = '" . $position['old_ecminvoiceoutitem_id'] . "'"));
			$return_array['old_price_netto'] = $tmp['price_netto'];
		}


		if ($createCorrect == "true") {
			if ($position['old_ecminvoiceoutitem_id'] != "") {
				$return_array['product_item_id'] = $position['old_ecminvoiceoutitem_id'];
			} else {
				$return_array['product_item_id'] = $position['id'];
			}


			if ($correctedItem == "true")
				$return_array['product_corrected'] = "true";
			else
				$return_array['product_corrected'] = "false";

			// get values from previous corrects
			if ($position['old_ecminvoiceoutitem_id'] != "" && $correctedItem == "true") {
				$cc = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT ii.id,ii.price_start, ii.price_netto, ii.quantity, ii.discount,
						ii.ecmvat_value, ii.ecmvat_id, ii.ecmvat_name FROM ecminvoiceoutitems as ii
						 INNER JOIN ecminvoiceouts AS i ON i.id=ii.ecminvoiceout_id WHERE i.canceled ='0' and i.deleted='0' and ii.id='" . $position['old_ecminvoiceoutitem_id'] . "' ORDER BY ii.date_entered DESC LIMIT 0,1"));
			} else {
				$cc = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT ii.id,ii.price_start, ii.price_netto, ii.quantity, ii.discount,
						ii.ecmvat_value, ii.ecmvat_id, ii.ecmvat_name FROM ecminvoiceoutitems as ii
						 INNER JOIN ecminvoiceouts AS i ON i.id=ii.ecminvoiceout_id WHERE i.canceled ='0' and i.deleted='0' and ii.ecminvoiceoutitem_id='" . $position['id'] . "' ORDER BY ii.date_entered DESC LIMIT 0,1"));
			}

			if ($cc['price_netto']) {
				$return_array['price_start'] = $cc['price_start'];
				$return_array['price_netto'] = $cc['price_netto'];
				$return_array['quantity'] = $cc['quantity'];
				$return_array['discount'] = $cc['discount'];
				$return_array['ecmvat_value'] = $cc['ecmvat_value'];
				$return_array['ecmvat_id'] = $cc['ecmvat_id'];
				$return_array['ecmvat_name'] = $cc['ecmvat_name'];
				$return_array['product_itemold_id'] = $cc['id'];
			} else {
				if ($position['old_ecminvoiceoutitem_id'] != "") {
					$return_array['product_itemold_id'] = $position['old_ecminvoiceoutitem_id'];
				} else {
					$return_array['product_itemold_id'] = $position['id'];
				}
			}
		} else {
			$return_array['product_item_id'] = $position['ecminvoiceoutitem_id'];
		}
		return $return_array;
	}

	function getPositionList($array = false, $isCorrect = "false")
	{
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM `" . strtolower($this->object_name) . "items` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "' order by position asc";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					$return_array[] = $this->getPosition($w, $isCorrect, "false");
					if ($isCorrect == "true") {
						$return_array[] = $this->getPosition($w, $isCorrect, "true");
					}
				}
				$json = getJSONobj();
				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}
	function deleteProductsFromStockWithConsignment($p, $id, $itemid)
	{
		$db = $GLOBALS['db'];
		$in_p = $db->fetchByAssoc($db->query("SELECT price FROM ecmstockoperations WHERE id = '" . $p['product_consignment_id'] . "'"));
		$this->addProductToStockOut($p['product_consignment_id'], $p['ecmproduct_id'], $p['quantity'], $in_p['price'], $this->register_date, $id, $this->stock_id, $itemid, $p['product_consignment_part'], $p['dd_unit_id']);
		$db->query("update ecminvoiceoutitems set price_purchase='" . $in_p['price'] . "' where id='" . $itemid . "'");
	}

	function addProducts($p, $id, $itemid)
	{
		$arr = array();
		$w = $GLOBALS['db']->query("select quantity as qty,id,price from ecmstockoperations where deleted='0' and type='0' and in_id IS NULL and stock_id='" . $this->stock_id . "' and product_id='" . $p['ecmproduct_id'] . "' and used='0'  ORDER BY counter ASC");
		while ($rrr = $GLOBALS['db']->fetchByAssoc($w)) {
			$ww = $GLOBALS['db']->query("select quantity from ecmstockoperations where in_id='" . $rrr['id'] . "' and type='1' and in_id IS NOT NULL and stock_id='" . $this->stock_id . "' and product_id='" . $p['ecmproduct_id'] . "' and deleted='0'  ORDER BY counter ASC");
			$rqty = 0;
			while ($rrp = $GLOBALS['db']->fetchByAssoc($ww)) {
				$rqty += $rrp['quantity'];
			}
			$qty = $rrr['qty'] - $rqty;
			if ($qty > 0) {
				$arr[] = array("qty" => $qty, "id" => $rrr['id'], "price" => $rrr['price']);
			}
		}
		$rr = array();
		$used_qty = 0;
		$stop = 0;
		foreach ($arr as $value) {
			if ($p['quantity'] - $used_qty <= $value['qty']) {
				$rr[] = array("id" => $value['id'], "qty" => $p['quantity'] - $used_qty, "price" => $value['price']);
				$stop = 1;
			} else {
				$rr[] = array("id" => $value['id'], "qty" => $value['qty'], "price" => $value['price']);
				$used_qty += $value['qty'];
			}
			if ($stop) {
				$stop = 0;
				break;
			}
		}
		$avg_pq = 0;
		$avg_q = 0;
		foreach ($rr as $r) {
			$this->addProductToStockOut($r['id'], $p['ecmproduct_id'], $r['qty'], $r['price'], $this->register_date, $id, $this->stock_id, $itemid, null, $p['dd_unit_id']);
			$avg_pq += $r['qty'] * $r['price'];
			$avg_q += $r['qty'];
		}
		$GLOBALS['db']->query("update ecminvoiceoutitems set price_purchase='" . ($avg_pq / $avg_q) . "' where id='" . $itemid . "'");
	}
	function addProductToStockOut($stock_in_id, $product_id, $quantity, $price, $date, $mm_id, $stock_id, $itemid, $part_no, $unit_id)
	{
		global $app_list_strings;
		require_once("modules/EcmStockOperations/EcmStockOperation.php");
		$o = new EcmStockOperation();
		$o->unformat_all_fields();

		require_once("modules/EcmProducts/EcmProduct.php");
		$o->product_id = $product_id;
		$p = new EcmProduct();
		$p->retrieve($product_id);
		$o->product_code = $p->code;
		$o->product_name = $p->name;

		require_once("modules/EcmStocks/EcmStock.php");
		$o->stock_id = $stock_id;
		$s = new EcmStock();
		$s->retrieve($stock_id);
		$o->stock_name = $s->name;

		$o->parent_id = $this->id;
		$o->parent_name = $this->document_no;
		$o->parent_type = "EcmInvoiceOuts";

		if ($part_no)
			$o->part_no = $part_no;

		$o->quantity = round($quantity, $app_list_strings['ecmproducts_unit_dom_precision'][$unit_id]);
		$o->price = $price;
		$o->in_id = $stock_in_id;
		$o->documentitem_id = $itemid;
		$o->type = 1;
		$oid = $o->save();
		$GLOBALS['db']->query("update ecmstockoperations set price='" . $price . "' where id='" . $oid . "'");

		require_once("modules/EcmStockStates/EcmStockState.php");
		$ss = new EcmStockState();
		$ss->UpdateStockState($o->stock_id, $o->product_id);
	}

	function deleteAssignedPositions()
	{
		if (isset($this->id) && $this->id != '') {
			$query = "DELETE FROM `" . strtolower($this->object_name) . "items` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "'";
			$r = $this->db->query($query);
			if ($r)
				return true;
		}
		return false;
	}
	function formatPositions($position_list)
	{
		return;
		if (! is_array($position_list) || count($position_list) == 0)
			return false;
		global $app_list_strings;
		require_once('modules/Currencies/Currency.php');
		foreach ($position_list as $key => $value) {
			$position_list[$key]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$value['unit_id']];
			$position_list[$key]['category_id'] = $app_list_strings['ecmproducts_category_dom'][$value['category_id']];
			// $position_list[$key]['vat_id'] = format_number($value['vat_id']).'%';
			$position_list[$key]['discount'] = format_number($value['discount']) . '%';
			if (isset($currency) && ($currency->id == $this->currency_id)) {
			} else {
				$currency = new Currency();
				$currency->retrieve($this->currency_id);
			}
			$position_list[$key]['price'] = format_number($value['price']) . ' ' . $currency->iso4217;
			$position_list[$key]['total'] = format_number($value['total']) . ' ' . $currency->iso4217;
			// $position_list[$key]['price'] = format_number($value['price']).' PLN';
			// $position_list[$key]['total'] = format_number($value['total']).' PLN';
			$this->currency_symbol = $currency->iso4217;
		}
		return $position_list;
	}

	function comparePositionList()
	{
		$query = "select sum(it.quantity) as quantity,it.ecmproduct_id as product_id from ecminvoiceoutitems it
	    left join ecminvoiceouts f on f.id=it.ecminvoiceout_id
	    where f.so_id='$this->so_id' group by it.ecmproduct_id";
		$r = $this->db->query($query);
		if ($r->num_rows > 0) {
			$used_array = array();
			while ($res = $this->db->fetchByAssoc($r)) {
				$used_array[] = $res;
			}
			$es = new EcmSale();
			$es->retrieve($this->so_id);
			$return_array = $es->getPositionList(true);
			// merge
			foreach ($return_array as $k => $v) {
				foreach ($used_array as $k2 => $v2) {
					if ($v['product_id'] == $v2['product_id']) {
						$return_array[$k]['quantity'] = $v['quantity'] - $v2['quantity'];
					}
				}
			}
			// remove used
			foreach ($return_array as $k => $v) {
				if ($v['quantity'] == 0) {
					unset($return_array[$k]);
				}
			}
			$es = new EcmSale();
			$es->retrieve($this->so_id);
			if ($es->type == 'sales_order') {
				if (count($return_array) == 0) {
					$this->db->query("update ecmsales set status='s90' where id='$this->so_id'");
				} else {
					$this->db->query("update ecmsales set status='s95' where id='$this->so_id'");
				}
			}
		}
	}

	// ***************************End Managing Positions*************************//
	function ACLAccess($view, $is_owner = 'not_set')
	{
		global $current_user;
		$file = 'modules/EcmGroupSales/EcmGroupSale.php';
		if (file_exists($file)) {
			require_once($file);
			$cc = EcmGroupSale::loadSettings(true);
		} else
			return true;
		if (is_admin($current_user)) {
			switch ($view) {
				case 'confirming':
					return ($this->status == "s20");
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}
			return true;
		}
		if ($is_owner == 'not_set') {
			$is_owner = $this->isOwner($current_user->id);
		}
		// if we don't implent acls return true
		if (! $this->bean_implements('ACL'))
			return true;
		$view = strtolower($view);
		if ($cc['user_manager_role']) { // Manager
			switch ($view) {
				case 'list':
				case 'index':
				case 'listview':
					return ACLController::checkAccess($this->module_dir, 'list', true);
				case 'edit':
				case 'save':
				case 'popupeditview':
				case 'editview':
					return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner));
				case 'view':
				case 'detail':
				case 'detailview':
					return ACLController::checkAccess($this->module_dir, 'view', $is_owner);
				case 'delete':
					return ACLController::checkAccess($this->module_dir, 'delete', $is_owner);
				case 'export':
					return ACLController::checkAccess($this->module_dir, 'export', $is_owner);
				case 'import':
					return ACLController::checkAccess($this->module_dir, 'import', true);
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'can_commit':
					return true;
				case 'confirming':
					return ($this->status == "s20");
				case 'auto_commiting':
					return true;
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}
		} else if ($cc['user_representative_extra_role']) { // Representative Extra
			switch ($view) {
				case 'list':
				case 'index':
				case 'listview':
					return ACLController::checkAccess($this->module_dir, 'list', true);
				case 'edit':
					return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
				case 'save':
				case 'popupeditview':
				case 'editview':
					return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner));
				case 'view':
				case 'detail':
				case 'detailview':
					return ACLController::checkAccess($this->module_dir, 'view', $is_owner);
				case 'delete':
					return (ACLController::checkAccess($this->module_dir, 'delete', $is_owner) && $this->status == "s10");
				case 'export':
					return ACLController::checkAccess($this->module_dir, 'export', $is_owner);
				case 'import':
					return ACLController::checkAccess($this->module_dir, 'import', true);
				case 'quote_to_sale':
				case 'quote_to_invoice':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'send_email':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
				case 'can_commit':
					return true;
				case 'confirming':
					return false;
				case 'auto_commiting':
					return true;
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}
		} else if ($cc['user_representative_role']) { // Representative
			switch ($view) {
				case 'list':
				case 'index':
				case 'listview':
					return ACLController::checkAccess($this->module_dir, 'list', true);
				case 'edit':
					return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
				case 'save':
				case 'popupeditview':
				case 'editview':
					return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner));
				case 'view':
				case 'detail':
				case 'detailview':
					return ACLController::checkAccess($this->module_dir, 'view', $is_owner);
				case 'delete':
					return (ACLController::checkAccess($this->module_dir, 'delete', $is_owner) && $this->status == "s10");
				case 'export':
					return ACLController::checkAccess($this->module_dir, 'export', $is_owner);
				case 'import':
					return ACLController::checkAccess($this->module_dir, 'import', true);
				case 'quote_to_sale':
				case 'quote_to_invoice':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'send_email':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
				case 'can_commit':
					return false;
				case 'confirming':
					return false;
				case 'auto_commiting':
					return false;
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}
		}
		// if it is not one of the above views then it should be implemented on the page level
		return true;
	}

	// mz generate number
	function generateNumber($stock_id, $date)
	{
		$db = $GLOBALS['db'];
		$r = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecminvoiceouts WHERE deleted='0' AND YEAR(register_date)='" . date('Y', strtotime($date)) . "' and type='normal' and stock_id='" . $stock_id . "'"));

		$a = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecminvoiceouts WHERE deleted='0' AND YEAR(register_date)='" . date('Y', strtotime($date)) . "' and type='normal' and stock_id='" . $stock_id . "' and document_no LIKE '%/a%'"))['c'];

		if (! $r || ! $r['c'] || $r['c'] == '')
			$count = 0;
		else
			$count = intval($r['c']);

		$count++;

		if ($a) {
			$count -= intval($a);
		}

		// has 5 digits?
		$tmp = strval($count);
		while (strlen($tmp) < 5)
			$tmp = '0' . $tmp;

		return date('Ymd', strtotime($date)) . $tmp;
	}
	function generateNumberCorrect()
	{
		$db = $GLOBALS['db'];
		$r = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecminvoiceouts WHERE deleted='0' AND YEAR(register_date)='" . date('Y') . "' and type='correct'"));

		if (! $r || ! $r['c'] || $r['c'] == '')
			$count = 0;
		else
			$count = intval($r['c']);

		$count++;

		// has 5 digits?
		$tmp = strval($count);
		while (strlen($tmp) < 5)
			$tmp = '0' . $tmp;

		return date("Ymd") . $tmp;
	}
	function formatNumber($number, $stock_id)
	{
		$db = $GLOBALS['db'];
		$st = $db->fetchByAssoc($db->query("select no from ecmstocks where id='" . $stock_id . "'"));
		$n = intval(substr($number, 8, 5));
		$y = substr($number, 0, 4);

		// has 3 digits?
		while (strlen($n) < 3)
			$n = '0' . $n;
		if ($st['no'] != '')
			return '' . $n . '/' . $st['no'] . '/' . $y;
		else
			return '' . $n . '/' . $y;
	}
	function formatNumberCorrect($number)
	{
		$n = intval(substr($number, 8, 5));
		$y = substr($number, 0, 4);

		// has 3 digits?
		while (strlen($n) < 3)
			$n = '0' . $n;

		return '' . $n . '/' . $y;
	}

	public static function getInvoiceList($where)
	{
		global $db, $current_user;
		//	var_dump($where);
		if (count($where['accounts']) > 0) {
			$query = "SELECT ecminvoiceouts.* FROM ecminvoiceouts,accounts WHERE (ecminvoiceouts.canceled=0 OR ecminvoiceouts.canceled IS NULL)
				AND (ecminvoiceouts.deleted=0 OR ecminvoiceouts.deleted IS NULL) AND ecminvoiceouts.parent_id=accounts.id and " . implode(" AND ", $where['ecminvoiceouts']) . ' and ' . implode(" AND ", $where['accounts']) . ' ORDER BY ecminvoiceouts.date_entered, ecminvoiceouts.register_date';
		} else {
			$query = "SELECT * FROM ecminvoiceouts WHERE (canceled=0 OR canceled IS NULL) AND (deleted=0 OR deleted IS NULL) AND " . implode(" AND ", $where['ecminvoiceouts']) . ' ORDER BY date_entered, register_date';
		}

		//	echo "<br>".$query . "<Br>";
		$result = $db->query($query);
		$returnArray = NULL;
		if ($result->num_rows > 0) {
			$returnArray = array();

			while ($row = $db->fetchByAssoc($result)) {
				$currency_value = 1;



				if ($row['currency_value_nbp'] != '') {
					$currency_value = $row['currency_value_nbp'];
				}
				/*
				if($row['currency_value']!= ''){
					$currency_value = $row['currency_value'];
				}
				*/



				$positionQuery = "SELECT 
				ecminvoiceoutitems.id as position_id, 
				ecminvoiceoutitems.name as position_name, 
				ecminvoiceoutitems.total_netto as position_total_netto, 
				ecminvoiceoutitems.total_brutto as position_total_brutto, 
				ecminvoiceoutitems.price_purchase as position_price_purchase,
				ecminvoiceoutitems.quantity as position_quantity,
				ecminvoiceoutitems.dd_unit_id as position_unit_id,
				ecminvoiceoutitems.dd_unit_name as position_unit_name,
				ecminvoiceoutitems.total_netto_corrected as position_total_netto_corrected,
				ecminvoiceoutitems.quantity_corrected as position_quantity_corrected,
				ecminvoiceoutitems.total_brutto_corrected as position_total_brutto_corrected,
				ecminvoiceoutitems.old_ecminvoiceoutitem_id as old_position_id,
				ecminvoiceoutitems.code as position_code,
						ecminvoiceoutitems.ecminvoiceout_id as ecminvoiceout_id,
				ecmproducts.id as product_id
				FROM ecminvoiceoutitems , ecmproducts 
				WHERE 
				ecminvoiceoutitems.ecminvoiceout_id='" . $row['id'] . "' 
				AND ecminvoiceoutitems.ecmproduct_id = ecmproducts.id  ";
				if (count($where['ecmproducts']) > 0) {
					$positionQuery .= ' AND ' . implode(" AND ", $where['ecmproducts']);
				}
				$positionQuery .=  " ORDER BY ecminvoiceoutitems.position ";
				$positionresult = $db->query($positionQuery);
				$positionArray = NULL;
				if ($positionresult->num_rows > 0) {
					$positionArray = array();
					while ($rowposition = $db->fetchByAssoc($positionresult)) {
						$tmprow = array();
						$tmprow['position_name'] = $rowposition['position_name'];
						$tmprow['position_id'] = $rowposition['position_id'];
						$tmprow['position_code'] = $rowposition['position_code'];

						if ($row['type'] == 'correct') {
							// Pobieram cene zakupu
							$purchase_price_query = "SELECT price_purchase FROM ecminvoiceoutitems WHERE id='" . $rowposition['old_position_id'] . "'";
							$r = $db->query($purchase_price_query);
							$rpurchase = $db->fetchByAssoc($r);
							$tmprow['position_total_price_purchase'] = round($rpurchase['price_purchase'] * $rowposition['position_quantity_corrected'], 2);
							$tmprow['position_total_netto'] = round($rowposition['position_total_netto_corrected'] * $currency_value, 2);
							$tmprow['position_total_brutto'] = round($rowposition['position_total_brutto_corrected'] * $currency_value, 2);
							$tmprow['position_quantity'] = $rowposition['position_quantity_corrected'];
						} else {
							$tmprow['position_total_netto'] = round($rowposition['position_total_netto'] * $currency_value, 2);
							$tmprow['position_total_brutto'] = round($rowposition['position_total_brutto'] * $currency_value, 2);
							$tmprow['position_total_price_purchase'] = round($rowposition['position_price_purchase'] * $rowposition['position_quantity'], 2);
							$tmprow['position_quantity'] = $rowposition['position_quantity'];
						}

						$tmprow['position_unit_id'] = $rowposition['position_unit_id'];
						$tmprow['position_unit_name'] = $rowposition['position_unit_name'];
						$tmprow['ecminvoiceout_id'] = $rowposition['ecminvoiceout_id'];
						$tmprow['product_id'] = $rowposition['product_id'];
						$positionArray[] = $tmprow;
					}






					// tu wklejam
					$currency_value = 1;
					if ($row['currency_value_nbp'] != '') {
						$currency_value = $row['currency_value_nbp'];
					}
					/*
					if($row['currency_value']!= ''){
						$currency_value = $row['currency_value'];
					}*/

					$positionQuery = "SELECT
				ecminvoiceoutitems.id as position_id,
				ecminvoiceoutitems.name as position_name,
				ecminvoiceoutitems.total_netto as position_total_netto,
				ecminvoiceoutitems.total_brutto as position_total_brutto,
				ecminvoiceoutitems.price_purchase as position_price_purchase,
				ecminvoiceoutitems.quantity as position_quantity,
				ecminvoiceoutitems.dd_unit_id as position_unit_id,
				ecminvoiceoutitems.dd_unit_name as position_unit_name,
								ecminvoiceoutitems.ecminvoiceout_id as ecminvoiceout_id,
				ecminvoiceoutitems.total_netto_corrected as position_total_netto_corrected,
				ecminvoiceoutitems.quantity_corrected as position_quantity_corrected,
				ecminvoiceoutitems.total_brutto_corrected as position_total_brutto_corrected,
				ecminvoiceoutitems.old_ecminvoiceoutitem_id as old_position_id,
				ecminvoiceoutitems.code as position_code,
				ecminvoiceoutitems.ecmproduct_id as product_id
				FROM ecminvoiceoutitems
				WHERE
				ecminvoiceoutitems.ecminvoiceout_id='" . $row['id'] . "'
				 ";
					if (count($where['ecmproducts']) > 0) {
						$positionQuery .= ' AND ' . implode(" AND ", $where['ecmproducts']);
					}
					$positionQuery .=  " ORDER BY ecminvoiceoutitems.position ";
					$positionresult = $db->query($positionQuery);

					if ($positionresult->num_rows > 0) {

						while ($rowposition = $db->fetchByAssoc($positionresult)) {
							$p = new EcmProduct();
							$p->retrieve($rowposition['product_id']);
							if ($p->id != '') continue;
							$tmprow = array();
							$tmprow['position_name'] = $rowposition['position_name'];
							$tmprow['position_id'] = $rowposition['position_id'];
							$tmprow['position_code'] = $rowposition['position_code'];

							if ($row['type'] == 'correct') {
								// Pobieram cene zakupu
								$purchase_price_query = "SELECT price_purchase FROM ecminvoiceoutitems WHERE id='" . $rowposition['old_position_id'] . "'";
								$r = $db->query($purchase_price_query);
								$rpurchase = $db->fetchByAssoc($r);
								$tmprow['position_total_price_purchase'] = round($rpurchase['price_purchase'] * $rowposition['position_quantity_corrected'], 2);
								$tmprow['position_total_netto'] = round($rowposition['position_total_netto_corrected'] * $currency_value, 2);
								$tmprow['position_total_brutto'] = round($rowposition['position_total_brutto_corrected'] * $currency_value, 2);
								$tmprow['position_quantity'] = $rowposition['position_quantity_corrected'];
							} else {
								$tmprow['position_total_netto'] = round($rowposition['position_total_netto'] * $currency_value, 2);
								$tmprow['position_total_brutto'] = round($rowposition['position_total_brutto'] * $currency_value, 2);
								$tmprow['position_total_price_purchase'] = round($rowposition['position_price_purchase'] * $rowposition['position_quantity'], 2);
								$tmprow['position_quantity'] = $rowposition['position_quantity'];
							}

							$tmprow['position_unit_id'] = $rowposition['position_unit_id'];
							$tmprow['position_unit_name'] = $rowposition['position_unit_name'];
							$tmprow['product_id'] = $rowposition['product_id'];
							$tmprow['ecminvoiceout_id'] = $rowposition['ecminvoiceout_id'];
							$positionArray[] = $tmprow;
						}
					}
				} else {
					$currency_value = 1;

					if ($row['currency_value_nbp'] != '') {
						$currency_value = $row['currency_value_nbp'];
					}
					/*
					if($row['currency_value']!= ''){
						$currency_value = $row['currency_value'];
					}*/

					$positionQuery = "SELECT
				ecminvoiceoutitems.id as position_id,
				ecminvoiceoutitems.name as position_name,
				ecminvoiceoutitems.total_netto as position_total_netto,
				ecminvoiceoutitems.total_brutto as position_total_brutto,
				ecminvoiceoutitems.price_purchase as position_price_purchase,
				ecminvoiceoutitems.quantity as position_quantity,
				ecminvoiceoutitems.dd_unit_id as position_unit_id,
				ecminvoiceoutitems.dd_unit_name as position_unit_name,
								ecminvoiceoutitems.ecminvoiceout_id as ecminvoiceout_id,
				ecminvoiceoutitems.total_netto_corrected as position_total_netto_corrected,
				ecminvoiceoutitems.quantity_corrected as position_quantity_corrected,
				ecminvoiceoutitems.total_brutto_corrected as position_total_brutto_corrected,
				ecminvoiceoutitems.old_ecminvoiceoutitem_id as old_position_id,
				ecminvoiceoutitems.code as position_code,
				ecminvoiceoutitems.ecmproduct_id as product_id
				FROM ecminvoiceoutitems
				WHERE
				ecminvoiceoutitems.ecminvoiceout_id='" . $row['id'] . "'
				 ";
					if (count($where['ecmproducts']) > 0) {
						$positionQuery .= ' AND ' . implode(" AND ", $where['ecmproducts']);
					}
					$positionQuery .=  " ORDER BY ecminvoiceoutitems.position ";
					$positionresult = $db->query($positionQuery);

					if ($positionresult->num_rows > 0) {

						while ($rowposition = $db->fetchByAssoc($positionresult)) {
							$tmprow = array();
							$tmprow['position_name'] = $rowposition['position_name'];
							$tmprow['position_id'] = $rowposition['position_id'];
							$tmprow['position_code'] = $rowposition['position_code'];

							if ($row['type'] == 'correct') {
								// Pobieram cene zakupu
								$purchase_price_query = "SELECT price_purchase FROM ecminvoiceoutitems WHERE id='" . $rowposition['old_position_id'] . "'";
								$r = $db->query($purchase_price_query);
								$rpurchase = $db->fetchByAssoc($r);
								$tmprow['position_total_price_purchase'] = round($rpurchase['price_purchase'] * $rowposition['position_quantity_corrected'], 2);
								$tmprow['position_total_netto'] = round($rowposition['position_total_netto_corrected'] * $currency_value, 2);
								$tmprow['position_total_brutto'] = round($rowposition['position_total_brutto_corrected'] * $currency_value, 2);
								$tmprow['position_quantity'] = $rowposition['position_quantity_corrected'];
							} else {
								$tmprow['position_total_netto'] = round($rowposition['position_total_netto'] * $currency_value, 2);
								$tmprow['position_total_brutto'] = round($rowposition['position_total_brutto'] * $currency_value, 2);
								$tmprow['position_total_price_purchase'] = round($rowposition['position_price_purchase'] * $rowposition['position_quantity'], 2);
								$tmprow['position_quantity'] = $rowposition['position_quantity'];
							}

							$tmprow['position_unit_id'] = $rowposition['position_unit_id'];
							$tmprow['position_unit_name'] = $rowposition['position_unit_name'];
							$tmprow['product_id'] = $rowposition['product_id'];
							$tmprow['ecminvoiceout_id'] = $rowposition['ecminvoiceout_id'];
							$positionArray[] = $tmprow;
						}
					}
				}
				$row['position_list'] = $positionArray;
				$row['document_type'] = "EcmInvoiceOuts";
				$returnArray[] = $row;
			}
		}
		/*	foreach($returnArray as $value){
			var_dump($value);
			echo '<br><br>';
		} */
		return $returnArray;
	}

	function get_PDF_file_path($pdf_type)
	{
		//Sprawdzam czy jest pobrana faktura
		if ($this->id == '') {
			return 'NAJPIERW RETRIEVE potem se generuj PDF';
		}

		//Sprawdzamy czy katalog do zapisu PDF istneje jak nie to tworzymy
		$EcmSysInfo = new EcmSysInfo();
		$dir = 'upload/' . $EcmSysInfo->getDatabaseName() . '/pdf/EcmInvoiceOuts/';
		if (!is_dir($dir)) {
			mkdir($dir, '755', true);
		}


		// Tworzymy nazwe pliku

		if ($this->type == 'normal') {
			$prefix = "FK";
		} else if ($this->type == 'correct') {
			$prefix = "KF";
		}

		if ($pdf_type == '1') {
			$prefix .= "_DUPLIKAT";
		}

		if ($pdf_type == 'lr') {
			$prefix .= "_LR";
		}

		$data_array = explode(".", $this->register_date);
		$infix = $data_array[2] . $data_array[1] . $data_array[0];
		$suffix = $this->document_autoincrement;


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


		//Sprawdzam czy pdf juz istnieje
		if (file_exists($dir . $file_name)) {
			if ($EcmSysInfo->getDatabaseName() == 'saassystem') {

				$date = new DateTime($this->register_date);

				$date2 = new DateTime("01.11.2017");

				if ($date < $date2) {

					return $dir . $file_name;
				}
			}
			if ($EcmSysInfo->getDatabaseName() == 'preDb_0dcc87940d3655fa574b253df04ca1c3') {
				unlink($dir . $file_name);
			}
			//	return $dir . $file_name;
		}

		// Jak nie ma to tworzymy : )
		global $current_user, $app_list_strings;
		$user = new User();
		$user->retrieve($this->assigned_user_id);
		$labels = return_module_language($this->ecmlanguage, 'EcmInvoiceOuts');
		//dla kompatybilnosci kodu...
		$focus = new EcmInvoiceOut();
		$focus->retrieve($this->id);

		if ($pdf_type == 'lr') {
			$header = $EcmSysInfo->getHeaderForModule('EcmInvoiceOuts');
			$footer = $EcmSysInfo->getFooterForModule('EcmInvoiceOuts');
			include_once("modules/EcmStockOperations/PdfTemplate/content.php");
			$content = getDocOperations('EcmInvoiceOuts', $this->id);
		}
		if ($pdf_type == '0') {
			include_once("modules/EcmInvoiceOuts/PDFTemplate/helper.php");
			$pp = $focus->getPositionList(true);
			$positions = formatPDFPositions($pp, $focus);

			$discount_avaiable = checkIsDiscount($focus->getPositionList(true), $focus);

			$oo_avaiable = checkIsOO($focus->getPositionList(true), $focus);
			$pk_avaiable = checkIsPK($focus->getPositionList(true), $focus);

			$header = $EcmSysInfo->getHeaderForModule('EcmInvoiceOuts');
			$footer = $EcmSysInfo->getFooterForModule('EcmInvoiceOuts');

			$content = '';
			if ($focus->endinvoice == 1) {
				include("modules/EcmInvoiceOuts/PDFTemplate/content_end.php");
			} else {
				if ($EcmSysInfo->getDatabaseName() == 'preDb_0dcc87940d3655fa574b253df04ca1c3') {
					include("modules/EcmInvoiceOuts/PDFTemplate/twinpol.php");
				} else {
					include("modules/EcmInvoiceOuts/PDFTemplate/content.php");
				}
			}
			//$content.='test';

			if ($oo_avaiable == true) {
				$content .= '<br> OO - Odwrotne obciążenie zgodnie z art. 17 ust. 1 pkt 8 ustawy o vat.';
			}
		}
		if ($pdf_type == '1') {
			include_once("modules/EcmInvoiceOuts/PDFTemplate/helper.php");
			$pp = $focus->getPositionList(true);
			$positions = formatPDFPositions($pp, $focus);
			$discount_avaiable = checkIsDiscount($focus->getPositionList(true), $focus);
			$oo_avaiable = checkIsOO($focus->getPositionList(true), $focus);
			$pk_avaiable = checkIsPK($focus->getPositionList(true), $focus);

			$header = $EcmSysInfo->getHeaderForModule('EcmInvoiceOuts');
			$footer = $EcmSysInfo->getFooterForModule('EcmInvoiceOuts');
			$content = '';
			if ($focus->endinvoice == 1) {
				include("modules/EcmInvoiceOuts/PDFTemplate/content_end.php");
			} else {
				include("modules/EcmInvoiceOuts/PDFTemplate/content.php");
			}

			//$content.=PHP_EOL."Duplikat wystawiony dnia: ".date('d.m.Y');

			if ($oo_avaiable == true) {
				$content .= '<br> OO - Odwrotne obciążenie zgodnie z art. 17 ust. 1 pkt 7 ustawy o vat.';
			}
		}

		include_once("include/MPDF57/mpdf.php");
		$p = new mPDF('', 'A4', null, 'helvetica', 10, 10, 30, 45, 5, 5);
		$p->SetHTMLHeader($header);
		$p->SetHTMLFooter($footer);
		$p->WriteHTML($content);
		$p->Output($dir . $file_name, "F");
		return $dir . $file_name;
	}
}
