<?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 EcmInvoiceOutOld 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 $currency_id;
    var $number;
    var $document_no;
    var $parent_type;
    var $parent_name;
    var $parent_id;
    var $type;
    var $ecminvoiceoutold_id;
    var $ecminvoiceoutold_name;
    var $status;
    var $register_date;
    var $sell_date;
    var $payment_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 $to_nip;
	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 $wz_id;
	var $order_no;
	var $supplier_code;
	var $delivery_place;

	var $ecmpaymentcondition_id;
	var $ecmpaymentcondition_name;
	var $ecmpaymentcondition_text;

    var $currency_symbol;

    var $parent_name_copy;
    var $parent_contact_name;
    var $parent_contact_title;	    

    var $template;

    var $pdf;

    var $position_list;

    var $parser;

    var $account;

    var $contact;

    var $user;

    var $mfp;

    var $ecminvoiceoutold;

    

    // 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        = "EcmInvoiceOutOlds";

    var $table_name        = "ecminvoiceoutolds";

    var $object_name       = "EcmInvoiceOutOld";

     

    //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'

    );

  

    function EcmInvoiceOutOld() {

      parent::SugarBean();

      $this->setupCustomFields('EcmInvoiceOutOlds');

      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  .= "ecminvoiceoutolds.*

                  ,users.user_name as assigned_user_name";

      if($custom_join) {

        $query .= $custom_join['select'];

      }

      $query   .= " FROM ecminvoiceoutolds 

                   LEFT JOIN users

                   ON ecminvoiceoutolds.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 ecminvoiceoutolds.name";

      

      return $query;

    }

  

    function create_export_query($order_by, $where) {

      

      $custom_join = $this->custom_fields->getJOIN();

      $query       = "SELECT

                      ecminvoiceoutolds.*,

                      users.user_name assigned_user_name";

      if($custom_join) {

        $query .=  $custom_join['select'];

      }

      $query   .= " FROM ecminvoiceoutolds ";

      $query   .= " LEFT JOIN users

                  ON ecminvoiceoutolds.assigned_user_id=users.id";

      if($custom_join) {

        $query .=  $custom_join['join'];

      }

      $query   .= "";

      $where_auto = " ecminvoiceoutolds.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 ecminvoiceoutolds.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 FROM ecminvoiceoutolds WHERE id='$this->id'");

      if($result) $row = $this->db->fetchByAssoc($result);
      if(is_resource($result)) {
      	$row = $this->db->fetchByAssoc($result);
      	if($row) {
      		$this->status = $row['status'];
      	}
      }

    }

  

    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, 'EcmInvoiceOutOlds');

      $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. 

      $the_array['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
      //$the_array['STATUS_IMG'] = "<img border='0' src='modules/EcmInvoiceOutOlds/images/$this->status.gif' >";
	  $the_array['STATUS'] = EcmInvoiceOutOld::CreateImgStatus($this->id,$this->status);
      $the_array['TOTAL'] = format_number($this->total);
/*
	  $the_array['PDF_URL'] = '<img border="0" id="sendemail_'.$this->id.'" src="modules/EcmInvoiceOutOlds/images/send_email_enabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON','EcmInvoiceOutOlds').'" onClick="'.$this->createSendEmailLink().'" style="cursor:pointer;" />&nbsp;';
	  $the_array['PDF_URL'] .= '<img border="0" src="modules/EcmInvoiceOutOlds/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF','EcmInvoiceOutOlds').'" onClick="EcmPreviewPDF(\'index.php?module=EcmInvoiceOutOlds&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer" />&nbsp;';

	  $the_array['PDF_URL'] .= '<img border="0" src="modules/EcmInvoiceOutOlds/images/download_enabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF','EcmInvoiceOutOlds').'" onClick="window.location=\'index.php?module=EcmInvoiceOutOlds&action=previewPDF&method=D&record='.$this->id.'&to_pdf=1\';" style="cursor:pointer"/>&nbsp;';
	  
	  if($_REQUEST['module'] != "Home" && $_REQUEST['module'] != "EcmInvoiceOutOlds")
	  	$the_array['PDF_URL'] .= '<img border="0" id="edit_'.$this->id.'" src="modules/EcmInvoiceOutOlds/images/edit_inline_enabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" onClick="javascript:window.location=\'index.php?module=EcmInvoiceOutOlds&action=EditView&record='.$this->id.'\';" style="cursor:pointer;" />';
*/      
	  $this->retrieve($this->id);
	  $the_array['OPTIONS'] = $this->ListIconsView();
	  
	  $w=$GLOBALS[db]->query("select total,ecmvat_value from ecminvoiceoutolditems where deleted='0' and ecminvoiceoutold_id='".$this->id."'");
	  while($r=$GLOBALS[db]->fetchByAssoc($w))$inv_tot+=$r['total']*(1+$r['ecmvat_value']/100);
	  $total=$inv_tot;
	  
	  if($this->ecminvoiceoutold_id){
	  	$w=$GLOBALS[db]->query("select total,ecmvat_value from ecminvoiceoutolditems where deleted='0' and ecminvoiceoutold_id='".$this->ecminvoiceoutold_id."'");
	 	while($r=$GLOBALS[db]->fetchByAssoc($w))$inv_c_tot+=$r['total']*(1+$r['ecmvat_value']/100);
		$total-=$inv_c_tot;
	  }
	  $the_array['TOTAL'] = format_number($total);
	  
	  return  $the_array;

    }


	function getEmailTemplateId($what) {
	
		$GLOBALS['db'] = new MysqlManager();
		$GLOBALS['db']->connect();
		
		$query = "SELECT `id` FROM `email_templates` WHERE `name` LIKE 'InvoiceTemplate".$what."%' LIMIT 1";
		$result = $GLOBALS['db']->query($query);
		if(is_resource($result)) {
			$row = $GLOBALS['db']->fetchByAssoc($result);
			if(is_array($row)) {
				return $row['id'];
			}
		}
		return '';
	}

	function createSendEmailLink() {
		
		require_once('modules/EcmEmails/EcmEmailsDataCreator.php');
		$eedc = new EcmEmailsDataCreator();
		if(isset($this->contact_id) && $this->contact_id != '') {
			$eedc->addToModule('Contacts', $this->contact_id);
			$eedc->setEmailTemplateId($this->getEmailTemplateId("Contact"));
		}
		else { 
			$eedc->addToModule('Accounts', $this->parent_id);
			$eedc->setEmailTemplateId($this->getEmailTemplateId("Account"));
		}
		
		global $current_user;
		
		$eedc->setFromModule('Users', $current_user->id);
		$eedc->addAssigned('Accounts', $this->parent_id);
		$eedc->addAssigned('Contacts', $this->contact_id);
		$eedc->addAssigned('EcmDocumentTemplates', $this->template_id);
		$eedc->addAssigned('Users', '');
		$eedc->addAssigned($this->module_dir, $this->id);
		
		$eedc->addAttachmentBySugar($this->createPdfFileName(), $this->module_dir, "previewPDF", array("record" => $this->id, "method" => "S", "to_pdf" => "1"), array("method" => "I"));
		return $eedc->createJavaScriptAction();
		
	}

	static function CreateImgStatus($id, $status) {
		global $app_list_strings;
		return '<span id="statusListEcmInvoiceOutOld_'.$id.'" ><img src="modules/EcmInvoiceOutOlds/images/'.$status.'.gif" title="'.$app_list_strings['ecminvoiceoutolds_status_dom'][$status].'" /></span>';
	}


    function createPdfFileName($format=true) {

	  $arr1 = Array('\\', '/', ':', '*', '?' , '"',  '<', '>', '|', ' ');

      $arr2 = Array('',  '', '',  '',  '',   '\'', '[', ']', '', '_');

      $tmp = $this->document_no;

      if($format) { 
      
        if($this->type == "normal")
          $tmp = str_replace($arr1, $arr2, 'Invoice_'.$tmp.'.pdf');
        else
        if($this->type == "correct")
          $tmp = str_replace($arr1, $arr2, 'Correct_'.$tmp.'__to_Invoice_'.$this->ecminvoiceoutold->document_no.'.pdf');
        
      
      }
      else

        $tmp = 'InvoiceOut '.$tmp.'.pdf';

      //$mod = return_module_language($current_language, 'EcmInvoiceOutOlds'); 

      //return urlencode(

//      return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//);

      return $tmp; //);

    }

  

    /**

    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::invoiceout(from_html($the_query_string));

      array_push($where_clauses, "ecminvoiceoutolds.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 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>';

		return parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect);
	}


	function generateOptions($icon,$module='',$action='') {
	
		global $app_strings,$mod_strings;
		
		$tmp  = '';
		
		if($icon == 'pdf') {
				
			//pdf
			if($this->ACLAccess('pdf_toolbar')) {
			$tmp = '<img border="0" src="modules/'.$this->module_dir.'/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF',$this->module_dir).'" onClick="EcmPreviewPDF(\'index.php?module='.$this->module_dir.'&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer" />';			
			} else {
			$tmp = '<img border="0" src="modules/'.$this->module_dir.'/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF',$this->module_dir).'" onClick="EcmPreviewPDF(\'index.php?module='.$this->module_dir.'&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:0});" style="cursor:pointer" />';			
			}
		
		} else 
		if($icon == 'download') {
				
			//download
			if($this->ACLAccess('pdf_toolbar')) {
			$tmp = '<img border="0" src="modules/'.$this->module_dir.'/images/download_enabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF',$this->module_dir).'" onClick="window.location=\'index.php?module='.$this->module_dir.'&action=previewPDF&method=D&record='.$this->id.'&to_pdf=1\';" style="cursor:pointer"/>';			
			} else {
			$tmp = '<img border="0" src="modules/'.$this->module_dir.'/images/download_disabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF',$this->module_dir).'"/>';			
			}
		
		} else		
		
		if($icon == 'duplicate') {
		
			//duplicate
			$tmp = '<a href="index.php?module='.$this->module_dir.'&action=EditView&record='.$this->id.'&isDuplicate=true"><img border="0" src="modules/'.$this->module_dir.'/images/duplicate.jpg" title="'.translate('LBL_LIST_DUPLICATE',$this->module_dir).'" /></a>';
		
		} else 
		if($icon == 'edit') {
		
			//edit
			if($this->ACLAccess('edit') && $this->status=="registered") 
				$tmp = '<img border="0" id="edit_'.$this->id.'" src="modules/'.$this->module_dir.'/images/edit_inline_enabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" onClick="javascript:window.location=\'index.php?module='.$this->module_dir.'&action=EditView&record='.$this->id.'&return_module='.$_REQUEST['module'].'&return_action='.$_REQUEST['action'].'&return_id='.$_REQUEST['record'].'\';" style="cursor:pointer;" />';
			else
				$tmp = '<img border="0" id="edit_'.$this->id.'" src="modules/'.$this->module_dir.'/images/edit_inline_disabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" />';	
		
		} else
		if($icon == 'send_email') {
			//send_email
			if($this->status=="accepted") 
				$tmp = '<img border="0" id="sendemail_'.$this->id.'" src="modules/'.$this->module_dir.'/images/send_email_enabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON',$this->module_dir).'" onClick="'.$this->createSendEmailLink().'" style="cursor:pointer;" />';
			else
				$tmp = '<img border="0" id="sendemail_'.$this->id.'" src="modules/'.$this->module_dir.'/images/send_email_disabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON',$this->module_dir).'" style="cursor:pointer;" />';	
		
		} else
		if($icon == 'correct') {
			if($this->status!="registered")$tmp = '<a href="index.php?module='.$this->module_dir.'&offset=1&return_module='.$this->module_dir.'&action=EditView&return_action=index&record='.$this->id.'&isCorrect=true"><img border="0" src="modules/'.$this->module_dir.'/images/correct.jpg" title="'.$mod_strings['LBL_CORRECT_TITLE'].'" /></a>';
			else $tmp='<img border="0" src="modules/'.$this->module_dir.'/images/correct_disabled.jpg" title="'.$mod_strings['LBL_CORRECT_TITLE'].'" style="cursor:pointer;" />';
		} else if($icon == 'view') {
			$tmp = '<img border="0" src="themes/Sugar/images/view_inline.gif" style="cursor: pointer;" onClick="javascript:window.location=\'index.php?module='.$this->module_dir.'&action=DetailView&record='.$this->id.'&return_module='.$_REQUEST['module'].'&return_action='.$_REQUEST['action'].'&return_id='.$_REQUEST['record'].'\';" title="'.$mod_strings['LBL_DETAIL_BUTTON'].'" />';
		}
		
				
		return $tmp;
	}

	function ListIconsView() {

		if(isset($_REQUEST['module']) && $_REQUEST['module'] != '' && isset($_REQUEST['action'])) {
			$module = $_REQUEST['module'];
			$action = $_REQUEST['action'];
			
			$glue = "&nbsp;";
			$viewIcons = array();
			if($module == $this->module_dir){ //This module, action ListView or index
				$viewIcons = array( 'send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
				if($this->status=="registered") $viewIcons = array('send_email', 'download', 'correct','pdf', 'duplicate', 'edit' );
			}
			else
			if($module == "Home") { //This is for a Home module for Dashlets
				$glue = "&nbsp;";
				$viewIcons = array( 'send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
				if($this->status=="registered") $viewIcons = array('send_email', 'download', 'correct','pdf', 'duplicate', 'edit' );
			} else { //this is for subpanels, popups
				$glue = "&nbsp;";
				$viewIcons = array( 'send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
				if($this->status=="registered") $viewIcons = array('send_email', 'download', 'correct','pdf', 'duplicate', 'edit' );
			}
			
			$arr = array();
			foreach($viewIcons as $value) {
				$tmp = $this->generateOptions($value);
				if($tmp != '') $arr[] = $tmp;
			}
			
			return '<span id="optionsList'.$this->object_name.'_'.$this->id.'">'.implode($glue,$arr).'<script language="javascript">var List'.$this->module_dir.'Module="'.$module.'"; var List'.$this->module_dir.'Action="'.$action.'";</script></span>';
		}
		return '';
	}
	
	
    function save($check_notify = FALSE)  {
      
      global $current_user;
      if(($this->fetched_row && $this->fetched_row['template_id'] != $this->template_id) || (empty($this->id) || $this->id == '')) {
	  	if($this->type=="normal"){
			$this->number = $this->generateNumber(); 
      		$this->document_no = $this->formatNumber();
		}
		else{
			$this->number = $this->generateNumberCorrect(); 
      		$this->document_no = $this->formatNumberCorrect();
		}
	  }

      if($this->status == 'accepted' && $current_user->getPreference('confirm_invoiceouts')){ $this->accepted = 1; } else { $this->accepted = 0; }
      if($this->status == 'not_accepted' && $current_user->getPreference('confirm_invoiceouts')){ $this->accepted = 0; }

	  $this->ecmpaymentcondition_text = EcmInvoiceOutOld::getTranslation('EcmPaymentConditions',$this->ecmpaymentcondition_id,$this->ecmlanguage);
	  $this->ecmdeliverycondition_text = EcmInvoiceOutOld::getTranslation('EcmDeliveryConditions',$this->ecmdeliverycondition_id,$this->ecmlanguage);
      $return_id = parent::save($check_notify);

	  if($this->type=="correct" && $this->status=="accepted"){
	  	$cor=new EcmInvoiceOutOld();
	  	$cor->retrieve($this->ecminvoiceoutold_id);
	  	$cor_pl=$cor->getPositionList(true);
	  	$nor_pl=$this->position_list;
	  
	  	$cor_prod=array();
	  	for($i=0;$i<count($cor_pl);$i++){
	  		$cor_prod[$cor_pl[$i]['id']]+=$cor_pl[$i]['quantity'];
	  	}
	  	$nor_prod=array();
	  	for($i=0;$i<count($nor_pl);$i++){
	  		$nor_prod[$nor_pl[$i]['id']]+=$nor_pl[$i]['quantity'];
	  	} 
	  
	  	$diff_prod=array();
	  	for($i=0;$i<count($nor_pl);$i++){
	  		$diff_prod[$nor_pl[$i]['id']]=$nor_prod[$nor_pl[$i]['id']]-$cor_prod[$nor_pl[$i]['id']];
	  	}
	  	for($i=0;$i<count($cor_pl);$i++){
	  		$diff_prod[$cor_pl[$i]['id']]=$nor_prod[$cor_pl[$i]['id']]-$cor_prod[$cor_pl[$i]['id']];
	  	}
		
		$n=0;
		$r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select wz_id from ecminvoiceoutolds where id='".$this->ecminvoiceoutold_id."'"));
		$wz_id=$r['wz_id'];
		if(count($diff_prod)>0){
			foreach($diff_prod as $k=>$v){
				if($v!=0){
					$n++;
					$rr=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select price from ecmstockdocoutitems where ecmstockdocout_id='".$wz_id."' and ecmproduct_id='".$k."' and deleted='0'"));
					$rr=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select price from ecmstockoperations where parent_id='".$wz_id."' and product_id='".$k."' and deleted='0'"));
					
					$r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select code,name,unit_id,id,vat_id,vat_name,vat_value from ecmproducts where id='".$k."' and deleted='0'"));
					$prod[]=array(
						"position"=>$n,
						"id"=>$k,
						"price"=>$rr['price'],
						"code"=>$r['code'],
						"name"=>$r['name'],
						"quantity"=>(-1*$v),
						"unit_id"=>$r['unit_id'],
						"vat_id"=>$r['vat_id'],
						"vat_name"=>$r['vat_name'],
						"vat_value"=>$r['vat_value'],
					);
				}
			}
		}
		if(count($prod)>0){
		require_once("modules/EcmStockDocCorrects/EcmStockDocCorrect.php");
		$cor=new EcmStockDocCorrect();
	  	$cor->number=$cor->generateNumber(); 
      	$cor->document_no=$cor->formatNumber();
		$cor->unformat_all_fields();
		$r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select wz_id from ecminvoiceoutolds where id='".$this->ecminvoiceoutold_id."'"));
		$r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select stock_id from ecmstockdocouts where id='".$r['wz_id']."'"));
		$cor->stock_id=$r['stock_id'];
		if(!$cor->stock_id)$cor->stock_id="c7afd71a-4c3a-bde4-138d-4acaee1644e4";
		$cor->register_date=$GLOBALS['timedate']->to_db_date(date("Y-m-d"));
		$cor->ecmlanguage="pl_pl";
		$cor->currency_id="PLN";
		$cor->status="accepted";
		$cor->show_images_on_offer=0;
		$cor->assigned_user_id=$current_user->id;
		$cor->subtotal=0;
		$cor->total=0;
		$cor->position_list=$prod;
		$cor->template_id=$this->template_id;
		$r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select name from ecmtemplates where id='".$this->template_id."'"));
		$cor->template_name=$r['name'];
		$corid=$cor->save();
		$GLOBALS[db]->query("update ecmstockdoccorrects set date='".date("Y-m-d")."' where id='".$corid."'");
		}
	  }

	  $this->savePositions($return_id);
	  
	  if($this->type=="correct"){
	  	$w=$GLOBALS[db]->query("select total from ecminvoiceoutolditems where ecminvoiceoutold_id='".$this->ecminvoiceoutold_id."' and deleted='0'");
		while($r=$GLOBALS[db]->fetchByAssoc($w))$nor_total+=$r['total'];
	  	$w=$GLOBALS[db]->query("select total from ecminvoiceoutolditems where ecminvoiceoutold_id='".$return_id."' and deleted='0'");
		while($r=$GLOBALS[db]->fetchByAssoc($w))$cor_total+=$r['total'];
		$GLOBALS[db]->query("update ecminvoiceoutolds set total='".($cor_total-$nor_total)."' where id='".$return_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;
		
		for($i = 0; $i < count($position_list); $i ++) {   

			if($position_list[$i]['name'] == '') continue;
			
			$p = $position_list[$i];
			require_once("modules/EcmVats/EcmVat.php");
			$vats = new EcmVat();
			$vats->retrieve($p['vat_id']);
			$p['vat_name'] = $vats->name;

			require_once("modules/Currencies/Currency.php");
			$curr = new Currency();
			$curr->retrieve($p['currency_id']);
			$p['currency_name'] = $curr->name;

			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;	
			}
			
			$lv=return_app_list_strings_language($this->ecmlanguage);
			
			$r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select price from ecmstockdocoutitems where ecmproduct_id='".$r['id']."' and ecmstockdocout_id='".$this->wz_id."'"));
			$purchase_price=$r['price'];
			
			$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['id'],
				'position' => $position,
				'code' => $p['code'],
				'name' => $p['name'],
				'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
				'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
				'purchase_price' => $purchase_price,
				'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
				'total' => ((empty($p['total']) || $p['total'] == '') ? 0 : $p['total']),
				'dd_unit_id' => $p['unit_id'],
				'dd_unit_name' => $lv['ecmproducts_unit_dom'][$p['unit_id']],
				'ecmvat_id' => $p['vat_id'],
				'ecmvat_name' => $p['vat_name'],
				'ecmvat_value' => $p['vat_value'],
				'ecmproductcategory_id' => $p['category_id'],
				'currency_id' => $p['currency_id'],
				'currency_name' => $p['currency_name'],
				'tax_code' => $p['tax_code'],
				'recipient_code' => $p['recipient_code'],
				
			);

			$this->db->query($this->constructInsertQuery($arr));
			$position ++;
		}	
		
	}
	function getPosition($position) {

		if(!is_array($position)) return '';

		global $timedate;
		
		$return_array = array();
		$return_array['id'] = $position['ecmproduct_id'];
		$return_array['position'] = $position['position'];
		$return_array['code'] = $position['code'];
		$return_array['name'] = $position['name'];
		$return_array['quantity'] = $position['quantity'];
		$return_array['price'] = $position['price'];
		$return_array['discount'] = $position['discount'];
		$return_array['total'] = $position['total'];
		$return_array['unit_id'] = $position['dd_unit_id'];
		$return_array['unit_name'] = $position['dd_unit_name'];
		$return_array['vat_id'] = $position['ecmvat_id'];
		$return_array['vat_name'] = $position['ecmvat_name'];
		$return_array['vat_value'] = $position['ecmvat_value'];
		$return_array['category_id'] = $position['ecmproductcategory_id'];
		$return_array['currency_id'] = $position['currency_id'];
		$return_array['currency_name'] = $position['currency_name'];
		$return_array['tax_code'] = $position['tax_code'];
		$return_array['recipient_code'] = $position['recipient_code'];
		return $return_array;
		
	}
    function getPositionList($array = 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);
          }
          $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;          
    }
//***************************End Managing Positions*************************//

    static function getTranslation($module,$id,$language) {
		if(isset($id) && $id != '' && isset($module) && $module != '') {
			global $beanList, $beanFiles;
			$file = $beanFiles[$beanList[$module]];
			if(file_exists($file)) {
				require_once($file);
				$bean = new $beanList[$module]();
				$bean->retrieve($id);
				if(isset($bean->id) && $bean->id != '') {
				  if(isset($bean->translations[$language]) && $bean->translations[$language] != '') return $bean->translations[$language];
				}
			}
		}
		return null;
	}
    

    function getTemplateList() {

      $query = "select `id`,`name` from `ecmdocumenttemplates` where `deleted`='0' order by `name`";

      $result = $GLOBALS[db]->query($query);

      $arr = array();

      if($result)

        while($row = mysql_fetch_assoc($result))

          $arr[$row['id']] = $row['name'];

      return $arr;

    } 

    

    function setTemplate() {

      if(!isset($this->template_id) || $this->template_id == '') return null;

      if(isset($this->template)) return $this->template;

      

      require_once('modules/EcmDocumentTemplates/EcmDocumentTemplate.php');

      $this->template = new EcmDocumentTemplate();

      //$this->template->retrieve($this->template_id);
	  $this->template->retrieve($this->template_id, true, false);


      if(isset($this->template->id) && $this->template->id != '') {

        $this->template->format_all_fields();

      } 

      else

        $this->template = null;

        

      return $this->template;

    }

	function generateNumber() {
	  $this->setTemplate();
      $this->number = isset($this->template) ? $this->template->generateNumber($this->table_name) : '';
      return $this->number;
    }  

    function formatNumber() {
      $this->setTemplate();
      $this->document_no = isset($this->template) ? $this->template->formatNumber($this->number, $this->module_dir) : ''; 
      return $this->document_no;
    }   
    function generateNumberCorrect() {
	  $this->setTemplate();
      $this->number = $this->template->generateNumberCorrect($this->table_name);
      return $this->number;
    }  

    function formatNumberCorrect() {
      $this->setTemplate();
      $this->document_no = $this->template->formatNumberCorrect($this->number, $this->module_dir); 
      return $this->document_no;
    }   

    function formatDocumentNumber($documentNumber = '', $code = '') {
      return isset($this->template) ? $this->template->formatDocumentNumber($documentNumber, $code) : ''; 
    }
        
    function DrawPositions($pdf = null) {
	  global $mod_strings;
	  
	  $currency = new Currency();
	  $currency->retrieve($this->currency_id);
	  $this->currency_symbol=$currency->iso4217;
	  
      if(!isset($this->position_list) || !is_array($this->position_list))
        $this->position_list = $this->getPositionList(true);
      $calc = $this->calculate($this->position_list,true);
      //$this->position_list = $this->formatPositions($this->position_list);
      
      $calc['total'] .= ' '.$this->currency_symbol;
      $calc['subtotal'] .= ' '.$this->currency_symbol;
      if($calc['discount']) {
        $calc['total2'] .= ' '.$this->currency_symbol;
        $calc['discount']['value'] .= ' '.$this->currency_symbol;
      }
      
      if(isset($calc['vats']) && is_array($calc['vats']) && count($calc['vats']) > 0)
        foreach($calc['vats'] as $key => $value) $calc['vats'][$key] .= ' '.$this->currency_symbol;

      $name_w = 22;
      //if($calc['draw_discount']) $name_w -= 8;
      //if($calc['draw_vat']) $name_w -= 8;
      $table = array(); 
      $table [0]['position'] = array('width' => 4, 'value' => $mod_strings['LBL_PDF_LIST_POSITION'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 8);
      $table [0]['description'] = array('width' => $name_w, 'value' => $mod_strings['LBL_PDF_LIST_DESCRIPTION'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
      $table [0]['tax_code'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_TAX_CODE'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
      $table [0]['quantity'] = array('width' => 7, 'value' => $mod_strings['LBL_PDF_LIST_QUANTITY'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
      $table [0]['unit'] = array('width' => 5, 'value' => $mod_strings['LBL_PDF_LIST_UNIT'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 8);
      $table [0]['unit_price'] = array('width' => 10, 'value' => $mod_strings['LBL_PDF_LIST_PRICE'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
      $table [0]['unit_price_total'] = array('width' => 12, 'value' => $mod_strings['LBL_PDF_LIST_TOTAL_PRICE'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
      //if($calc['draw_discount']) $table [0]['discount'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_DISCOUNT'], 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
      //if($calc['draw_vat']) {
	  	$table [0]['vat_id'] = array('width' => 5, 'value' => $mod_strings['LBL_PDF_LIST_VAT'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
	  	$table [0]['vat_value'] = array('width' => 13, 'value' => $mod_strings['LBL_PDF_LIST_VAT_VALUE'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
	  //}
      $table [0]['total'] = array('width' => 14, 'value' => $mod_strings['LBL_PDF_LIST_TOTAL'],'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
	  $pdf->DrawTable($table,array(0));
	  $pdf->Ln(0);
	  
	  
      $i = 1;
	  
	  $table=array();
      if($this->position_list != '')
      foreach($this->position_list as $p) {
        $table [$i]['position'] = array('width' => 4, 'value' => $i, 'border' => 1, 'align' => 'R', 'font-size' => 7 );
        $table [$i]['description'] = array('width' => $name_w, 'value' => htmlspecialchars_decode($p['name']), 'border' => 1, 'align' => 'L', 'font-size' => 7 );
		$table [$i]['tax_code'] = array('width' => 8, 'value' => $p['tax_code'],'border' => 1, 'align' => 'C', 'font-size' => 7);
        $table [$i]['quantity'] = array('width' => 7, 'value' => $p['quantity'], 'border' => 1, 'align' => 'C', 'font-size' => 7 );
        $table [$i]['unit'] = array('width' => 5, 'value' => $GLOBALS['app_list_strings']['ecmproducts_unit_dom'][$p['unit']], 'border' => 1, 'align' => 'C', 'font-size' => 7 );
        $table [$i]['unit_price'] = array('width' => 10, 'value' => $p['price'], 'border' => 1, 'align' => 'R', 'font-size' => 7 );
		$price_total=$p['price']*$p['quantity'];
        $table [$i]['unit_price_total'] = array('width' => 12, 'value' => ($price_total), 'border' => 1, 'align' => 'R', 'font-size' => 7 );
        //if($calc['draw_discount']) $table [$i]['discount'] = array('width' => 8, 'value' => $p['discount'], 'border' => 0, 'align' => 'R', 'font-size' => 7 );
        //if($calc['draw_vat']){
			$table [$i]['vat_id'] = array('width' => 5, 'value' => ($p['vat_value']), 'border' => 1, 'align' => 'R', 'font-size' => 7 );
			$vat_value=$p['vat_value']/100*$p['price']*$p['quantity'];
			$table [$i]['vat_value'] = array('width' => 13, 'value' => ($vat_value), 'border' => 1, 'align' => 'R', 'font-size' => 7 );
			
		//}
        $table [$i]['total'] = array('width' => 14, 'value' => ($price_total+$vat_value), 'border' => 1, 'align' => 'R', 'font-size' => 7 );
		$totals[$p['vat_id']]['price']+=$price_total;
		$totals[$p['vat_id']]['total']+=$price_total+$vat_value;
		$totals[$p['vat_id']]['vat']+=$vat_value;
        $i++;
      }

      $pdf->DrawTable($table,array(0));
      //total, vat, subtotal
	  
      $pdf->Ln(4);
      $pr = ($pdf->fw-$pdf->lMargin-$pdf->rMargin)/100;
      //$pdf->SetX($pdf->fw-$pdf->rMargin-$pr*34);
      $table = array();    

      if($calc['vats']) {  
        /*$table [] = array(
          'subtotal1' => array('width' => 42, 'value' => $mod_strings['LBL_PDF_TOTAL'], 'background' => array(255,255,255), 'border' => 1, 'overflow' => 1, 'align' => 'L', 'font-size' => 7),
          'subtotal2' => array('width' => 14, 'value' => $calc['subtotal'].' PLN', 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7), );
*/
        foreach($calc['vats'] as $key => $value){
		  $r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select id,name,value from ecmvats where id='".$key."'"));
		  $vvn=$r['name'];
          $table [] = array(
            'vat1' => array('width' => 10, 'value' => $mod_strings['LBL_PDF_VAT'].' ('.$vvn.')', 'background' => array(255,255,255), 'border' => 1, 'overflow' => 1, 'align' => 'L', 'font-size' => 7),
            'netto_total' => array('width' => 12, 'value' => format_number($totals[$r['id']]['price']), 'background' => array(255,255,255), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),
            'vat_rate' => array('width' => 5, 'value' => format_number($r['value']), 'background' => array(255,255,255), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),
            'vat_total' => array('width' => 13, 'value' => format_number($totals[$r['id']]['vat']), 'background' => array(255,255,255), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),
            'vat2' => array('width' => 14, 'value' => format_number($totals[$r['id']]['total']), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7), );
		}
      }

      if(isset($calc['discount'])) {
        $table [] = array(
          'total21' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_TOTAL'], 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 7, 'font-style' => 'b'),
          'total22' => array('width' => 34, 'value' => $calc['total2'], 'border' => 0, 'overflow' => 1, 'align' => 'R' , 'font-size' => 7), );
        $table [] = array(
          'discount1' => array('width' => 86, 'value' => $mod_strings['LBL_PDF_DISCOUNT'].' '.$calc['discount']['procent'], 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 7, 'font-style' => 'b'),
          'discount2' => array('width' => 14, 'value' => $calc['discount']['value'], 'border' => 0, 'overflow' => 1, 'align' => 'R' , 'font-size' => 7), );
      } 
	  $table [] = array(
        'total1' => array('width' => 40, 'value' => $mod_strings['LBL_PDF_END_TOTAL'], 'border' => 1, 'overflow' => 1, 'align' => 'L', 'font-size' => 7, 'font-style' => 'b'),
        'total2' => array('width' => 14, 'value' => $calc['total'], 'border' => 1, 'overflow' => 1, 'align' => 'R' , 'font-size' => 7, 'font-style' => 'b'), );
	  $pdf->SetX(103);
      $pdf->DrawTable($table);
	  $pdf->Ln(1);
		
	  //$table=array();
      
      //$pdf->DrawTable($table);
    }   



    function DrawMainPDF($pdf) {


	  global $mod_strings;
	  
	  $arr=$this->template->getTemplateFile($_REQUEST['module']);
	  
	  include_once("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subheader.php");
	  /*
	  $pdf->SetFont('arialpl','','7');
      $this->DrawPositions($pdf);
	  */
	  include_once("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subfooter.php");
    }





    function getPDF($id = null,$method = 'I',$name = null) {
	
      global $sugar_config;

      if($id != null) {

        $this->retrieve($id);

        if($this->id == '') return;

      }

      global $mod_strings;
	  require_once('modules/EcmTexts/EcmText.php');
	  if(isset($this->ecmlanguage) && $this->ecmlanguage != '') {
		  $data = EcmText::LoadText(null,null,"EcmInvoiceOutOlds",$this->ecmlanguage);
		  if(isset($data[0]) && isset($data[0]['data']) && isset($data[0]['data']['labels'])) {
			$data = $data[0]['data']['labels'];
			foreach($data as $key => $value) {
				$mod_strings[$value['label']] = $value['translation'];
			}
		  }
	  }

      $this->format_all_fields();

      $this->setTemplate();


      if(isset($this->template->id) && $this->template->id != '') {

        $this->template->setPDF($this->template_id);
	 $this->template->pdf->SetAutoPageBreak(true,40);
        $this->DrawMainPDF($this->template->pdf);

        $this->template->outputPDF((($name) ? $name : $this->createPdfFileName()),$method);

      }

    }  

   

   function calculate($position_list, $format = false) {

      if(!is_array($position_list)) return false;

      $result = Array('total' => 0.0, 'vats' => false, 'subtotal' => 0.0, 'draw_vat' => false, 'draw_discount' => false);

      $vats = Array();

      

      foreach($position_list as $p) {

        if(!isset($vats[$p['vat_id']])) $vats[$p['vat_id']] = 0;

        $vats[$p['vat_id']] += floatval($p['total']);

        $result['subtotal'] += floatval($p['total']);

        if(!$result['draw_discount'] && floatval($p['discount']) > 0) $result['draw_discount'] = true;

      }

      

      $result['total'] = $result['subtotal'];

  

      if(!$this->to_is_vat_free) {

        $vats2 = Array();

        foreach($vats as $key => $value) {
		  $r=$GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select value from ecmvats where id='".$key."'"));
		  $vva=$r['value'];

          if(!$format) $vats2[$key] = floatval($value)*(floatval($vva)/100); 
		  else $vats2[$key] = format_number(floatval($value)*(floatval($vva)/100));        

          $result['total'] += floatval($value)*(floatval($vva)/100);
		  //print $result['total']."<br>";

        }
		$this->total=$result['total'];
		//die();
        asort($vats2,SORT_NUMERIC);

        $result['vats'] = $vats2;

        if(count($result['vats'])>1) $result['draw_vat'] = true;

      }
      
      $discount = $this->discount;
      if(!is_float($discount)) $discount = unformat_number($discount);

      if(isset($discount) && $discount != 0 && $discount != '') {
        $result['discount'] = array (
          'procent' => format_number(floatval($discount)).'%',
          'value' => $result['subtotal']*$discount/100,
        );
        $result['total2'] = $result['total'];
        $result['total'] = $result['total']-$result['discount']['value']; 
      }

      if($format) {
      
        if(isset($result['discount']) && isset($result['discount']['value']) && $result['discount']['value'] != '' && $result['discount']['value'] != 0) {
          $result['discount']['value'] = format_number($result['discount']['value']);
          $result['total2'] = format_number($result['total2']);
        }
      
        $result['total'] = format_number($result['total']); 

        $result['subtotal'] = format_number($result['subtotal']);

      }

      

      return $result;

    }



    function formatPositions($position_list) {

      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]['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;

        $this->currency_symbol = $currency->iso4217;
      }
      return $position_list;

    }



    function loadParser() {
      $this->template->mfp->clear();
      $this->template->mfp->add("EcmQuotes","quote_",$this);
      $this->template->mfp->add("Users","user_",$this->setUser());
      if($this->setAccount() != null)
        $this->template->mfp->add("Accounts",'account_',$this->account);
      if($this->setContact() != null)
        $this->template->mfp->add("Contacts",'contact_',$this->contact);
      $this->template->mfp->add("EcmDocumentTemplates","documenttemplate_",$this->template);
    }
     
    function loadParserArray($name = '') {
      require_once('modules/EcmDocumentTemplates/ModuleFieldsParser/ModuleFieldsParser.php');
      $mfp = new ModuleFieldsParser();
      $mfp->clear();

      global $app_list_strings;

      $mfp->add("EcmInvoiceOutOlds","invoiceout_",'',$app_list_strings['moduleList']['EcmInvoiceOutOlds']);
      $mfp->add("Users","user_",'',$app_list_strings['moduleList']['Users']);
      $mfp->add("Accounts",'account_','',$app_list_strings['moduleList']['Accounts']);
      $mfp->add("Contacts",'contact_','',$app_list_strings['moduleList']['Contacts']);
      $mfp->add("EcmDocumentTemplates","documenttemplate_",'',$app_list_strings['moduleList']['EcmDocumentTemplates']);
      
      if($name == '') {
        $mfp_arr = array(
          'header' => $mfp->getFormHTML(false, 'header'),
          'footer' => $mfp->getFormHTML(false, 'footer'),
          'ads' => $mfp->getFormHTML(false, 'ads'),
        );
      } else $mfp_arr = $mfp->getFormHTML(false,$name);
      return $mfp_arr;
    }

    

    function setAccount() {
        require_once('modules/Accounts/Account.php');
        $this->account = new Account();
        $this->account->retrieve($this->parent_id);
        return $this->account;
    }
    function setContact() {
      require_once('modules/Contacts/Contact.php');
      $us = new Contact();
      $us->retrieve($this->contact_id);
      $this->contact = $us;
      return $this->contact;
    }

    function setUser() {
      if(is_object($this->user)) return $this->user;
      require_once('modules/Users/User.php');
      $us = new User();
      global $current_user;
      $us->retrieve(($this->assigned_user_id)?$this->assigned_user_id:$current_user->id);
      if(isset($us->id) && $us->id != '') {
        $this->user = $us;
      } 
      else
        $this->user = null;
      return $this->user;
    }
	
    function doNotAccepted() {
      global $current_user;
      $cq = $current_user->getPreference('confirm_invoiceouts');
      if(isset($cq) && $cq) {
        $query = "UPDATE `ecminvoiceoutolds` SET `status` = 'not_accepted',`accepted` = '0' WHERE CONVERT( `id` USING utf8 ) = '".$this->id."' LIMIT 1 ;";
        $result = $this->db->query($query);
        if($result) {
          $this->status = 'not_accepted';
          $this->accepted = 0;
        }
      }  
    }

    function loadEcmInvoiceOutOld() {
      $this->ecminvoiceoutold = new EcmInvoiceOutOld();
      if(isset($this->ecminvoiceoutold_id) && $this->ecminvoiceoutold_id != ''){
        $this->ecminvoiceoutold->retrieve($this->ecminvoiceoutold_id);
      }
    }
	function slownieEN($kw){
		
	}
	function slowniePL($kw)
	{
		$t_a = array('','sto','dwieście','trzysta','czterysta','pięćset','sześćset','siedemset','osiemset','dziewięćset');
		$t_b = array('','dziesięć','dwadzieścia','trzydzieści','czterdzieści','pięćdziesiąt','sześćdziesiąt','siedemdziesiąt','osiemdziesiąt','dziewięćdziesiąt');
		$t_c = array('','jeden','dwa','trzy','cztery','pięć','sześć','siedem','osiem','dziewięć');
		$t_d = array('dziesięć','jedenaście','dwanaście','trzynaście','czternaście','piêtnaście','szesnaście','siedmnaście','osiemnaście','dziewiętnaście');

		$t_kw_15 = array('septyliard','septyliardów','septyliardy');
		$t_kw_14 = array('septylion','septylionów','septyliony');
		$t_kw_13 = array('sekstyliard','sekstyliardów','sekstyliardy');
		$t_kw_12 = array('sekstylion','sekstylionów','sepstyliony');
		$t_kw_11 = array('kwintyliard','kwintyliardów','kwintyliardy');
		$t_kw_10 = array('kwintylion','kwintylionów','kwintyliony');
		$t_kw_9 = array('kwadryliard','kwadryliardów','kwaryliardy');
		$t_kw_8 = array('kwadrylion','kwadrylionów','kwadryliony');
		$t_kw_7 = array('tryliard','tryliardów','tryliardy');
		$t_kw_6 = array('trylion','trylionów','tryliony');
		$t_kw_5 = array('biliard','biliardów','biliardy');
		$t_kw_4 = array('bilion','bilionów','bilony');
		$t_kw_3 = array('miliard','miliardów','miliardy');
		$t_kw_2 = array('milion','milionów','miliony');
		$t_kw_1 = array('tysiąc','tysięcy','tysiące');
		$t_kw_0 = array('złoty','złotych','złote');

  		if($kw!='')
		{
    		$kw=(substr_count($kw,',')==0) ? $kw.',00':$kw;
    		$tmp=explode(",",$kw);
    		$ln=strlen($tmp[0]);
    		$tmp_a=($ln%3==0) ? (floor($ln/3)*3):((floor($ln/3)+1)*3);
    		for($i = $ln; $i < $tmp_a; $i++)
			{
      			$l_pad .= '0';
      			$kw_w = $l_pad . $tmp[0];
    		}
    		$kw_w=($kw_w=='') ? $tmp[0]:$kw_w;
    		$paczki=(strlen($kw_w)/3)-1;
    		$p_tmp=$paczki;
    		for($i=0;$i<=$paczki;$i++)
			{
     			$t_tmp='t_kw_'.$p_tmp;
      			$p_tmp--;
      			$p_kw=substr($kw_w,($i*3),3);
      			$kw_w_s=($p_kw{1}!=1) ? $t_a[$p_kw{0}].' '.$t_b[$p_kw{1}].' '.$t_c[$p_kw{2}]:$t_a[$p_kw{0}].' '.$t_d[$p_kw{2}];
      			if(($p_kw{0}==0)&&($p_kw{2}==1)&&($p_kw{1}<1)) $ka=${$t_tmp}[0]; //mozliwe ze $p_kw{1}!=1
      			else if (($p_kw{2}>1 && $p_kw{2}<5)&&$p_kw{1}!=1) $ka=${$t_tmp}[2];
     			else $ka=${$t_tmp}[1];
      			$kw_slow.=$kw_w_s.' '.$ka.' ';
    		}	
  		}
		if($kw<1000000 && eregi("milion",$kw_slow))
		{
			
			$kw_slow=substr($kw_slow,11,strlen($kw_slow));
		}
 		$text = $kw_slow.' '.$tmp[1].'/100 gr.';
  		return $text;
	}

  }

?>