<?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_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 $canceled;
	var $pricebook_id;
	var $show_recipient_code;
	var $total_netto;
	var $total_brutto;
	var $vats_summary;
	// 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
		$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";
		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 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 );
		/*
		 * $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'] = format_number ( $tmp ['total_netto'] );
		}
		$this->retrieve ( $this->id );
		
		$the_array ['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
		$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&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'] = "<a  target='_blank' href='index.php?module=EcmSales&action=DetailView&record=$a->id'>".$a->document_no."</a>";
		
		
		if($this->wz_id!=""){
			$a = new EcmStockDocOut();
			$a->retrieve($this->wz_id);
			
			$wz_array[] = "<a  target='_blank' href='index.php?module=EcmStockDocOuts&action=DetailView&record=$a->id'>".$a->document_no."</a>";
		}
		
		if($this->wz_record_zb!=""){
			$wzIds=explode(",",($this->wz_record_zb));
			
			foreach ($wzIds as $id){
				if($id!=""){
					$a = new EcmStockDocOut();
					$a->retrieve($id);
					
					$wz_array[] = "<a  target='_blank' href='index.php?module=EcmStockDocOuts&action=DetailView&record=$a->id'>".$a->document_no."</a>";
				}
			}
		}
		
		$the_array['WZ']=implode(',',$wz_array);
		
		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, $singleSelect = false) {
		echo '<script type="text/javascript" src="include/ECM/EcmPreviewPDF/EcmPreviewPDF.js"></script>';
		echo '<script type="text/javascript" src="modules/EcmInvoiceOuts/ListView.js"></script>';
		echo '<link rel="stylesheet" type="text/css" href="modules/EcmInvoiceOuts/ListView.css" />';
		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 saveWzRelation() {
		if ($this->wz_id != "") {
			$query = 'update ecmstockdocouts set ecminvoiceout_id="' . $this->id . '",ecminvoiceout_name="' . $this->document_no . '", where id="' . $this->wz_id . '"';
			$this->db->query ( $query );
		}
	}
	function save($check_notify = FALSE) {
		global $current_user;
		
		if (! $this->id || $this->id == '') {
			// generate number
			$this->number = $this->generateNumber ( 'yes' );
			$this->document_no = $this->formatNumber ( $this->number );
			if ($this->paid_val == '')
				$this->paid_val = 0;
		}
		
		if ($this->type == 'correct' && !((isset($_REQUEST['isEditMode']) && $_REQUEST['isEditMode'] == 'true'))) {
			$this->number = $this->generateNumberCorrect ();
			$this->document_no = $this->formatNumberCorrect ( $this->number );
			$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;
		}

		// clear PDF on new version save
		$this->db->query("delete from ecminvoiceout_pdf where id='".$this->id."'");
		
		$this->vats_summary = htmlspecialchars ( $this->vats_summary );
		$db = $GLOBALS ['db'];
		
		$return_id = parent::save ( $check_notify );
		
		$this->saveWzRelation ();
		
		if ($this->type == 'normal')
			$this->savePositions ( $return_id );
		if ($this->type == 'correct')
			$this->saveCorrectPositions ( $return_id );
		
		$a = new Account ();
		$a->retrieve ( $this->parent_id );
		if ($a->parent_id == '1249') {
			$aa = new Account ();
			$aa->retrieve ( '1249' );
			$p_id = $aa->id;
			$p_name = $aa->name;
			unset ( $aa );
		} else {
			$p_id = $this->parent_id;
			$p_name = $this->parent_name;
		}
		unset ( $a );
		
		$res_count = $db->query ( "select id from ecmtransactions where record_id='" . $return_id . "' and deleted='0'" );
		$count = $res_count->num_rows;
		if ($count == 0) {
			
			$GLOBALS ['db']->query ( "INSERT INTO ecmtransactions(id,name,date_entered,date_modified,modified_user_id,created_by,description,deleted,assigned_user_id,value,parent_name,parent_id,payment_date,type,paid,register_date,record_id,record_type,currency_id,currency_value)VALUES
		            ('" . create_guid () . "','" . $this->document_no . "','" . date ( "Y-m-d H:i:s" ) . "','" . date ( "Y-m-d H:i:s" ) . "','" . $_SESSION ['authenticated_user_id'] . "','" . $_SESSION ['authenticated_user_id'] . "','" . $this->description . "','" . $this->deleted . "','" . $this->assigned_user_id . "','" . $this->total_brutto . "','" . $p_name . "','" . $p_id . "','" . $this->payment_date . "','0','" . $this->paid_val . "','" . $this->register_date . "','" . $return_id . "','EcmInvoiceOuts','" . $this->currency_id . "','" . $this->currency_value_nbp . "')" );
		} else {
			$db->query ( "update ecmtransactions set value='" . $total_brutto . "' where record_id='" . $return_id . "'" );
		}
		
		/*
		if($this->parent_id=='1b9643ca-5b1a-8f9b-b809-586b5619b068'){
			if($this->type=='normal'){
				$this->sendSoap();
			}
		}
		*/
		$this->CalculatePurchasePrices ();
		return $return_id;
	}
	
	function sendSoap(){
		ini_set ( "soap.wsdl_cache_enabled", "0" );
		require_once ("nusoap/nusoap.php");
		
		$soapUrl = 'http://system.saas-systems.pl/soap.php?wsdl';
		$soapUser = 'admin';
		$soapPassword = 'rudemodz123';
		
		$client = new nusoap_client ( $soapUrl, 'wsdl' );
		
		$login_parameters = array (
				'user_auth' => array (
						'user_name' => $soapUser,
						'password' => md5 ( $soapPassword ),
						'version' => '1'
				),
				'application_name' => 'SoapTest',
				'name_value_list' => array ()
		);
		
		$login_result = $client->call ( 'login', $login_parameters );
		
		if ($login_result ['id'] != '') {
			$session_id = $login_result ['id'];
			
			
			$sdi = new EcmInvoiceOut();
			$sdi->retrieve($this->id);
			$sdi_fields = array ();
			
			$sdi_fields [] = array (
					"name" => 'parent_id',
					"value" => 'f084e64a-4e63-a3d1-6417-58cbf730df3f'
			);
			$sdi_fields [] = array (
					"name" => 'parent_name',
					"value" => 'E5 Polska Sp. z o.o.'
			);
			
			$sdi_fields [] = array (
					"name" => 'parent_address_street',
					"value" => 'ul. Wąwozowa 11'
			);
			$sdi_fields [] = array (
					"name" => 'parent_address_postalcode',
					"value" => '02-796'
			);
			$sdi_fields [] = array (
					"name" => 'parent_address_city',
					"value" => 'Warszawa'
			);
			$sdi_fields [] = array (
					"name" => 'parent_address_country',
					"value" => 'Polska '
			);
			$sdi_fields [] = array (
					"name" => 'parent_nip',
					"value" => '525-21-73-990'
			);
			$sdi_fields [] = array (
					"name" => 'kind',
					"value" => 'other'
			);
			
			$sdi_fields [] = array (
					"name" => 'stock_id',
					"value" => '754a59d6-979f-7006-a202-57c96a3eb06b'
			);
			$sdi_fields [] = array (
					"name" => 'name',
					"value" => $sdi->document_no
			);
			
			$sdi_fields [] = array (
					"name" => 'id',
					"value" => $sdi->id
			);
			$sdi_fields [] = array (
					"name" => 'total_netto',
					"value" => format_number($sdi->total_netto)
			);
			
			$sdi_fields [] = array (
					"name" => 'total_netto',
					"value" => format_number($sdi->total_netto)
			);
			
			$sdi_fields [] = array (
					"name" => 'vats_summary',
					"value" => ($sdi->vats_summary)
			);
			
			
			$sdi_fields [] = array (
					"name" => 'date_fk',
					"value" => date("d.m.Y")
			);
			
			$sdi_fields [] = array (
					"name" => 'register_date',
					"value" => date("d.m.Y")
			);
			
			
			$sdi_fields [] = array (
					"name" => 'new_with_id',
					"value" => true
			);
			
			$sdi_fields [] = array (
					"name" => 'position_list',
					"value" => serialize ( $sdi->getPositionList ( true ) )
			);
			
			$set_entry_parameters = array (
					// session id
					"session" => $session_id,
					
					// The name of the module from which to retrieve records.
					"module_name" => "EcmStockDocIns",
					
					// Record attributes
					"name_value_list" => $sdi_fields
			)
			;
			
			$set_entry_result = $client->call ( "set_entry", $set_entry_parameters );
			
			
		}
	}
	
	// ***************************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) {
		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;
			}
			
			$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'] == '') ? 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'],
					'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'],
					'recipient_code' => $p ['recipient_code'],
					'ean' => $p ['product_ean'] 
			);
			$this->db->query ( $this->constructInsertQuery ( $arr ) );
			// if($this->stock_id!='' && $this->wz_id=='')$this->addProducts($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;
			}
			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] ['ecmvat_id'] == $position_list [$i + 1] ['ecmvat_id'])
				continue;
			
			$arr = array (
					'id' => create_guid (),
					'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_price_netto' => $position_list [$i + 1] ['price_netto'],
					'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'],
					'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 ),
					'total_vat_corrected' => round ( floatval ( $position_list [$i] ['total_vat'] ) - floatval ( $position_list [$i + 1] ['total_vat'] ), 2 ) 
			);
			$this->db->query ( $this->constructInsertQuery ( $arr ) );
			$counter ++;
		}
	}
	function getPosition($position, $createCorrect = "false", $correctedItem = false) {
		if (! is_array ( $position ))
			return '';
		global $timedate;
		$pr = new EcmProduct ();
		$pr->retrieve ( $position ['ecmproduct_id'] );
		$return_array = array ();
		$return_array ['product_id'] = $position ['ecmproduct_id'];
		$return_array ['position'] = $position ['position'];
		$return_array ['product_code'] = $position ['code'];
		$return_array ['product_ks_group'] = $pr->group_ks;
		$return_array ['product_ean'] = $position ['ean'];
		$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 ['price_brutto'] = $position ['price_brutto'];
		$return_array ['discount'] = $position ['discount'];
		$return_array ['total_netto'] = $position ['total_netto'];
		$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 ['recipient_code'] = $position ['recipient_code'];
		$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 ['total_netto_corrected'] = $position ['total_netto_corrected'];
		$return_array ['total_vat_corrected'] = $position ['total_vat_corrected'];
		$return_array ['total_brutto_corrected'] = $position ['total_brutto_corrected'];
		$return_array['product_parent_doc_id'] =$position ['parent_doc_id'];
		$return_array['product_parent_doc_type']= $position ['parent_doc_type'];
		$return_array['product_parent_doc_item_id'] = $position ['parent_doc_item_id'];
		
		// 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") {
			
			$return_array ['product_item_id'] = $position ['id'];
			
			if ($correctedItem == "true")
				$return_array ['product_corrected'] = "true";
			else {
				// repair VAT
				// $return_array ['ecmvat_id'] = '28079566-b825-e38f-9993-4ccc7b781de5';
				// $return_array ['ecmvat_name'] = '23%';
				// $return_array ['ecmvat_value'] = '23';
				$return_array ['product_corrected'] = "false";
			}
			
			// get values from previous corrects
			
			$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 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 {
				$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 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;
	}
	// ***************************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($kod = null) {
		if ($kod == null) {
			$rok = date ( 'Y' );
		} else {
			$rok = date ( 'Y', strtotime ( $this->register_date ) );
		}
		
		$db = $GLOBALS ['db'];
		$r = $db->fetchByAssoc ( $db->query ( "SELECT count(id) as c FROM ecminvoiceouts WHERE deleted='0' AND YEAR(register_date)='" . $rok . "' and type='normal'" ) );
		
		if (! $r || ! $r ['c'] || $r ['c'] == '')
			$count = 0;
		else
			$count = intval ( $r ['c'] );
		
		$count ++;
		
		// difference between old and new module (- 2323/14/a)
		// $count+=151;
		
		// has 5 digits?
		$tmp = strval ( $count );
		while ( strlen ( $tmp ) < 5 )
			$tmp = '0' . $tmp;
		
		if ($kod == null) {
			return date ( "Ymd" ) . $tmp;
		} else {
			return date ( 'Ymd', strtotime ( $this->register_date ) ) . $tmp;
			;
		}
	}
	function generateNumberCorrect($kod = null) {
		if ($kod == null) {
			$rok = date ( 'Y' );
		} else {
			$rok = date ( 'Y', strtotime ( $this->register_date ) );
		}
		
		$db = $GLOBALS ['db'];
		$r = $db->fetchByAssoc ( $db->query ( "SELECT count(id) as c FROM ecminvoiceouts WHERE deleted='0' AND YEAR(register_date)='" . $rok . "' and type='correct'" ) );
		
		if (! $r || ! $r ['c'] || $r ['c'] == '')
			$count = 0;
		else
			$count = intval ( $r ['c'] );
		
		$count ++;
		
		// difference between old and new module
		// $count-=6;
		
		// has 5 digits?
		$tmp = strval ( $count );
		while ( strlen ( $tmp ) < 5 )
			$tmp = '0' . $tmp;
		
		if ($kod == null) {
			return date ( "Ymd" ) . $tmp;
		} else {
			return date ( 'Ymd', strtotime ( $this->register_date ) ) . $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, 2, 2 );
		
		// has 3 digits?
		while ( strlen ( $n ) < 3 )
			$n = '0' . $n;
		// if($st['no']!='')return ''.$n.'/'.$st['no'].'/'.$y;
		return 'FV ' . $n . '/' . $y;
	}
	function formatNumberCorrect($number) {
		$n = intval ( substr ( $number, 8, 5 ) );
		$y = substr ( $number, 2, 2 );
		
		// has 3 digits?
		while ( strlen ( $n ) < 3 )
			$n = '0' . $n;
		
		return 'FVKOR ' . $n . '/' . $y;
	}
	function CalculatePurchasePrices() {
		$db = $GLOBALS ['db'];
		
		// update items
		if ($this->type == 'normal')
			$query = "
			UPDATE
				ecminvoiceoutitems AS ii
			INNER JOIN
				ecmstockdocoutitems AS wi ON ii.parent_doc_item_id = wi.id
			SET
				ii.price_purchase = wi.price
			WHERE
				ii.ecminvoiceout_id = '$this->id';
			";
		else
			$query = "
			UPDATE 
				ecminvoiceoutitems AS ci
			INNER JOIN 
				ecminvoiceoutitems AS ii ON ci.ecminvoiceoutitem_id = ii.id
			SET
				ci.price_purchase = ii.price_purchase
			WHERE
				ci.ecminvoiceout_id='$this->id';
			";
		
		$db->query ( $query );
		
		// update purchase_price on invoice
		if ($this->type == 'normal')
			$query = "
			UPDATE 
				ecminvoiceouts i
			INNER JOIN (
				SELECT ecminvoiceout_id, ROUND(SUM(quantity * price_purchase),2)  pp_sum 
				FROM ecminvoiceoutitems
				GROUP BY ecminvoiceout_id
			) ii 
			ON i.id = ii.ecminvoiceout_id
			SET i.purchase_price = ii.pp_sum
			WHERE
			i.id='$this->id';	
		";
		else
			$query = "
			UPDATE
				ecminvoiceouts i
			INNER JOIN (
				SELECT ecminvoiceout_id, ROUND(SUM(quantity_corrected * price_purchase),2)  pp_sum
				FROM ecminvoiceoutitems
				GROUP BY ecminvoiceout_id
			) ii
			ON i.id = ii.ecminvoiceout_id
			SET i.purchase_price = ii.pp_sum
			WHERE
			i.id='$this->id';
			";
		
		$db->query ( $query );
	}
	function sendDocument() {
		ini_set ( "soap.wsdl_cache_enabled", "0" );
		require_once ("nusoap/nusoap.php");
		
		$soapUrl = 'http://system.saas-systems.pl/soap.php?wsdl';
		$soapUser = 'admin';
		$soapPassword = 'rudemodz123';
		
		$this->client = new nusoap_client ( $this->url, 'wsdl' );
		
		$login_parameters = array (
				'user_auth' => array (
						'user_name' => $soapUser,
						'password' => md5 ( $soapPassword ),
						'version' => '1' 
				),
				'application_name' => 'SoapTest',
				'name_value_list' => array () 
		);
		
		$login_result = $this->client->call ( 'login', $login_parameters );
		
		if ($login_result ['id'] != '') {
			$this->session_id = $login_result ['id'];
		}
	}
}
?>