<?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 import
 	* @version $Id: Import_fra_BKK_csv,v 1.8 2007/03/18 16:33:16 sigurdne Exp $
	*/

	/**
	 * Description
	 * @package property
	 */

	class import_conv
	{
		var $spbudact_code='12304321';
		var $mvakode=0;
		var $kildeid=1;
		var $splitt=0;
		var $soXport;
		var $invoice;
		var $meter_table;
		protected $bilagsnr = array();

		var $import = array
		(
			'Bestilling'	=> 'pmwrkord_code', 
			'Fakt. Nr'		=> 'fakturanr',
			'Måler nr'		=> 'maalernr',
			'Konto'			=> 'spbudact_code',
			'Objekt'		=> 'dima',
			'Omr'			=> 'omraade',
			'Adresse'		=> 'stedsnavn',
			'MVA'			=> 'mvakode',
			'Tjeneste'		=> 'kostra_id',
			'Belop [kr]'	=> 'belop'
		);

//		var $header = array('Fakt. Nr','Måler nr','Konto','Objekt','MVA','Belop [kr]','Omr','Adresse');


		function import_conv()
		{
			$this->soXport 		= CreateObject('property.soXport');	
			$this->invoice 		= CreateObject('property.boinvoice');
			$this->config 		= CreateObject('phpgwapi.config','property');
			$this->config->read_repository();
			$this->meter_table = $this->config->config_data['meter_table'];

			$this->db 				= & $GLOBALS['phpgw']->db;
			$this->join				= & $this->db->join;
			$this->left_join		= & $this->db->left_join;
			$this->like				= & $this->db->like;
			$this->datetimeformat	= $this->db->datetime_format();
			$this->dateformat		= $this->db->date_format();
		}

		function import($invoice_common,$download)
		{
			$tsvfile	= $invoice_common['tsvfile'];
			$conv_type	= $invoice_common['conv_type'];
			$this->bilagsnr[] = $this->invoice->next_bilagsnr();
			$buffer = array();
			$xmlparse = CreateObject('property.XmlToArray');
			$xmlparse->setEncoding('UTF-8');
			$xmlparse->setDecodesUTF8Automaticly(false);
			$xmlparse->setIncludesEmptyValues(true);
			$var_result = $xmlparse->parseFile($tsvfile);

			$i = 0;			
			if(isset($var_result['Invoice']))
			{
				foreach ($var_result['Invoice'] as $invoice)
				{
					foreach ($invoice['InvoiceHeader'][0]['Buyer'][0]['Ref'] as $_ref)
					{
						if ($_ref['Code'] == 'CustomerNumber')
						{
							$kundenr = $_ref['Text'];
						}
					}

					$supplier_orgnumber	= $invoice['InvoiceHeader'][0]['Supplier'][0]['OrgNumber'];
					$fakturanr			= $invoice['InvoiceHeader'][0]['InvoiceNumber'];
					$invoice_date		= date($this->dateformat,strtotime($invoice['InvoiceHeader'][0]['InvoiceDate']));
					$payment_date		= date($this->dateformat,strtotime($invoice['InvoiceHeader'][0]['Payment'][0]['DueDate']));
					$periode			= date('Ym',strtotime($invoice['InvoiceHeader'][0]['InvoiceDate']));
					$kidnr				= $invoice['InvoiceHeader'][0]['Payment'][0]['KidNumber'];
					$currency			= $invoice['InvoiceHeader'][0]['Payment'][0]['Currency'];
					$maalepunktid		= $invoice['InvoiceHeader'][0]['InvoiceReferences'][0]['BuyersOrderNumber'];
					$godkjentbelop		= $invoice['InvoiceSummary'][0]['InvoiceTotals'][0]['GrossAmount'];
					$kunde_navn			= $invoice['InvoiceHeader'][0]['Buyer'][0]['Name'];

					$stedsnavn			= $invoice['InvoiceHeader'][0]['Buyer'][0]['PostalAddress'][0]['Address1'] . "\n";
					$stedsnavn			.= $invoice['InvoiceHeader'][0]['Buyer'][0]['PostalAddress'][0]['Address2'] . "\n";
					$stedsnavn			.= $invoice['InvoiceHeader'][0]['Buyer'][0]['PostalAddress'][0]['PostalCode'] . "\n";
					$stedsnavn			.= $invoice['InvoiceHeader'][0]['Buyer'][0]['PostalAddress'][0]['PostalDistrict'] . "\n";
					
					$buffer[$i]['bilagsnr'] = max($this->bilagsnr);

					if($godkjentbelop < 0)
					{
						$buffer[$i]['artid'] = 2;					
					}
					else
					{
						$buffer[$i]['artid'] = $invoice_common['art'];
					}

					if( $invoice_common['art'] == 2 ) // kreditnota
					{
						$godkjentbelop = -1 * abs($godkjentbelop);
					}

					$merknad = <<<HTML
					<table cellspacing="10">
						<tr>
							<td>
								Målepunktid
							</td>
							<td>
								$maalepunktid
							</td>
						</tr>
						<tr>
							<td>
								Fakturanr
							</td>
							<td>
								$fakturanr
							</td>
						</tr>
						<tr>
							<td>
								Kundenr
							</td>
							<td>
								$kundenr
							</td>
						</tr>
						<tr>
							<td>
								Kundenavn
							</td>
							<td>
								$kunde_navn
							</td>
						</tr>
						<tr>
							<td>
								Adresse
							</td>
							<td>
								$stedsnavn
							</td>
						</tr>
					</table>
HTML;


					$merknad .= <<<HTML
					<table cellspacing="10">
						<tr>
							<td>
								Beskrivelse
							</td>
							<td>
								Enhetspris
							</td>
							<td>
								Beløp
							</td>
							<td>
								Mengde
							</td>
							<td>
								Enhet
							</td>
						</tr>
HTML;
					
					foreach($invoice['InvoiceDetails'] as $invoicedetails)
					{
						foreach ($invoicedetails['BaseItemDetails'] as $baseitemdetails)
						{
							$line = "<tr><td>{$baseitemdetails['Description']}</td>";
							$line .= '<td align = "right">'. number_format(round($baseitemdetails['UnitPrice'],2),2). "</td>";
							$line .= '<td align = "right">'."{$baseitemdetails['LineItemAmount']}</td>";
							$line .= '<td align = "right">'."{$baseitemdetails['QuantityInvoiced']}</td>";
							$line .= '<td align = "right">'."{$baseitemdetails['UnitOfMeasure']}</td></tr>";
							$merknad .= $line;
						}
					}					

					$merknad .= <<<HTML
					</table>
HTML;
					$buffer[$i]['merknad']				= $merknad;

					$maalerinfo	= $this->anleggsnr_to_objekt($maalepunktid,$this->meter_table);
					$dima		= $maalerinfo['dima'];
					$loc1		= $maalerinfo['loc1'];
					$omraade	= $maalerinfo['district'];

					if($invoice_common['auto_tax'])
					{
						$mvakode=$this->soXport->auto_tax($dima);
						
						if($mvakode)
						{
							$buffer[$i]['mvakode']		= $mvakode;
						}
						else
						{
							$buffer[$i]['mvakode']		= $this->mvakode;
						}
					}
					else
					{
						$buffer[$i]['mvakode']			= $this->mvakode;
					}

					$buffer[$i]['stedsnavn'] 			= $stedsnavn;
					$buffer[$i]['currency'] 			= $currency;
					$buffer[$i]['fakturanr'] 			= $fakturanr;
					$buffer[$i]['dima']					= $dima;
					$buffer[$i]['loc1']					= $loc1;
					$buffer[$i]['omraade']				= $omraade;
					$buffer[$i]['splitt']				= $this->splitt;
					$buffer[$i]['kildeid']				= $this->kildeid;
					$buffer[$i]['spbudact_code']		= $this->spbudact_code;
					$buffer[$i]['kidnr']				= $kidnr;
					$buffer[$i]['typeid']				= $invoice_common['type'];
					$buffer[$i]['fakturadato']			= $invoice_date;
					$buffer[$i]['forfallsdato']			= $payment_date;
					$buffer[$i]['periode']				= $periode;
					$buffer[$i]['regtid']				= date($this->datetimeformat);
					$buffer[$i]['belop'] 				= $godkjentbelop;
					$buffer[$i]['godkjentbelop']		= $godkjentbelop;
					$buffer[$i]['spvend_code']			= $invoice_common['vendor_id'];
					$buffer[$i]['dimb']					= $invoice_common['dim_b'];
					$buffer[$i]['oppsynsmannid']		= $invoice_common['janitor'];
					$buffer[$i]['saksbehandlerid']		= $invoice_common['supervisor'];
					$buffer[$i]['budsjettansvarligid']	= $invoice_common['budget_responsible'];

					if($invoice_common['auto_tax'])
					{
						$buffer[$i]['mvakode']			= $this->soXport->tax_b_account_override($buffer[$i]['mvakode'] ,$buffer[$i]['spbudact_code']);
						$buffer[$i]['mvakode']			= $this->soXport->tax_vendor_override($buffer[$i]['mvakode'] ,$buffer[$i]['spvend_code']);
						$buffer[$i]['kostra_id']		= $this->soXport->get_kostra_id($buffer[$i]['dima']);
					}

					$i++;
					$this->bilagsnr[] = max($this->bilagsnr)+1;
 				}
			}

			if(!$download)
			{
				$buffer = $this->import_end_file($buffer);
			}

//			$this->header = array('Fakt. Nr','Måler nr','Konto','Objekt','MVA','Tjeneste','Belop [kr]','Omr','Adresse');
			return $buffer;
		}
		

		function anleggsnr_to_objekt($anleggsnr,$meter_table)
		{
			$sql = "SELECT {$meter_table}.ext_meter_id,{$meter_table}.loc1,{$meter_table}.loc2,{$meter_table}.loc3,fm_part_of_town.district_id "
			. " FROM {$meter_table} {$this->join} fm_location1 ON {$meter_table}.loc1 = fm_location1.loc1 $this->join "
  		          . " fm_part_of_town ON fm_location1.part_of_town_id = fm_part_of_town.part_of_town_id WHERE {$meter_table}.ext_system_id2 {$this->like} '%{$anleggsnr}'";
//	_debug_array($sql);
			$this->db->query($sql);

			$this->db->next_record();
			$loc1 = $this->db->f('loc1');
			$loc2 = $this->db->f('loc2');

			$maalerinfo['loc1']=$loc1;
			$maalerinfo['dima']=$loc1.$loc2;
			$maalerinfo['maalernr']=$this->db->f('ext_meter_id');
			$maalerinfo['district']=$this->db->f('district_id');
			return $maalerinfo;
		}

		function import_end_file($buffer)
		{

//_debug_array($buffer);die();
			$num	= $this->soXport->add($buffer);
			array_pop($this->bilagsnr);
			$bilagsnr = max($this->bilagsnr);
			$this->db->query("UPDATE fm_idgenerator SET VALUE ={$bilagsnr} WHERE name = 'Bilagsnummer'");
			$receipt['message'][]= array('msg' => lang('Successfully imported %1 records into your invoice register.',$num).' '.lang('ID').': '. implode(',', $this->bilagsnr));
			return $receipt;
		}
	}
