<?php
	/**
	* phpGroupWare - property: a Facilities Management System.
	*
	* @author Sigurd Nes <sigurdne@online.no>
	* @copyright Copyright (C) 2003,2004,2005,2006,2007 Free Software Foundation, Inc. http://www.fsf.org/
	* This file is part of phpGroupWare.
	*
	* phpGroupWare is free software; you can redistribute it and/or modify
	* it under the terms of the GNU General Public License as published by
	* the Free Software Foundation; either version 2 of the License, or
	* (at your option) any later version.
	*
	* phpGroupWare is distributed in the hope that it will be useful,
	* but WITHOUT ANY WARRANTY; without even the implied warranty of
	* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	* GNU General Public License for more details.
	*
	* You should have received a copy of the GNU General Public License
	* along with phpGroupWare; if not, write to the Free Software
	* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
	*
	* @license http://www.gnu.org/licenses/gpl.html GNU General Public License
	* @internal Development of this application was funded by http://www.bergen.kommune.no/bbb_/ekstern/
	* @package property
	* @subpackage export
 	* @version $Id: Basware_X114 6597 2010-11-15 21:48:48Z sigurdne $
	*/

	/**
	 * Description
	 * @package property
	 */

	phpgw::import_class('phpgwapi.datetime');

	class export_conv
	{
		//var $fil_katalog='c:/temp'; //On windows use "//computername/share/filename" or "\\\\computername\share\filename" to check files on network shares.
		
		var $debug;
		var $client_code = 14;
		
		function  __construct()
		{
			$GLOBALS['phpgw_info']['flags']['currentapp']	=	'property';
			$this->currentapp		= $GLOBALS['phpgw_info']['flags']['currentapp'];
			$this->db 				= & $GLOBALS['phpgw']->db;
			$this->join				= & $this->db->join;

			$this->soXport 			= CreateObject('property.soXport');	
			$this->config			= CreateObject('phpgwapi.config','property');
			$this->config->read_repository();
		}

		protected function select_vouchers_to_transfer()
		{
			if(isset($this->config->config_data['invoice_approval']) && $this->config->config_data['invoice_approval']== 1)
			{
				$sql= 'SELECT DISTINCT bilagsnr from fm_ecobilag WHERE budsjettsigndato IS NOT NULL AND utbetalingsigndato IS NOT NULL';
			}
			else
			{
				$sql= 'SELECT DISTINCT bilagsnr from fm_ecobilag WHERE budsjettsigndato IS NOT NULL AND (saksigndato IS NOT NULL OR oppsynsigndato IS NOT NULL) AND utbetalingsigndato IS NOT NULL';
			}
			$this->db->query($sql,__LINE__,__FILE__);
			$vouchers = array();
			while ($this->db->next_record())
			{
				$vouchers[]	= $this->db->f('bilagsnr');
			}
			return $vouchers;
		}

		protected function log_end($batchid)
		{
			$tid=date($this->soXport->datetimeformat);
			$sql= "insert into fm_ecologg (batchid,melding,tid) values ('$batchid','End transfer','$tid')";
			$this->db->query($sql,__LINE__,__FILE__);
		}

		protected function log_error($batchid,$error_desr)
		{
			$tid = date($this->soXport->datetimeformat);
			$sql = "INSERT INTO fm_ecologg (batchid,ecobilagid,status,melding,tid) VALUES ('$batchid',NULL,0,'$error_desr','$tid')";
			$this->db->query($sql,__LINE__,__FILE__);
		}

		protected function increment_batchid()
		{
			$this->db->query("UPDATE fm_idgenerator SET value = value + 1 WHERE name = 'Ecobatchid'",__LINE__,__FILE__);
			$this->db->query("SELECT value from fm_idgenerator WHERE name = 'Ecobatchid'",__LINE__,__FILE__);
			$this->db->next_record();
			$batchid = $this->db->f('value');
			return $batchid;
		}

		protected function next_batchid()
		{
			$this->db->query("SELECT value from fm_idgenerator WHERE name = 'Ecobatchid'",__LINE__,__FILE__);
			$this->db->next_record();
			$batchid = $this->db->f('value')+1;
			return $batchid;
		}

		//Lagre start melding
		protected function log_start($batchid)
		{
			$tid = date($this->db->datetime_format());
			$sql= "INSERT INTO fm_ecologg (batchid,melding,tid) VALUES ('$batchid','Start transfer','$tid')";
			$this->db->query($sql,__LINE__,__FILE__);
		}

		protected function get_vendor_info($vendor_id='')
		{
			$sql = "SELECT org_nr, konto_nr FROM fm_vendor WHERE id='$vendor_id'";
			$this->db->query($sql,__LINE__,__FILE__);
			$this->db->next_record();

			$vendor_info= array
			(
				'org_nr' => $this->db->f('org_nr'),
				'konto_nr' => $this->db->f('konto_nr')
			);

			return $vendor_info;
		}

		protected function get_order_title($order_id='')
		{
			$sql = "SELECT type FROM fm_orders WHERE id='$order_id'";
			$this->db->query($sql,__LINE__,__FILE__);
			$this->db->next_record();

			switch($this->db->f('type'))
			{
				case 'workorder':
					$sql2 = "SELECT title FROM fm_workorder WHERE id='$order_id'";
					$this->db->query($sql2,__LINE__,__FILE__);
					$this->db->next_record();
					$order_title = $this->db->f('title');
					break;
				case 's_agreement':
					$sql2 = "SELECT descr as title FROM fm_s_agreement WHERE id='$order_id'";
					$this->db->query($sql2,__LINE__,__FILE__);
					$this->db->next_record();
					$order_title = $this->db->f('title');
					break;
			}

			return $order_title;
		}


		protected function select_invoice_rollback($date, $Filnavn)
		{
			$date_array = phpgwapi_datetime::date_array($date);
	 		$day = $date_array['day'];
	 		$month = $date_array['month'];
	 		$year = $date_array['year'];

			switch($GLOBALS['phpgw_info']['server']['db_type'])
			{
				case 'mssql':
					$datepart_year 		= "datepart(year,overftid)";
					$datepart_month 	= "datepart(month,overftid)";
					$datepart_day 		= "datepart(day,overftid)";
					break;
				case 'mysql':
					$datepart_year 		= "YEAR(overftid)";
					$datepart_month 	= "MONTH(overftid)";
					$datepart_day 		= "DAYOFMONTH(overftid)";
					break;
				case 'pgsql':
					$datepart_year 		= "date_part('year',overftid)";
					$datepart_month 	= "date_part('month',overftid)";
					$datepart_day 		= "date_part('day',overftid)";
					break;
				case 'postgres':
					$datepart_year 		= "date_part('year',overftid)";
					$datepart_month 	= "date_part('month',overftid)";
					$datepart_day 		= "date_part('day',overftid)";
					break;
			}

			$sql="SELECT * FROM fm_ecobilagoverf WHERE filnavn='$Filnavn' AND $datepart_year=$year AND $datepart_month=$month AND $datepart_day= $day";
			$this->db->query($sql,__LINE__,__FILE__);

			$invoice_rollback = array();
			while ($this->db->next_record())
			{
				$invoice_rollback[] = array
				(
					'id'					=> $this->db->f('id'),
					'bilagsnr'				=> $this->db->f('bilagsnr'),
					'kidnr'					=> $this->db->f('kidnr'),
					'typeid'				=> $this->db->f('typeid'),
					'kildeid'				=> $this->db->f('kildeid'),
					'pmwrkord_code'			=> $this->db->f('pmwrkord_code'),
					'belop'					=> $this->db->f('belop'),
					'fakturadato'			=> $this->db->f('fakturadato'),
					'periode'				=> $this->db->f('periode'),
					'forfallsdato'			=> $this->db->f('forfallsdato'),
					'fakturanr'				=> $this->db->f('fakturanr'),
					'spbudact_code'			=> $this->db->f('spbudact_code'),
					'regtid'				=> $this->db->f('regtid'),
					'artid'					=> $this->db->f('artid'),
					'godkjentbelop'			=> $this->db->f('godkjentbelop'),
					'spvend_code'			=> $this->db->f('spvend_code'),
					'dima'					=> $this->db->f('dima'),
					'loc1'					=> $this->db->f('loc1'),
					'dimb'					=> $this->db->f('dimb'),
					'mvakode'				=> $this->db->f('mvakode'),
					'dimd'					=> $this->db->f('dimd'),
					'project_id'			=> $this->db->f('project_id'),
					'kostra_id'				=> $this->db->f('kostra_id'),
					'item_type'				=> $this->db->f('item_type'),
					'item_id'				=> $this->db->f('item_id'),
					'oppsynsmannid'			=> $this->db->f('oppsynsmannid'),
					'saksbehandlerid'		=> $this->db->f('saksbehandlerid'),
					'budsjettansvarligid'	=> $this->db->f('budsjettansvarligid'),
					'oppsynsigndato'		=> $this->db->f('oppsynsigndato'),
					'saksigndato'			=> $this->db->f('saksigndato'),
					'budsjettsigndato'		=> $this->db->f('budsjettsigndato'),
					'merknad'				=> $this->db->f('merknad'),
					'splitt'				=> $this->db->f('splitt'),
					'ordrebelop'			=> $this->db->f('ordrebelop'),
					'utbetalingid'			=> $this->db->f('utbetalingid'),
					'utbetalingsigndato'	=> $this->db->f('utbetalingsigndato'),
					'external_ref'			=> $this->db->f('external_ref'),
					'currency'				=> $this->db->f('currency'),
				);
			}

			return $invoice_rollback;
		}

		//rollback function
		protected function bilag_update_overf($BilagOverf)
		{
			$values= array
			(
				$BilagOverf['project_id'],
				$BilagOverf['kostra_id'],
				$BilagOverf['pmwrkord_code'],
				$BilagOverf['bilagsnr'],
				$BilagOverf['splitt'],
				$BilagOverf['kildeid'],
				$BilagOverf['kidnr'],
				$BilagOverf['typeid'],
				$BilagOverf['fakturadato'],
				$BilagOverf['forfallsdato'],
				$BilagOverf['regtid'],
				$BilagOverf['artid'],
				$BilagOverf['spvend_code'],
				$BilagOverf['dimb'],
				$BilagOverf['oppsynsmannid'],
				$BilagOverf['saksbehandlerid'],
				$BilagOverf['budsjettansvarligid'],
				$BilagOverf['fakturanr'],
				$BilagOverf['spbudact_code'],
				$BilagOverf['dima'],
				$BilagOverf['loc1'],
				$BilagOverf['dimd'],
				$BilagOverf['mvakode'],
				$BilagOverf['periode'],
				$this->db->db_addslashes($BilagOverf['merknad']),
				$BilagOverf['utbetalingid'],
				$BilagOverf['oppsynsigndato'],
				$BilagOverf['saksigndato'],
				$BilagOverf['budsjettsigndato'],
				$BilagOverf['utbetalingsigndato'],
				$BilagOverf['item_type'],
				$BilagOverf['item_id'],
				$BilagOverf['external_ref'],
				$BilagOverf['belop'],
				$BilagOverf['godkjentbelop'],
				$BilagOverf['currency']
			);
			
			$values	= $this->db->validate_insert($values);

			$sql= "INSERT INTO fm_ecobilag (project_id,kostra_id,pmwrkord_code,bilagsnr,splitt,kildeid,kidnr,typeid,"
			. " fakturadato,forfallsdato,regtid,artid,spvend_code,dimb,oppsynsmannid,"
			. " saksbehandlerid,budsjettansvarligid,fakturanr,spbudact_code,dima,loc1,dimd,mvakode,"
			. " periode,merknad,utbetalingid,oppsynsigndato,saksigndato,budsjettsigndato,utbetalingsigndato,"
			. " item_type,item_id,external_ref,belop,godkjentbelop,currency)"
			. " VALUES ({$values})";

			$this->db->query($sql,__LINE__,__FILE__);
		}

   	   	//Oppdater beløp på arbeidsordre operator="-" ved tilbakerulling
		protected function correct_actual_cost($order_id, $Belop, $actual_cost_field, $operator)
		{
			$sql = "SELECT type FROM fm_orders WHERE id='$order_id'";
			$this->db->query($sql,__LINE__,__FILE__);
			$this->db->next_record();

			$table = '';
			$update_paid = '';
			switch($this->db->f('type'))
			{
				case 'workorder':
					$table = 'fm_workorder';
					if($operator == "-")
					{
						$update_paid = ", paid = 1";
					}
					else
					{
						$update_paid = ", paid = 2";
					}
					break;
				case 's_agreement':
					$table = 'fm_s_agreement';
					$actual_cost_field = 'actual_cost';
					break;
			}

			$Belop = $Belop/100;
			if(!$table)
			{
				throw new Exception('ERROR: the order id seems to not correspond with any order type');
			}

			$sql="UPDATE $table SET $actual_cost_field=$actual_cost_field $operator $Belop $update_paid WHERE id='$order_id'";
			$this->db->query($sql,__LINE__,__FILE__);
		}

		public function overfor($download,$force_period_year='')
		{
//			$download = 'on';
//			$download = False;
//			$this->debug=True;

			//Generer batch ID
			$batchid = $this->soXport->next_batchid();
			if ($download=='on')
			{
				$this->increment_batchid();
				//Lagre melding
				$this->log_start($batchid);
			}

			//Velg ut alle perioder som har bilag som skal overføres
			$vouchers = $this->select_vouchers_to_transfer();

			foreach ($vouchers as $voucher_id)
			{
				$receipt['message'][]= array('msg' => $this->transfer_voucher($batchid, $voucher_id, $download, $force_period_year));
			}

			//Lagre melding
			if ($download=='on')
			{
				$this->log_end($batchid); //Lagre melding
			}

			return $receipt;
		}
		
		protected function errorhandler($batchid,$error_desr)
		{
			if($this->db->Transaction)
			{
				$this->db->transaction_abort();
			}

			$meld = $error_desr;
		
			//Vis feilmelding
//			echo $meld;
		
			//Lagre feilmelding
			$this->log_error($batchid,$error_desr);
		}
		
		public function RullTilbake($Filnavn, $date)
		{								
			$voucher = $this->select_invoice_rollback($date, $Filnavn);
			$this->db->transaction_begin();

			foreach ($voucher as $line)
			{
				$this->bilag_update_overf($line);

				if($line['pmwrkord_code'])
				{
					$Belop = sprintf("%01.2f", $line['ordrebelop'])*100;
				
					if ($line['dimd'] % 2 == 0)
					{
						$actual_cost_field='act_mtrl_cost';
					}
					else
					{
						$actual_cost_field='act_vendor_cost';
					}
		
					$operator='-';

					$this->correct_actual_cost($line['pmwrkord_code'],$Belop,$actual_cost_field,$operator);
				}
		
				//Slett fra avviks tabell
			//	$this->soXport->delete_avvik($line['bilagsnr']);
		
				//Slett fra arkiv
				$this->soXport->delete_invoice($line['bilagsnr']);
			}
		
			$antall = count($voucher);
			if($antall > 0)
			{		
				$fil_katalog = $this->config->config_data['export_path'];			
			
				if(unlink ($fil_katalog. '/' . $Filnavn))
				{
					$this->db->transaction_commit();
					$receipt['message'][]= array('msg' => $antall . ' ' . lang('bilag/underbilag rullet tilbake'));
					$receipt['message'][]= array('msg' => lang('File %1 is deleted',$Filnavn));
				}
				else
				{
					$this->db->transaction_abort();
					$receipt['message'][]= array('msg' => 'Noe gikk galt!');
				}							
			}
			else
			{
				$receipt['error'][]= array('msg' => lang('Sorry - None hits'));
			}
			return $receipt;
		}
				
		protected function LagFilnavn ($external_ref)
		{	
			$fil_katalog = $this->config->config_data['export_path'];
			$continue = True;
			$Filnavn = $fil_katalog . "/x114_14_{$external_ref}.xml";

			//Sjekk om filen eksisterer
			If (!file_exists($Filnavn))
			{
				return $Filnavn;
			}

			return False;
		}
		
		protected function transfer_voucher($batchid, $voucher_id, $download, $force_period_year = '')
		{
			
			//Velg ut alle hoved bilag som skal overføres

			$oRsBilag = $this->get_voucher($voucher_id);

			if(isset($oRsBilag[0]['external_ref']) && $oRsBilag[0]['external_ref'])
			{
				//Bestem filnavn
				$Filnavn = $this->LagFilnavn($oRsBilag[0]['external_ref']);

				if (!$Filnavn)
				{
					$message='LagFilnavn: Filnavn er i bruk';
					$this->errorhandler($batchid,$message);
					return $message;
				}

				//Test om filen kan opprettes og skrives til
				if (@fopen($Filnavn, "wb"))
				{
					unlink($Filnavn);
				}
				else
				{
					$message='kan ikke lagre til fil: '. $Filnavn .'<br>';
					if($this->debug)
					{
						echo $message;
					}
					else
					{
						return $message;
					}
				}
			}

			$antall = count($oRsBilag);

			$this->db->transaction_begin();

			$tranfser_bilag = array($oRsBilag[0]['bilagsnr']);
			$localtime = phpgwapi_datetime::user_localtime();

			$transactioninformation = array
			(
				0 => array
				(
					'TRANSACTIONTYPE' => 'X114',
					'TRANSFER' => array
					(
						0 => array
						(
							'TRANSFERDATE' => date('d.m.Y', $localtime),//28.05.2009
							'TRANSFERTIME' => date('H:i:s', $localtime)//14:29:52
						)
					)
				)
			);

			$invoiceheader = array
			(
				0 => array
				(
					'TRANSACTIONTYPE'			=> 'X114',
					'KEY'						=> '', //dummy
					'VOUCHERID'					=> $oRsBilag[0]['bilagsnr'], // 70903541
					'SCANNINGNO'				=> $oRsBilag[0]['external_ref'], // 11E28NJINL3VR6
					'PROFILE'					=> 'TRAINVPOMA',
					'CLIENT.CODE'				=> $this->client_code, //14,
					'POATTRIB1'					=> '', //dummy
					'POATTRIB2'					=> '', //dummy
					'POPURCHASER'				=> '', //dummy
					'PREVOUCHERID'				=> '', //dummy
					'PURCHASEORDERNO'			=> $oRsBilag[0]['order_id'], // 1409220008
					'PURCHASEORDEROWNER.CODE'	=> $oRsBilag[0]['spvend_code'], // 100644
					'PURCHASEORDERSTATUS.CODE'	=> 'OK',
					'GENERALCOMMENT'			=> $comment, // Denne er fakturert i 3 deler OBS OBS!
				)
			);

			$accountline = array();

			$periode	= $oRsBilag[0]['periode'];

			foreach ($oRsBilag as $line)
			{
				//Bestem belops felt
				if ($line['splitt'] == 0)
				{
					//Bilaget er ikke splittet
					if ($line['godkjentbelop'] <> $line['belop'])
					{
						$BelopFelt = 'godkjentbelop';			
						//Logg til avviks tabell
						if ($download=='on')
						{
//							$this->soXport->log_to_deviation_table($line);
						}
					}
					else
					{
						$BelopFelt = 'belop';
					}
				}
				
				//Bilaget er splittet
				if ($line['godkjentbelop'] == $line['belop'])
				{
					$BelopFelt = 'godkjentbelop';
				}
				else
				{
					 //Ikke lovlig
					$message = lang('Avvik mellom fakturabelop og godkjent belop pa splittet faktura!');
					$this->errorhandler($batchid,$message);
					return $message;
				}

				$amount =  $line[$BelopFelt] * 100; 

				if($line['order_id'])
				{
					//Oppdater beløp på arbeidsordre
					if ($download=='on')
					{
						if ($line['dimd'] % 2 == 0)
						{
							$actual_cost_field='act_mtrl_cost';
						}
						else
						{
							$actual_cost_field='act_vendor_cost';
						}
						$operator='+';
						
						if(!$this->debug)
						{
							$this->correct_actual_cost($line['order_id'],$amount, $actual_cost_field,$operator);
						}
					}
				}

				$oRsOverfBilag				= $line;
				$oRsOverfBilag['filnavn']	= $Filnavn? basename($Filnavn) : date('d.m.Y-H:i:s', phpgwapi_datetime::user_localtime());
				$oRsOverfBilag['ordrebelop']= $line[$BelopFelt];
				$oRsOverfBilag['pmwrkord_code'] = $line['order_id'];

				//Kopier verdier  til fm_ecobilagoverf
				if ($download=='on' && !$this->debug)
				{
					$this->soXport->add_OverfBilag($oRsOverfBilag);
				}

/*
				$Resk_nr	= sprintf("%-9s",$oRsBilag[$k]['spvend_code']);// verdi: Blank., type: i4, plass: 382 - 390
				$Att_ansvarlig	= sprintf("%-6s",utf8_decode($oRsBilag[$k]['saksbehandler']));// verdi: Blank, type: c6, plass: 424 - 429

				$vendor_info = $this->get_vendor_info($oRsBilag[$k]['spvend_code']);
				
				if(!$vendor_info['org_nr'])
				{
					$message = 'mangler org_nr for reskontronr: ' . $oRsBilag[$k]['spvend_code'];
					$this->errorhandler($batchid,$message);
					return $message;
				}

				if(!$vendor_info['konto_nr'])
				{
					$message = 'mangler konto for reskontronr: ' . $oRsBilag[$k]['spvend_code'];
					$this->errorhandler($batchid,$message);
					return $message;
				}

				$Resk_navn	= sprintf("%-50s",$vendor_info['org_nr']);// verdi: Fødselsnr, type: c50, plass: 430 - 479
				$Bank_Postgiro_kontonr = sprintf("%-35s",str_replace(" ","",$vendor_info['konto_nr']));// verdi: konto_nr, type: c35, plass: 740 - 774

*/

				$descr = '';
				if($line['merknad'])
				{
					$descr = $line['merknad'];
				}
				else if ($line['order_id'])
				{
					$descr = $this->get_order_title($line['order_id']);
				}
				
				$accountline[] = array
				(
					'TRANSACTIONTYPE'		=> 'R114',
					'ACCOUNTLINK.CODE'		=> $line['spbudact_code'], // 4180
					'AMOUNT'				=> $amount, // 312500
					'APPROVER.FULLNAME'		=> $GLOBALS['phpgw_info']['user']['fullname'], //Batch 04 - 14
					'DIMENSION.D1.CODE'		=> $line['dima'], // 1111
					'DIMENSION.D2.CODE'		=> $line['dimb'], // 62000
					'DIMENSION.D3.CODE'		=> $dim3, // dummy
					'DIMENSION.D4.CODE'		=> $dim4, // dummy
					'DIMENSION.D5.CODE'		=> $dim5, // dummy
					'DIMENSION.D6.CODE'		=> $dim6, // dummy
					'DIMENSION.D7.CODE'		=> $dim7, // dummy
					'DIMENSION.D8.CODE'		=> $dim8, // dummy
					'POITEMDESCRIPTION'		=> $descr, // Sugerør,plast,fleksibelt,20cm
					'POITEMNUMBER'			=> $itemnumber, //200200
					'POITEMTYPE'			=> 'C', // A = Item, B = Special Product (SP), C = Text based  (Misc.)
					'POLINENUMBER'			=> $linenumber, // 10
					'RECEIVER.FULLNAME'		=> $GLOBALS['phpgw_info']['user']['fullname'], // Batch 04 - 14
					'STATUS'				=> 5,
					'SUBACCOUNT'			=> $periode, //200905 Accounting period YYYYMM
					'ALLOCATION.KEY'		=> 0,//$distribution_code, //0
					'ALLOCATION.PERIOD'		=> '' //dummy
				);		

			}
	
/*
			$Dim_1		= sprintf("%8s",$oRsOverfBilag['district_id']);// verdi: Ansvarssted, type: c8, plass: 29 - 36
			$Dim_2		= sprintf("%-8s",$oRsOverfBilag['kostra_id']);// verdi: Tjeneste, type: c8, plass: 37 - 44
			$Dim_3		= sprintf("%-8s",substr($oRsOverfBilag['dima'],0,6));// verdi: Objekt-bygg, type: c8, plass: 45 - 52
			$Dim_4		= sprintf("%-8s",'');// verdi: Ressurs, type: c8, plass: 53 - 60
			$Dim_5		= sprintf("%-12s",$oRsOverfBilag['project_id']);// verdi: Prosjekt, type: c12, plass: 61 - 72
			$Dim_6		= sprintf("%-4s",$oRsOverfBilag['dimd']);// verdi: Blank, type: c4, plass: 73 - 76
			$Dim_7		= sprintf("%-4s",'');// verdi: Blank, type: c4, plass: 77 - 80
*/

			$invoices = array
			(
				0 => array
				(
					'INVOICE' => array
					(
						0 => array
						(
							'INVOICEHEADER' => $invoiceheader,
							'ACCOUNTLINES' => array
							(
								0 => array
								(
									'ACCOUNTLINE' => $accountline
								)
							)
						)
					)
				)
			);

			$export_data = array
			(
				'TRANSACTIONINFORMATION'	=> $transactioninformation,
				'INVOICES'					=> $invoices
			);

			$xmltool = CreateObject('phpgwapi.xmltool');	

			$buffer = $xmltool->import_var('INVOICEIMPORT', $export_data,true, true);
			$buffer = str_replace('<INVOICEIMPORT>', '<INVOICEIMPORT TYPE="INVOICE">', $buffer);
			
//			echo $buffer; 
//-- fortsett her....									

			//Slett bilaget i fm_ecobilag
			if ($download=='on' && !$this->debug)
			{
				$this->_delete_from_fm_ecobilag($voucher_id);		
				//Logg transaksjon		
				$this->soXport->log_transaction($batchid,$voucher_id,lang('Invoice tranferred'));
			}
				
			//Fullfør transaksjon
			if ($download=='on' && !$this->debug)
			{
				$file_written = true;

			// aktiver neste blokk for a skrive filer for basware
			// -- Start
			/* 
				$file_written = false;
				$fp = fopen($Filnavn, "wb");
				fwrite($fp,$buffer);
				
				if(fclose($fp))
				{
					$file_written=true;
				}
			*/
			// -- END
				if( $file_written && $this->config->config_data['invoice_export_method'] != 'ftp' )
				{
					$transfer_ok = true;
				}
				else if($file_written)
				{
					$transfer_ok = $this->transfer($buffer,$Filnavn,$batchid,$tranfser_bilag);
				}

				if($transfer_ok)
				{
					$this->db->transaction_commit();
					$message = "Antall bilag/underbilag overfort: {$antall}, fil: {$Filnavn}";
				}
				else
				{
					$this->db->transaction_abort();
					$message = 'Noe gikk galt med overforing av godkjendte fakturaer!';				
				}
			}
			else
			{
				$message = $buffer;
				$this->db->transaction_abort();

			}

			return $message;
		}
		
    	protected function get_voucher($bilagsnr)
    	{
  	  		$bilagsnr = $bilagsnr;
  	  		$sql= "SELECT fm_ecobilag.*,fm_ecouser.initials as saksbehandler FROM fm_ecobilag $this->join fm_ecouser ON fm_ecobilag.budsjettansvarligid=fm_ecouser.lid WHERE bilagsnr = {$bilagsnr}";
			$this->db->query($sql,__LINE__,__FILE__);

			$voucher = array();
			while ($this->db->next_record())
			{
				$voucher[] = array
				(
					'id'					=> $this->db->f('id'),
					'bilagsnr'				=> $bilagsnr,
					'kidnr'					=> $this->db->f('kidnr'),
					'typeid'				=> $this->db->f('typeid'),
					'kildeid'				=> $this->db->f('kildeid'),
					'order_id'				=> $this->db->f('pmwrkord_code'),
					'belop'					=> $this->db->f('belop'),
					'fakturadato'			=> $this->db->f('fakturadato'),
					'periode'				=> $this->db->f('periode'),
					'forfallsdato'			=> $this->db->f('forfallsdato'),
					'fakturanr'				=> $this->db->f('fakturanr'),
					'spbudact_code'			=> $this->db->f('spbudact_code'),
					'regtid'				=> $this->db->f('regtid'),
					'artid'					=> $this->db->f('artid'),
					'godkjentbelop'			=> $this->db->f('belop'),
					'spvend_code'			=> $this->db->f('spvend_code'),
					'dima'					=> $this->db->f('dima'),
					'dimb'					=> $this->db->f('dimb'),
					'mvakode'				=> $this->db->f('mvakode'),
					'dimd'					=> $this->db->f('dimd'),
					'oppsynsmannid'			=> $this->db->f('oppsynsmannid'),
					'saksbehandlerid'		=> $this->db->f('saksbehandlerid'),
					'budsjettansvarligid'	=> $this->db->f('budsjettansvarligid'),
					'oppsynsigndato'		=> $this->db->f('oppsynsigndato'),
					'saksigndato'			=> $this->db->f('saksigndato'),
					'budsjettsigndato'		=> $this->db->f('budsjettsigndato'),
					'merknad'				=> $this->db->f('merknad'),
					'splitt'				=> $this->db->f('splitt'),
					'utbetalingid'			=> $this->db->f('utbetalingid'),
					'utbetalingsigndato'	=> $this->db->f('utbetalingsigndato'),
					'saksbehandler'			=> $this->db->f('saksbehandler'),
					'external_ref'			=> $this->db->f('external_ref'),
					'kostra_id'				=> $this->db->f('kostra_id')
				);
			}

			return $voucher;
    	}

		protected function _delete_from_fm_ecobilag($bilagsnr)
		{
			$bilagsnr = (int) $bilagsnr;
			$sql="DELETE FROM fm_ecobilag WHERE bilagsnr = $bilagsnr";
			$this->db->query($sql,__LINE__,__FILE__);
		}

		protected function transfer($buffer,$Filnavn,$batchid,$tranfser_bilag)
		{			

			if($this->config->config_data['invoice_export_method']=='ftp')
			{
				$ftp	= $this->phpftp_connect();	
				
				$basedir = $this->config->config_data['invoice_ftp_basedir'];
				if($basedir)
				{
					$newfile = $basedir . '/' . basename($Filnavn);
				}
				else
				{
					$newfile = basename($Filnavn);
				}

				if (ftp_put($ftp,$newfile, $Filnavn, FTP_BINARY))
				{
				 	for ($i=0;$i<count($tranfser_bilag);$i++)
					{				
						$this->soXport->log_transaction($batchid,$tranfser_bilag[$i],lang('Invoice pre_transferred %1',basename($Filnavn)));
					}
					$transfer_ok = True;
				}
				else
				{
				 	for ($i=0;$i<count($tranfser_bilag);$i++)
					{				
						$this->soXport->log_transaction($batchid,$tranfser_bilag[$i],lang('Failed to pre_transfere %1 to agresso',basename($Filnavn)));
					}
					$transfer_ok = False;
				}
				if(!$transfer_ok)
				{
					unlink($Filnavn);
				}
			
				ftp_quit($ftp);
			}
			return 	$transfer_ok;
		}

		protected function phpftp_connect() 
		{
			$host = $this->config->config_data['invoice_ftp_host'];
			$user = $this->config->config_data['invoice_ftp_user'];
			$pass = $this->config->config_data['invoice_ftp_password'];
			
//			echo "connecting to $host with $user and $pass\n <br>";
			$ftp = ftp_connect($host);
			if($ftp) 
			{
				if (ftp_login($ftp,$user,$pass)) 
				{
					return $ftp;
				}
			}
		}
	}
?>
