<?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,v 1.11 2007/01/26 14:58:55 sigurdne Exp $
	*/

	/**
	 * Description
	 * @package property
	 */

	class import_conv
	{
		var $currentrecord = array(); //used for buffering to allow uid lines to go first
		var $id = -1;
		var $spbudact_code='12304321';
		var $mvakode=0;
		var $kildeid=1;
		var $splitt=0;
		var $type = 'fixed';
		var $header_count = 1;
		var $soXport;
		var $invoice;
		var $meter_table;

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

		var $header = array('Fakt. Nr','Mler nr','Konto','Objekt','MVA','Belp [kr]','Omr','Adresse');

		var $import_bkk = array('boligbyggelag','dato','kundenr','lopenr', 'maalernr' ,	'installasjonsnr', 
			'anleggsid','stedsnavn','kunde_navn','navn','netto','mva');
			
		var $import_bkk_offset = array(
			'boligbyggelag' => '0', 
			'dato' => '5', 
			'kundenr' => '16', 
			'lopenr' => '25', 
			'maalernr' => '30', 
			'installasjonsnr' => '43', 
			'anleggsid' => '54', 
			'stedsnavn' => '59',
			'kunde_navn' => '95',
			'navn' => '126',
			'netto' => '157',
			'mva' => '172'
			);

		var $import_bkk_len = array(
			'boligbyggelag' => '5', 
			'dato' => '10', 
			'kundenr' => '8', 
			'lopenr' => '4', 
			'maalernr' => '8', 
			'installasjonsnr' => '9', 
			'anleggsid' => '4', 
			'stedsnavn' => '35',
			'kunde_navn' => '30',
			'navn' => '30',
			'netto' => '14',
			'mva' => '14'
			);

		function import_conv()
		{

			$this->currentapp	= $GLOBALS['phpgw_info']['flags']['currentapp'];
			$this->soXport 		= CreateObject($this->currentapp.'.soXport');	
			$this->invoice 		= CreateObject($this->currentapp.'.boinvoice');
			$this->bocommon		= CreateObject($this->currentapp.'.bocommon');
			$this->dateformat	= $this->bocommon->dateformat;
			$this->datetimeformat	= $this->bocommon->datetimeformat;
			$this->next_bilagsnr	= $this->invoice->next_bilagsnr();
			$this->config = CreateObject('phpgwapi.config','property');
			$this->config->read_repository();
			$this->meter_table = $this->config->config_data['meter_table'];

		}

		function import($invoice_common,$download)
		{

			$tsvfile	= $invoice_common['tsvfile'];
			$conv_type	= $invoice_common['conv_type'];

			if(!$buffer[$this->id]['kidnr'] = $invoice_common['kid_nr'])
			{
				echo '<b>KID-nummer mangler</b><br><br>';
				return;
			}
			$valid_data= False;
			$buffer = array();
			$buffer = $this->import_start_file($buffer);
			$fp = fopen($tsvfile,'rb');
//print_r($buffer);

//print_r($header);
//echo '<br>';
			for ($i = 0; $i < $this->header_count && fgets($fp,8000); ++$i);

			while ($data = fgets($fp,8000))
			{
//print_r($data);
				$num = count($this->import_bkk);
//echo 'data :'.$data.'<br>';
				$buffer = $this->import_start_record($buffer);
//print_r($buffer);
				for ($c=0; $c<$num; $c++ )
				{
					//Send name/value pairs along with the buffer
					if ($this->import_bkk[$c] != '' && substr($data,5,10) !='')
					{
//echo 'len :'.$this->import_bkk_len[$this->import_bkk[$c]].'<br>';
//print_r(fread($data,$this->import_bkk_len[$this->import_bkk[$c]]));
//print_r($this->import_bkk[$c]);
						$value=substr($data,$this->import_bkk_offset[$this->import_bkk[$c]],$this->import_bkk_len[$this->import_bkk[$c]]);
						$name=$this->import_bkk[$c];
						if ($name=='installasjonsnr')
						{
							$name='anleggsnr';
							$value=substr($data,43,9)." ".substr($data,54,4);
						}
						if ($name=='netto')
						{
							$name='belop';
							$value=(floatval(substr($data,157,14)) + floatval(substr($data,172,14)))/100;
							$valid_data= True;				
						}
//echo 'name :'.$name;
//echo '  value :'.$value.'<br>';
//print_r($buffer);

						$buffer = $this->import_new_attrib($buffer,$name,$value,$invoice_common);
					}
				}
				if ($valid_data)
				{
					$buffer = $this->import_end_record($buffer,$invoice_common);
					$valid_data= False;
				}
			}
			fclose($fp);
//print_r($buffer);


//echo 'download'.$download.'<br>';

			if(!$download)
			{
				$buffer = $this->import_end_file($buffer,$invoice_common['bilagsnr']);
			}

			$this->header = array('Fakt. Nr','Mler nr','Konto','Objekt','MVA','Tjeneste','Belp [kr]','Omr','Adresse');

			return $buffer;
		}
		

		function import_start_file($buffer)
		{
			return $buffer;
		}

		function import_start_record($buffer)
		{
//print_r($buffer);
			$top=array();
			++$this->id;
			$this->currentrecord = $top;
			return $buffer;
		}

		function import_new_attrib($buffer,$name,$value,$invoice_common)
		{

			$value = trim($value);
		//	$value = str_replace('\n','<BR>',$value);
		//	$value = str_replace('\r','',$value);

			$this->currentrecord += array($name => $value);
//print_r($buffer);
			return $buffer;
		}

		function import_end_record($buffer,$invoice_common)
		{
			$buffer[$this->id]='';
			while ( list($name, $value) = each($this->currentrecord))
			{
				$invoice_date = date($this->dateformat,mktime(2,0,0,$invoice_common['smonth'],$invoice_common['sday'],$invoice_common['syear']));

				if($invoice_common['num_days'])
				{
					$payment_date = date($this->dateformat,mktime(2,0,0,$invoice_common['smonth'],$invoice_common['sday'],$invoice_common['syear'])+(86400*$invoice_common['num_days']));
				}
				else
				{
					$payment_date = date($this->dateformat,mktime(2,0,0,$invoice_common['emonth'],$invoice_common['eday'],$invoice_common['eyear']));			
				}

				if($name=='belop')
				{
					$value = str_replace('kr','',$value);
					$value = str_replace(' ','',$value);
					$value = str_replace(',','.',$value);
					$godkjentbelop=$value;
				}

				if($name=='anleggsnr')
				{
					$buffer[$this->id]['merknad'] = 'anleggsnr:' . $value;
					
					$maalerinfo=$this->soXport->anleggsnr_to_objekt($value,$this->meter_table);
					$dima=$maalerinfo['dima'];
					$loc1=$maalerinfo['loc1'];
//					$maalernr=$maalerinfo['maalernr'];
					$omraade=$maalerinfo['district'];
					if($invoice_common['auto_tax'])
					{
						$mvakode=$this->soXport->auto_tax($dima);
						
						if($mvakode)
						{
							$buffer[$this->id]['mvakode'] = $mvakode;
						}
						else
						{
							$buffer[$this->id]['mvakode'] = $this->mvakode;
						}
					}
					else
					{
						$buffer[$this->id]['mvakode'] = $this->mvakode;
					}

				}
				if($name=='stedsnavn')
				{
					$buffer[$this->id]['merknad'] .= "\r\n" . $value;
				}

				$buffer[$this->id][$name] = $value;
				$buffer[$this->id]['bilagsnr'] = $this->next_bilagsnr;
				$buffer[$this->id]['fakturanr'] = $invoice_common['invoice_num'];
				$buffer[$this->id]['dima'] = $dima;
				$buffer[$this->id]['loc1'] = $loc1;
				$buffer[$this->id]['omraade'] = $omraade;
//				$buffer[$this->id]['maalernr'] = $maalernr;
				$buffer[$this->id]['splitt'] = $this->splitt;
				$buffer[$this->id]['kildeid'] = $this->kildeid;
//				$buffer[$this->id]['mvakode'] = $this->mvakode;
				$buffer[$this->id]['spbudact_code'] = $this->spbudact_code;
				$buffer[$this->id]['kidnr'] = $invoice_common['kid_nr'];
				$buffer[$this->id]['typeid'] = $invoice_common['type'];
				$buffer[$this->id]['fakturadato'] = $invoice_date;
				$buffer[$this->id]['forfallsdato'] = $payment_date;
				$buffer[$this->id]['periode'] = $invoice_common['smonth'];
				$buffer[$this->id]['regtid'] = date($this->datetimeformat);
				$buffer[$this->id]['artid'] = $invoice_common['art'];
				$buffer[$this->id]['godkjentbelop'] = $godkjentbelop;
				$buffer[$this->id]['spvend_code'] = $invoice_common['vendor_id'];
				$buffer[$this->id]['dimb'] = $invoice_common['dim_b'];
				$buffer[$this->id]['oppsynsmannid'] = $invoice_common['janitor'];
				$buffer[$this->id]['saksbehandlerid'] = $invoice_common['supervisor'];
				$buffer[$this->id]['budsjettansvarligid'] = $invoice_common['budget_responsible'];

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

		function import_end_file($buffer,$bilagsnr)
		{
			$num	= $this->soXport->add($buffer);
			$receipt['message'][]= array('msg' => lang('Successfully imported %1 records into your invoice register.',$num).' '.lang('ID').': '. $bilagsnr);
			return $receipt;
		}
	}
?>
