<?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 EcmSale 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;
	// added 4.03.2009
	var $pricebook_id;
	var $show_recipient_code;
	//
	var $parent_iln;
	var $parent_nip;
	var $parent_document_no;
	var $shipping_address_name;
	var $shipping_addresses;
	var $shipping_address_street;
	var $shipping_address_city;
	var $shipping_address_postalcode;
	var $shipping_address_country;
	var $shipping_phone;
	var $shipping_iln;
	var $shipping_nip;
	var $payment_date_days;
	var $supplier_code;
	var $delivery_date;
	var $payment_date;
	var $edi_file;
	var $total_netto;
	var $total_brutto;
	// RELATED FIELDS
	var $created_by;
	var $created_by_name;
	var $modified_by_name;
	var $assigned_user_name;
	var $send_date;
	var $payment_method;
	var $order_source;
	var $order_source_id;
	var $pdf_type;
	var $pdf_text;
	var $ecommerce_invoices;
	// SUBPANELS RELATED
	// MODULE OBJECT DETAILS
	var $module_dir = "EcmSales";
	var $table_name = "ecmsales";
	var $object_name = "EcmSale";
	// 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',
	);

	var $main_sale_id;
	var $main_sale_no;

	var $stock_id;
	
	function EcmSale() {
		parent::SugarBean ();
		$this->setupCustomFields ( 'EcmSales' );
		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 .= "ecmsales.*
                  ,users.user_name as assigned_user_name";
		if ($custom_join) {
			$query .= $custom_join ['select'];
		}
		$query .= " FROM ecmsales 
                   LEFT JOIN users
                   ON ecmsales.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 ecmsales.name";
		return $query;
	}
	function create_export_query($order_by, $where) {
		$custom_join = $this->custom_fields->getJOIN ();
		$query = "SELECT
                      ecmsales.*,
                      users.user_name assigned_user_name";
		if ($custom_join) {
			$query .= $custom_join ['select'];
		}
		$query .= " FROM ecmsales ";
		$query .= " LEFT JOIN users
                  ON ecmsales.assigned_user_id=users.id";
		if ($custom_join) {
			$query .= $custom_join ['join'];
		}
		$query .= "";
		$where_auto = " ecmsales.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 ecmsales.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 );
		/*
		$result = $this->db->query ( "SELECT status, parent_id, contact_id, template_id, assigned_user_id FROM ecmsales 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 `ecmsales` 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,$current_user;

		$this->fill_in_additional_detail_fields ();
		$app_list_strings = return_app_list_strings_language ( $current_language );
		$mod_strings = return_module_language ( $current_language, 'EcmSales' );
		$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 ['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
		$a = new Account();
		$a->retrieve($this->parent_id);
		$the_array ['SHOP_NUMBER'] = $a->shop_number;
		
		$a = new EcmStockDocOut();
		$a->retrieve_by_string_fields(['so_id'=>$this->id]);
	
		$the_array ['WZ'] = "<a  target='_blank' href='index.php?module=EcmStockDocOuts&action=DetailView&record=$a->id'>".$a->document_no."</a>";
		$a = new EcmInvoiceOut();
		$a->retrieve_by_string_fields(['so_id'=>$this->id]);
		$the_array ['FV'] = "<a  target='_blank'  href='index.php?module=EcmInvoiceOuts&action=DetailView&record=$a->id'>".$a->document_no."</a>";
		
		$the_array ['ZS'] = "<a  target='_blank'  href='https://crm.e5.pl/index.php?module=EcmSales&action=DetailView&record=$this->edi_zs_id'>".$this->edi_zs_document_no."</a>";
		$the_array ['TOTAL'] = format_number ( $this->total_netto );
		//create image options
		$the_array['DOCUMENT_AUTOINCREMENT']=date('d.m.Y',strtotime($this->register_date));
		$op = '<a href="index.php?module=EcmSales&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/EcmSales/images/pdf.gif"/></a>';
		$the_array['OPTIONS'] = $op;

		return $the_array;
	}
	
	function getPriceFromDocument($product){
	    $zap=$this->db->query("select quantity,price_netto,total_netto from ecmsaleitems where ecmsale_id='".$this->id."' and ecmproduct_id='".$product."'");
	    $dane=$this->db->fetchByAssoc($zap);
	    return $dane;
	}
	
	function getStatusMenuInfo($inJSON = true) {
		global $app_list_strings;
		$arr = array ();
		foreach ( $app_list_strings ['ecmsales_status_dom'] as $key => $value ) {
			$arr [$key] = array (
					'enabled' => '<div><img src="modules/EcmSales/images/' . $key . '.gif" />' . $value . '</div>',
					'disabled' => '<div><img src="modules/EcmSales/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/EcmSales/ListView.js"></script>';
		echo '<link rel="stylesheet" type="text/css" href="modules/EcmSales/ListView.css" />';
		echo '<script language="javascript"> var EcmSalesStatusMenu = ' . $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="statusListEcmSale_' . $id . '" style="display:inline;"><img src="modules/EcmSales/images/' . $status . '.gif" title="' . $app_list_strings ['ecmsales_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, "ecmsales.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
		
		//get number format 2015-04-23
		require_once('modules/EcmSysInfos/EcmSysInfo.php');
		$EcmSysInfo = new EcmSysInfo();
		$template = $EcmSysInfo->getFormatNumberForModule('EcmSales');
		unset($EcmSysInfo);
	
		global $current_user;
		if (!$this->id || $this->id=='') {
			if ($template != "") {
				require_once('include/ECM/EcmDocumentNumberGenerator/EcmDocumentNumberGenerator.inc.php');
				$dng = new EcmDocumentNumberGenerator('EcmSales',$this->register_date);
				$this->document_no=  $dng->parseSaleNumber($template, $this->stock_id, $this->order_source);
			}
		}

        if ($this->order_source == null || strlen($this->order_source_id) == 0) {
            $this->order_source = 'standard';
        }

		$this->vats_summary = htmlspecialchars($this->vats_summary);
		$aa=explode('/',$this->document_no);
		$this->document_autoincrement=date("Ymd",strtotime($this->register_date)).''.sprintf('%05d',(string)((int)$aa[0]));
		


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

		//remove res
	//	include_once("modules/EcmStockOperations/EcmStockOperation.php");
		//$op=new EcmStockOperation();
		//$op->removeDocumentReservations($return_id);
		$this->savePositions($return_id);
		
		if($this->total_brutto!=0){
			$this->db->query("update ecmsales set total_brutto='".round($this->total_brutto,2)."' where id ='".$this->id."'");
		}
		return $return_id;
	}
	// ***************************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;
		$this->total_brutto=0;
		for($i = 0; $i < count ( $position_list ); $i ++) {
			if ($position_list [$i] ['name'] == '' || $position_list [$i]['product_id']=='')
				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']),
					'price_brutto'=> round($p['price_netto']+($p['price_netto']*($p ['ecmvat_name']/100)),2),
					'total_brutto'=> round($p['total_netto']+($p['total_netto']*($p ['ecmvat_name']/100)),2),
					'discount' => ((empty ( $p ['discount'] ) || $p ['discount'] == '') ? 0 : $p ['discount']),
					'total_netto' => ((empty ( $p ['total_netto'] ) || $p ['total_netto'] == '') ? 0 : $p ['total_netto']),
					'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' => (empty($p['recipient_code']) ? $p ['product_recipient_code'] : $p['recipient_code']),
			);
			$this->total_brutto=$this->total_brutto+($p['total_netto']+($p['total_netto']*($p ['ecmvat_name']/100)));
			$this->db->query ( $this->constructInsertQuery ( $arr ) );
			
			//add mz 11-05-2015
			//save reservation
			include_once("modules/EcmStockOperations/EcmStockOperation.php");
			$op=new EcmStockOperation();
			$q = ((empty ( $p ['quantity'] ) || $p ['quantity'] == '') ? 0 : $p ['quantity']);
			//$op->saveParentReservation($this->stock_id, $p ['product_id'], $id, $item_id, $q, 'EcmSale');
			$position ++;
		}
	}
	function getPosition($position,$module) {
		if (! is_array ( $position ))
			return '';
		global $timedate,$app_list_strings;
		$return_array = array ();
		$p=new EcmProduct();
		$p->retrieve($position ['ecmproduct_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'];
		if($module=='EcmReceipts'){
		    $return_array ['price_start'] = $position ['price_brutto'];
		} else {
		    $return_array ['price_start'] = $position ['price_start'];
		}
		$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->id' and it.ecmproduct_id='".$position ['ecmproduct_id']."' group by it.id";
		//echo $query;
		$r = $this->db->query ( $query );
		$r2=$this->db->fetchByAssoc($r);
		$return_array ['quantity_used']=$r2['quantity'];
		$return_array ['product_ks_group'] = $p->ks_group;
		$return_array ['price_netto'] = $position ['price_netto'];
		$return_array ['price_brutto'] = $position ['price_brutto'];
		$return_array ['price_total_netto'] = $position ['total_netto'];
		$return_array ['price_total_brutto'] = $position ['total_brutto'];
		$return_array ['price_vat'] = $position ['price_brutto']-$position ['price_netto'];
		$return_array ['price_total_vat'] = $position ['total_brutto']-$position ['total_netto'];
		$return_array ['price_ecmvat_id'] = $position ['ecmvat_id'];
		$return_array ['price_ecmvat_name'] = $position ['ecmvat_name'];
		$return_array ['price_ecmvat_value'] = $position ['ecmvat_value'];
		$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 ['product_recipient_code'] = $position ['recipient_code'];	
		$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']];
		$return_array['product_category_id'] = $p->product_category_id;
		$return_array['real_vat_id'] = $p->vat_id;
		$return_array['real_vat_name'] = $p->vat_name;
		$return_array['real_vat_value'] = $p->vat_value;
        // for WZ
        $return_array['product_pieces_per_carton'] = $p->pieces_per_carton;
        $return_array['un_code'] = $p->un_code;
		
		//get reservatiaons
		//add mz 2015-05-11
		include_once("modules/EcmStockOperations/EcmStockOperation.php");
		$op=new EcmStockOperation();
		$return_array['quantity_res'] = format_number($op->getProductReservations($this->id, $position['id']),0,0);
		unset($p);
		return $return_array;
	}
	function getPositionList($array = false,$module) {
		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,$module);
				}
				$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;
	}
	function getPositionListForInvoice($array = false,$module) {
	    $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->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;
	        }
	        $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,$module);
	            }
	        }
	
	
	        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]);
	            }
	        }
	         
	        // reindexing ....
	        $return_array = array_merge($return_array);
	        for($i=0;$i<count($return_array);$i++){
	            $return_array[$i]['position']=$i;
	        }
	
	        $json = getJSONobj ();
	        return $array ? $return_array : $json->encode ( $return_array );
	    } else {
	        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,$module);
	                }
	                $json = getJSONobj ();
	                return $array ? $return_array : $json->encode ( $return_array );
	            }
	        }
	    }
	    return $array ? false : '[]';
	}
	//mz generate number
	function generateNumber() {
		$db = $GLOBALS['db'];
		$r = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecmsales WHERE deleted='0' AND YEAR(register_date)='".date('Y')."'"));

	    if (!$r || !$r['c'] || $r['c']=='')
	    	$count = 0;
	    else
	    	$count = intval($r['c'])+1;
	    
	    $count++;
	    
	    //has 5 digits?
	    $tmp = strval($count);
	    while (strlen($tmp) < 5)
	    	$tmp = '0'.$tmp;
	    
	    return date("Ymd").$tmp;
	}
	
	function formatNumber($number) {
		$n = intval(substr($number, 8,5));
		$y = substr($number,0,4);
		
		//has 3 digits?
		while (strlen($n) < 3)
			$n = '0'.$n;
		
	   return 'ZS '.$n.'/'.$y;
	}
	/*
	function CreateQueryFromPost($array){
		$field_array=array();
		if($array['date_from']!='')$field_array[]="delivery_date>='".date("Y-m-d",strtotime($array['date_from']))."'";
		if($array['date_to']!='')$field_array[]="delivery_date<='".date("Y-m-d",strtotime($array['date_to']))."'";
		if($array['time_from']!='')$field_array[]="date_entered>='".date("Y-m-d",strtotime($array['time_from']))."'";
		if($array['time_to']!='')$field_array[]="date_entered<='".date("Y-m-d",strtotime($array['time_to']))."'";
		if($array['account_id']!='')$field_array[]="parent_id='".$array['account_id']."'";
		if($array['account_name']!='')$field_array[]="parent_name like '".$array['account_name']."'";
		if($array['parent_order_no']!='')$field_array[]="parent_document_no='".$array['parent_order_no']."'";
		switch ($array ['sale_type']) {
			case 'all' :
				$field_array[] = "type IN ('sales_order', 'gratis')";
				break;
			case 'sale' :
				$field_array[] = "type='sales_order'";
				break;
			case 'gratis' :
				$field_array[] = "type='gratis'";
				break;
		}
	
		if (count ( $field_array ) > 0)
			$where = " and " . implode ( " and ", $field_array );
		else
			$where = "";
		$z = "select * from ecmsales where deleted='0' and status!='s10' " . $where;
		if ($array['sale_type']=='all')
			$z.=" ORDER BY type DESC";
		echo $z;
		return $z;
	}
	*/
	/*
	function GetArrayResultFromQuery($query){
		$db = $GLOBALS ['db'];
		$w = $db->query ($query );
		echo mysql_error ();
		$bb = 0;
		$i=0;
		$result_array=array();
		$sum_total_qty=0;
		$sum_total_netto=0;
		$sum_total_brutto=0;
		$sum_total_invoice=0;
		$sum_total_vat=0;
		while ( $r = $db->fetchByAssoc ( $w ) ) {
			$rrr = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where so_id='" . $r ['id'] . "'" ) );
	
			if ($_REQUEST ['wz'] == 1 && $rrr ['id'])
				continue;
			$ww = $db->query ( "select quantity,price_netto as price,ecmvat_value from ecmsaleitems where ecmsale_id='" . $r ['id'] . "' and deleted='0'" );
			$total_netto = 0;
			$total_brutto = 0;
			$total_invoice = 0;
			$total_vat = 0;
			$total_qty = 0;
			while ( $rr = $db->fetchByAssoc ( $ww ) ) {
				$total_qty += $rr ['quantity'];
				$total_netto += $rr ['quantity'] * $rr ['price'];
				$total_brutto += $rr ['quantity'] * $rr ['price'] * (1 + $rr ['ecmvat_value'] / 100);
				$total_vat += $rr ['quantity'] * $rr ['price'] * ($rr ['ecmvat_value'] / 100);
			}
			if ($rrr ['id']) {
				$rinv = $db->fetchByAssoc ( $db->query ( "select id, subtotal from ecminvoiceouts where wz_id='" . $rrr ['id'] . "'" ) );
				$total_invoice = $rinv ['subtotal'];
				// $wi=$db->query("select price,quantity from ecminvoiceoutitems where ecminvoiceout_id='".$rinv['id']."' and deleted='0'");
				// while($ri=$db->fetchByAssoc($wi)){
				// $total_invoice+=$ri['quantity']*$ri['price'];
				// }
			} else {
				$inv = null;
				$wi = null;
				$ri = null;
				$rwz = null;
			}
				
			$rsale = $db->fetchByAssoc ( $db->query ( "select sum(quantity*price_netto) as qty from ecmsaleitems where ecmsale_id='" . $r ['id'] . "'" ) );
			$rwz = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where so_id='" . $r ['id'] . "'" ) );
			$rwzi = $db->fetchByAssoc ( $db->query ( "select sum(quantity*price) as qty from ecmstockdocoutitems where ecmstockdocout_id='" . $rwz ['id'] . "'" ) );
			$ecmstockdocout_id = $rwz ['id'];
			if ($ecmstockdocout_id) {
				$sum_wz_qty += $rwzi ['qty'];
				$sum_sale_qty += $rsale ['qty'];
			}
			$qty_diff = $rwzi ['qty'] - $rsale ['qty'];
			$diff_minus = $diff_plus = 0;
			$rst = $rsale ['qty'];
			$rwt = $rwzi ['qty'];
			$percent = number_format ( (100 * $rwzi ['qty'] / $rsale ['qty']), 2, ",", "." ) . "%";
			$order_total=0;
			$wz_total=0;
			$wz_green=0;
			$wz_red=0;
			if ($ecmstockdocout_id) {
				$pr=0;
				$wsale = $db->query ( "select quantity,price_netto as price,code,ecmproduct_id from ecmsaleitems where deleted='0' and ecmsale_id='" . $r ['id'] . "' order by code" );
				while ( $rsale = $db->fetchByAssoc ( $wsale ) ) {
					$qty = 0;
					$wwz = $db->query ( "select quantity,selling_price from ecmstockdocoutitems where deleted='0' and ecmproduct_id='" . $rsale ['ecmproduct_id'] . "' and ecmstockdocout_id='" . $ecmstockdocout_id . "'" );
					while ( $rwz = $db->fetchByAssoc ( $wwz ) ) {
						$qty += $rwz ['quantity'] * $rwz ['selling_price'];
					}
					if ($rsale ['quantity'] * $rsale ['price'] > $qty)
						$color = "red";
					elseif ($rsale ['quantity'] * $rsale ['price'] < $qty)
					$color = "green";
					else
						$color = "black";
	
					if ($rsale ['quantity'] * $rsale ['price'] > $qty)
						$diff_minus += $qty - $rsale ['quantity'] * $rsale ['price'];
					if ($rsale ['quantity'] * $rsale ['price'] < $qty)
						$diff_plus += $qty - $rsale ['quantity'] * $rsale ['price'];
	
					$sum [$rsale ['ecmproduct_id']] ['wz'] += $qty;
					$sum [$rsale ['ecmproduct_id']] ['sale'] += $rsale ['quantity'] * $rsale ['price'];
					$rpro = $db->fetchByAssoc ( $db->query ( "select deliverydate,name from ecmproducts where id='" . $rsale ['ecmproduct_id'] . "'" ) );
					$stock_q = $db->fetchByAssoc ( $db->query ( "select sum(quantity) as quantity from ecmstockoperations where product_id='" . $rsale ['ecmproduct_id'] . "'" ) );
	
					if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00")
						$eta = $rpro ['deliverydate'];
					else
						$eta = "";
					$order=$rsale ['quantity'] * $rsale ['price'];
					$result_array[$i]['products'][$pr]['id']=$rsale ['ecmproduct_id'];
					$result_array[$i]['products'][$pr]['code']=$rsale ['code'];
					$result_array[$i]['products'][$pr]['name']=$rpro['name'];
					$result_array[$i]['products'][$pr]['stock']=$rpro['name'];
					$result_array[$i]['products'][$pr]['order']=$order;
					$result_array[$i]['products'][$pr]['quantity']=$stock_q['quantity'];
					$result_array[$i]['products'][$pr]['wz']=$qty;
					$result_array[$i]['products'][$pr]['eta']=$eta;
						
					//totals
					$order_total+=$order;
					$wz_total+=$qty;
	
						
					$pr++;
				}
			}
			// guziczki kochane
			$rwz = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where so_id='" . $r ['id'] . "'" ) );
			$rfv = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecminvoiceouts where wz_id='" . $rwz ['id'] . "'" ) );
			if ($rwz ['id'] && $rfv ['id']) {
				$sw='yes';
				$sw_id=$rfv ['id'];
				$sw_nr=$rfv ['document_no'];
			} elseif ($rwz ['id'] && ! $rfv ['id']) {
				$sw_id=$rwz ['id'];
				$sw='no';
			} else {
				$tmp = '';
				$sw='none';
				$sw_id='';
			}
			$t .= $tmp;
			$rrr = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecmstockdocouts where so_id='" . $r ['id'] . "'" ) );
			if ($rrr ['id']) {
					
				$ed = "disabled";
				$title = $rrr ['document_no'];
				$wz_idd=$rrr['id'];
			} else {
				$onclick = ' onclick="javascript:window.open(\'index.php?module=EcmStockDocOuts&amp;action=EditView&parent_doc_type=EcmSales&parent_doc_id=' . $r ['id'] . '\',\'_newtab\');"';
				$ed = "enabled";
				$title = "Create WZ";
			}
			$result_array[$i]['wz_switch']=$ed;
			$result_array[$i]['wz_name']=$title;
			$result_array[$i]['wz_id']=$wz_idd;
			$result_array[$i]['fv_switch']=$sw;
			$result_array[$i]['fv_id']=$sw_id;
			$result_array[$i]['fv_name']=$sw_nr;
			$result_array[$i]['products']['order_total']=$order_total;
			$result_array[$i]['products']['wz_total']=$wz_total;
			$result_array[$i]['products']['minus']=$diff_minus;
			$result_array[$i]['products']['plus']=$diff_plus;
			$result_array[$i]['position']=$i+1;
			$result_array[$i]['id']=$r['id'];
			$result_array[$i]['number']=$r['number'];
			$result_array[$i]['document_no']=$r['document_no'];
			$result_array[$i]['parent_name']=$r['parent_name'];
			$result_array[$i]['parent_id']=$r['parent_id'];
			$result_array[$i]['delivery_date']=$r['delivery_date'];
			$result_array[$i]['quantity']=$total_qty ;
			$result_array[$i]['total_netto']=$total_netto ;
			$result_array[$i]['total_brutto']=$total_brutto ;
			$result_array[$i]['total_vat']=$total_vat ;
			$result_array[$i]['total_invoice']=$total_invoice ;
			$result_array[$i]['percent']=$percent;
				
			$i++;
			$sum_total_qty += $total_qty;
			$sum_total_netto += $total_netto;
			$sum_total_brutto += $total_brutto;
			$sum_total_invoice += $total_invoice;
			$sum_total_vat += $total_vat;
			$percent = (100 * $sum_wz_qty / $sum_sale_qty);
		}
		$result_array['total_quantity']=$sum_total_qty;
		$result_array['total_netto']=$sum_total_netto;
		$result_array['total_brutto']=$sum_total_brutto;
		$result_array['total_invoice']=$sum_total_invoice;
		$result_array['total_vat']=$sum_total_vat;

		$result_array['total_percent']=$percent;
	
		$rst = 0;
		$rwt = 0;
		$diff_plus = $diff_minus = 0;
		$c1=0;
		$ww = $db->query ( "select id from ecmproducts where deleted='0' order by code asc" );
		while ( $rr = $db->fetchByAssoc ( $ww ) ) {
			$k = $rr ['id'];
			if (! $sum [$k])
				continue;
			$rpro = $db->fetchByAssoc ( $db->query ( "select code,deliverydate from ecmproducts where id='" . $k . "'" ) );
			if ($sum [$k] ['wz'] < $sum [$k] ['sale'])
				$color = "red";
			elseif ($sum [$k] ['wz'] > $sum [$k] ['sale'])
			$color = "green";
			else
				$color = "black";
			$rst += $sum [$k] ['sale'];
			$rwt += $sum [$k] ['wz'];
	
			if ($sum [$k] ['sale'] > $sum [$k] ['wz'])
				$diff_minus += $sum [$k] ['wz'] - $sum [$k] ['sale'];
			if ($sum [$k] ['sale'] < $sum [$k] ['wz'])
				$diff_plus += $sum [$k] ['wz'] - $sum [$k] ['sale'];
	
			if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00")
				$eta = $rpro ['deliverydate'];
			else
				$eta = "";
	
			$result_array['total_product'][$c1]['code']=$rpro ['code'];
			$result_array['total_product'][$c1]['id']=$k;
			$result_array['total_product'][$c1]['order']=$sum [$k] ['sale'];
			$result_array['total_product'][$c1]['wz']=$sum [$k] ['wz'];
			$result_array['total_product'][$c1]['eta']=$eta;
			$c1++;
		}
		$result_array['total_product']['order_total']=$rst;
		$result_array['total_product']['wz_total']=$rwt;
		$result_array['total_product']['minus']=$diff_minus;
		$result_array['total_product']['plus']=$diff_plus;
	
	
		return $result_array;
	}
	*/
	function createPdfFileName($format=true) {
		global $mod_strings;
	
		$arr1 = Array('\\', '/', ':', '*', '?' , '"',  '<', '>', '|', ' ');
	
		$arr2 = Array('',  '', '',  '',  '',   '\'', '[', ']', '', '_');
	
		$tmp = $this->document_no;
	
		if($format)
	
			$tmp = str_replace($arr1, $arr2, $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf');
	
		else
	
			$tmp = $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf';
	
		//$mod = return_module_language($current_language, 'EcmInvoiceOuts');
	
		//return urlencode(
	
		//      return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//);
	
		return $tmp; //);
	
	}
	function CreateMultiPDF($post){
		$filename=array();
		foreach($post as $id){
				
			$strPath = dirname ( __FILE__ ) . "\\";
			if($id=='')continue;
			$this->retrieve ( $id );
				
			// $pdf2 = new PDFMerger;
			//$ab [] = $this->createPdfFileName ();
				
			$ch = curl_init ();
			curl_setopt ( $ch, CURLOPT_URL, 'http://'.$_SERVER['SERVER_ADDR'].'/crm/index.php?action=Authenticate&module=Users&return_module=Users&return_action=Login&user_name=db&user_password=rudemodz&login_theme=Sugar&login_language=en_us' );
			// curl_setopt($ch, CURLOPT_POSTFIELDS,'user_name=db&user_password='.$pass.'');
	
			curl_setopt ( $ch, CURLOPT_POST, 1 );
			curl_setopt ( $ch, CURLOPT_HEADER, 0 );
			curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
			curl_setopt ( $ch, CURLOPT_COOKIEJAR, 'cookie.txt' );
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt ( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3" );
			curl_setopt ( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3" );
			$page = curl_exec ( $ch );
			// echo $page;
			// echo $pass = md5('rudemodz');
			$up = 'http://'.$_SERVER['SERVER_ADDR'].'/crm/index.php?module=EcmSales&action=createPDF&to_pdf=1&show_img=0&show_ean=0&show_ean2=0&show_recipient_code=0&record=' . $id . '';
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
			curl_setopt ( $ch, CURLOPT_URL, $up );
				
			$page = curl_exec ( $ch );
			$fp = fopen ( 'pdftmp/' . $this->createPdfFileName () . '', 'w' );
			fwrite ( $fp, $page );
			fclose ( $fp );
			$filename [] = $this->createPdfFileName ();
		}
		$fp = fopen ( 'generatorfifi.php', 'w' );
		$s = "<?php\ninclude 'PDFMerger.php';\n\$pdf = new PDFMerger;\n\$pdf";
		foreach ( $filename as $k ) {
			$s .= "->addPDF('pdftmp/" . $k . "', 'all')\n";
		}
		$s .= "->merge('file', 'pdftmp/" . $current_user->user_name .'_'. date ( "hysmd" );
		$s .= ".pdf');";
		// $b=microtime();
		fwrite ( $fp, $s );
		fclose ( $fp );
		// echo microtime();
	
		$up = 'http://'.$_SERVER['SERVER_ADDR'].'/crm/generatorfifi.php';
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $ch, CURLOPT_URL, $up );
	
		$page = curl_exec ( $ch );
	
		return $current_user->user_name.'_'.date("hysmd").".pdf";
	}
	
	
	function GetArrayResultFromQuery($query){
		$db = $GLOBALS ['db'];
		$w = $db->query ($query );
		echo mysql_error ();
		$bb = 0;
		$i=0;
		$result_array=array();
		$sum_total_qty=0;
		$sum_total_netto=0;
		$sum_total_brutto=0;
		$sum_total_invoice=0;
		$sum_total_vat=0;
		
		$wal_query="select * from currency_nbp_archive  order by date desc limit 3";
		
		$ik=$db->query($wal_query);
		$wal=[];
		while($walutki = $db->fetchByAssoc ( $ik)){
			$wal[$walutki['currency_id']]=$walutki['value'];
		}
		while ( $r = $db->fetchByAssoc ( $w ) ) {
			$rrr = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'" ) );
			
			if ($_REQUEST ['wz'] == 1 && $rrr ['id'])
				continue;
				$ww = $db->query ( "select quantity,price_netto as price,ecmvat_value from ecmsaleitems where ecmsale_id='" . $r ['id'] . "' and deleted='0'" );
				$total_netto = 0;
				$total_brutto = 0;
				$total_invoice = 0;
				$total_vat = 0;
				$total_qty = 0;
				while ( $rr = $db->fetchByAssoc ( $ww ) ) {
					$total_qty += $rr ['quantity'];
					$total_netto += ($rr ['quantity'] * $rr ['price']);
					$total_brutto += $rr ['quantity'] * $rr ['price'] * (1 + $rr ['ecmvat_value'] / 100);
					$total_vat += $rr ['quantity'] * $rr ['price'] * ($rr ['ecmvat_value'] / 100);
				}
				if ($rrr ['id']) {
					$rinv = $db->fetchByAssoc ( $db->query ( "select id, total_netto from ecminvoiceouts where wz_id='" . $rrr ['id'] . "' AND deleted='0'" ) );
					$total_invoice = $rinv ['total_netto'];
					// $wi=$db->query("select price,quantity from ecminvoiceoutitems where ecminvoiceout_id='".$rinv['id']."' and deleted='0'");
					// while($ri=$db->fetchByAssoc($wi)){
					// $total_invoice+=$ri['quantity']*$ri['price'];
					// }
				} else {
					$inv = null;
					$wi = null;
					$ri = null;
					$rwz = null;
				}
				
				$rsale = $db->fetchByAssoc ( $db->query ( "select sum(quantity*price_netto) as qty from ecmsaleitems where ecmsale_id='" . $r ['id'] . "'" ) );
				$rwz = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where so_id='" . $r ['id'] . "' and deleted='0'" ) );
				$rwzi = $db->fetchByAssoc ( $db->query ( "select sum(quantity*price_sell) as qty from ecmstockdocoutitems where ecmstockdocout_id='" . $rwz ['id'] . "'" ) );
			
				
				$ecmstockdocout_id = $rwz ['id'];
				if ($ecmstockdocout_id) {
					$sum_wz_qty += $rwzi ['qty'];
					$sum_sale_qty += $rsale ['qty'];
				}
				$qty_diff = $rwzi ['qty'] - $rsale ['qty'];
				$diff_minus = $diff_plus = 0;
				$rst = $rsale ['qty'];
				$rwt = $rwzi ['qty'];
				$percent = number_format ( (100 * $rwzi ['qty'] / $rsale ['qty']), 2, ",", "." ) . "%";
				$order_total=0;
				$wz_total=0;
				$wz_green=0;
				$wz_red=0;
				if ($ecmstockdocout_id) {
					$pr=0;
					$wsale = $db->query ( "select quantity,price_netto as price,code,ecmproduct_id from ecmsaleitems where deleted='0' and ecmsale_id='" . $r ['id'] . "' order by code" );
					while ( $rsale = $db->fetchByAssoc ( $wsale ) ) {
						$qty = 0;
						$wwz = $db->query ( "select quantity,price_sell from ecmstockdocoutitems where deleted='0' and ecmproduct_id='" . $rsale ['ecmproduct_id'] . "' and ecmstockdocout_id='" . $ecmstockdocout_id . "'" );
						while ( $rwz = $db->fetchByAssoc ( $wwz ) ) {
							$qty += $rwz ['quantity'] * $rwz ['price_sell'];
						}
						if ($rsale ['quantity'] * $rsale ['price'] > $qty)
							$color = "red";
							elseif ($rsale ['quantity'] * $rsale ['price'] < $qty)
							$color = "green";
							else
								$color = "black";
								
								if ($rsale ['quantity'] * $rsale ['price'] > $qty)
									$diff_minus += $qty - $rsale ['quantity'] * $rsale ['price'];
									if ($rsale ['quantity'] * $rsale ['price'] < $qty)
										$diff_plus += $qty - $rsale ['quantity'] * $rsale ['price'];
										
										$sum [$rsale ['ecmproduct_id']] ['wz'] += $qty;
										$sum [$rsale ['ecmproduct_id']] ['sale'] += $rsale ['quantity'] * $rsale ['price'];
										$rpro = $db->fetchByAssoc ( $db->query ( "select deliverydate,name from ecmproducts where id='" . $rsale ['ecmproduct_id'] . "'" ) );
										$stock_q = $db->fetchByAssoc ( $db->query ( "select sum(quantity) as quantity from ecmstockoperations where product_id='" . $rsale ['ecmproduct_id'] . "'" ) );
										
										if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00")
											$eta = $rpro ['deliverydate'];
											else
												$eta = "";
												$order=$rsale ['quantity'] * $rsale ['price'];
												$result_array[$i]['products'][$pr]['id']=$rsale ['ecmproduct_id'];
												$result_array[$i]['products'][$pr]['code']=$rsale ['code'];
												$result_array[$i]['products'][$pr]['name']=$rpro['name'];
												$result_array[$i]['products'][$pr]['stock']=$rpro['name'];
												$result_array[$i]['products'][$pr]['order']=$order;
												$result_array[$i]['products'][$pr]['quantity']=$stock_q['quantity'];
												$result_array[$i]['products'][$pr]['wz']=$qty;
												$result_array[$i]['products'][$pr]['eta']=$eta;
												
												//totals
												$order_total+=$order;
												$wz_total+=$qty;
												
												
												$pr++;
					}
				}
				if($r['type']!='gratis'){
					// guziczki kochane
					
					$rwz = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where so_id='" . $r ['id'] . "' and deleted='0'" ) );
					
					$rfv = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecminvoiceouts where wz_id='" . $rwz ['id'] . "' and deleted='0' and canceled='0'" ) );
					if ($rwz ['id'] && $rfv ['id']) {
						$sw='yes';
						$sw_id=$rfv ['id'];
						$sw_nr=$rfv ['document_no'];
					} elseif ($rwz ['id'] && ! $rfv ['id']) {
						$sw_id=$rwz ['id'];
						$sw='no';
					} else {
						$tmp = '';
						$sw='none';
						$sw_id='';
					}
					$t .= $tmp;
					$rrr = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecmstockdocouts where so_id='" . $r ['id'] . "' and deleted='0'" ) );
					if ($rrr ['id']) {
						
						$ed = "disabled";
						$title = 'WZ '.$rrr ['document_no'];
						$wz_idd=$rrr['id'];
					} else {
						$onclick = ' onclick="javascript:window.open(\'index.php?module=EcmStockDocOuts&amp;action=EditView&parent_doc_type=EcmSales&parent_doc_id=' . $r ['id'] . '\',\'_newtab\');"';
						$ed = "enabled";
						$title = "Create WZ";
					}
				} else {
					$rw = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecmstockdocinsideouts where ecmsale_id='" . $r ['id'] . "'" ) );
					if($rw['id']!=''){
						$rwed = "disabled";
						$rw_t = $rw ['document_no'];
						$rw_id=$rw['id'];
					} else {
						$rwonclick = ' onclick="javascript:window.open(\'index.php?module=EcmStockDocinsideOuts&amp;action=EditView&parent_doc_type=EcmSales&parent_doc_id=' . $r ['id'] . '\',\'_newtab\');"';
						$rwed = "enabled";
						$rw_t = "Utwórz RW";
					}
				}
				$result_array[$i]['wz_switch']=$ed;
				$result_array[$i]['wz_name']=$title;
				$result_array[$i]['wz_id']=$wz_idd;
				$result_array[$i]['rw_switch']=$rwed;
				$result_array[$i]['rw_name']=$rw_t;
				$result_array[$i]['rw_id']=$rw_id;
				$result_array[$i]['type']=$r['type'];
				$result_array[$i]['fv_switch']=$sw;
				$result_array[$i]['fv_id']=$sw_id;
				$result_array[$i]['fv_name']=$sw_nr;
				$result_array[$i]['products']['order_total']=$order_total;
				$result_array[$i]['products']['wz_total']=$wz_total;
				$result_array[$i]['products']['minus']=$diff_minus;
				$result_array[$i]['products']['plus']=$diff_plus;
				$result_array[$i]['position']=$i+1;
				$result_array[$i]['id']=$r['id'];
				$result_array[$i]['number']=$r['number'];
				$result_array[$i]['document_no']=$r['document_no'];
				$result_array[$i]['parent_name']=$r['parent_name'];
				$result_array[$i]['parent_id']=$r['parent_id'];
				$result_array[$i]['delivery_date']=$r['delivery_date'];
				$result_array[$i]['send_date']=$r['send_date'];
				$result_array[$i]['send_accepted']=$r['send_accepted'];
				$result_array[$i]['quantity']=$total_qty ;
				$result_array[$i]['total_netto']=$total_netto ;
				$result_array[$i]['total_brutto']=$total_brutto ;
				$result_array[$i]['total_vat']=$total_vat ;
				$result_array[$i]['total_invoice']=$total_invoice ;
				$result_array[$i]['percent']=$percent;
				$result_array[$i]['currency']=$r['currency_id'];
				
				$i++;
				$sum_total_qty += $total_qty;
				$sum_total_netto += $total_netto * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1);
				$sum_total_brutto += $total_brutto * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1);
				$sum_total_invoice += $total_invoice * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1);
				$sum_total_vat += $total_vat * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1);
				$percent = (100 * $sum_wz_qty / $sum_sale_qty);
		}
		$result_array['total_quantity']=$sum_total_qty;
		$result_array['total_netto']=$sum_total_netto;
		$result_array['total_brutto']=$sum_total_brutto;
		$result_array['total_invoice']=$sum_total_invoice;
		$result_array['total_vat']=$sum_total_vat;
		$result_array['total_percent']=$percent;
		
		$rst = 0;
		$rwt = 0;
		$diff_plus = $diff_minus = 0;
		$c1=0;
		$ww = $db->query ( "select id from ecmproducts where deleted='0' order by code asc" );
		while ( $rr = $db->fetchByAssoc ( $ww ) ) {
			$k = $rr ['id'];
			if (! $sum [$k])
				continue;
				$rpro = $db->fetchByAssoc ( $db->query ( "select code,deliverydate from ecmproducts where id='" . $k . "'" ) );
				if ($sum [$k] ['wz'] < $sum [$k] ['sale'])
					$color = "red";
					elseif ($sum [$k] ['wz'] > $sum [$k] ['sale'])
					$color = "green";
					else
						$color = "black";
						$rst += $sum [$k] ['sale'];
						$rwt += $sum [$k] ['wz'];
						
						if ($sum [$k] ['sale'] > $sum [$k] ['wz'])
							$diff_minus += $sum [$k] ['wz'] - $sum [$k] ['sale'];
							if ($sum [$k] ['sale'] < $sum [$k] ['wz'])
								$diff_plus += $sum [$k] ['wz'] - $sum [$k] ['sale'];
								
								if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00")
									$eta = $rpro ['deliverydate'];
									else
										$eta = "";
										
										$result_array['total_product'][$c1]['code']=$rpro ['code'];
										$result_array['total_product'][$c1]['id']=$k;
										$result_array['total_product'][$c1]['order']=$sum [$k] ['sale'];
										$result_array['total_product'][$c1]['wz']=$sum [$k] ['wz'];
										$result_array['total_product'][$c1]['eta']=$eta;
										$c1++;
		}
		$result_array['total_product']['order_total']=$rst;
		$result_array['total_product']['wz_total']=$rwt;
		$result_array['total_product']['minus']=$diff_minus;
		$result_array['total_product']['plus']=$diff_plus;
		
		
		return $result_array;
	}
	
	function CreateQueryFromPost($array){
		$field_array=array();
		if($array['date_from']!='')$field_array[]="delivery_date>='".date("Y-m-d",strtotime($array['date_from']))."'";
		if($array['date_to']!='')$field_array[]="delivery_date<='".date("Y-m-d",strtotime($array['date_to']))."'";
		if($array['date_send_from']!='')$field_array[]="send_date>='".date("Y-m-d",strtotime($array['date_send_from']))."'";
		if($array['date_send_to']!='')$field_array[]="send_date<='".date("Y-m-d",strtotime($array['date_send_to']))."'";
		if($array['time_from']!='')$field_array[]="date_entered>='".date("Y-m-d",strtotime($array['time_from']))."'";
		if($array['time_to']!='')$field_array[]="date_entered<='".date("Y-m-d",strtotime($array['time_to']))."'";
		if($array['account_id']!='')$field_array[]="parent_id='".$array['account_id']."'";
		if($array['account_name']!='')$field_array[]="parent_name like '".$array['account_name']."'";
		if($array['parent_order_no']!='')$field_array[]="parent_document_no='".$array['parent_order_no']."'";
		switch ($array ['sale_type']) {
			case 'all' :
				$field_array[] = "type IN ('sales_order', 'gratis')";
				break;
			case 'sale' :
				$field_array[] = "type='sales_order'";
				break;
			case 'gratis' :
				$field_array[] = "type='gratis'";
				break;
		}
		
		if (count ( $field_array ) > 0)
			$where = " and " . implode ( " and ", $field_array );
			else
				$where = "";
				$z = "select * from ecmsales where deleted='0' and status!='s10' " . $where;
				if ($array['sale_type']=='all')
					$z.=" ORDER BY type DESC";
					return $z;
	}
}
?>