<?php
require_once 'modules/EcmReports/optima/OptimaXML.php';

ini_set('display_errors',1);

Class SimpleXMLExtended extends SimpleXMLElement {
	
	/**
	 * Adds a child with $value inside CDATA
	 * @param unknown $name
	 * @param unknown $value
	 */
	public function addCData($cdata_text){
		$node= dom_import_simplexml($this);
		$no = $node->ownerDocument;
		$node->appendChild($no->createCDATASection($cdata_text));
	} 
}

class ExportOptima {
	private $date_from;
	private $date_to;
	private $db;
	private $optimaXML;
	private $XMLObject;
	public function __construct($date, OptimaXML $optimaXML) {
		$date = new DateTime ( $date );
		$this->date_from = $date->format ( "Y-m-01" );
		$this->date_to = $date->format ( "Y-m-t" );
		$this->db = $GLOBALS ['db'];
		$this->optimaXML = $optimaXML;
	}
	public function loadXmlObject() {
		$this->optimaXML->generateStartXMl ()->loadXml ();
	}
	 
	public function addAccounts() {
		global $app_list_strings;
		
		$payment_methods = $app_list_strings ['payment_method_dom'];
		
		$fpn = new SimpleXMLExtended ( '<KONTRAHENCI></KONTRAHENCI>' );
		
		$fpn->addChild ( 'WERSJA', OptimaXMLConstant::WERSJA );
		$fpn->addChild ( 'BAZA_ZRD_ID', OptimaXMLConstant::BAZA_ZRD_ID );
		$fpn->addChild ( 'BAZA_DOC_ID', OptimaXMLConstant::BAZA_DOC_ID );
		
		$i=0;
	
		foreach ( $this->getAccounts() as $value ) {
	
				$fpn = $this->addAccount ( $value, $fpn );
	
			
		}
	
		$this->xml_adopt ( $this->optimaXML->basicXML, $fpn );
	
	}
	
	public function addAccount($acc, $fpn) {
		$header = new SimpleXMLExtended ( '<KONTRAHENT></KONTRAHENT>',LIBXML_NOEMPTYTAG);
		$fpe = $header->addChild ( 'KONTRAHENT' );
		
		global $app_list_strings;
		
	

		$this->addIfNotEmpty ( $fpe, 'ID_ZRODLA', $acc->id );
		$this->addIfNotEmpty ( $fpe, 'AKRONIM', $acc->number);
		$this->addIfNotEmpty ( $fpe, 'RODZAJ', strtolower($app_list_strings['account_type2_dom'][$acc->account_type]) );
		$this->addIfNotEmpty ( $fpe, 'CHRONIONY', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'MEDIALNY', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'ROLNIK', 'Nie' );
		if ($acc->invoice_type== 'K') {
	
			$export = 'krajowy';
		} else if ($acc->invoice_type== 'U') {

			$export = 'wewnątrzunijny';
		} else if ($acc->invoice_type== 'E') {
			$export = 'pozaunijny';
		
		}
		
		$this->addIfNotEmpty ( $fpe, 'EKSPORT', $export );
		$this->addIfNotEmpty ( $fpe, 'FINALNY',($acc->natural_person==1 ? 'Tak' : 'Nie'));
		$this->addIfNotEmpty ( $fpe, 'PLATNIK_VAT', ($acc->vat_payer==1 ? 'Tak' : 'Nie'));
		$this->addIfNotEmpty ( $fpe, 'POWIAZANY_UOV', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'NIEAKTYWNY', 'Nie' );
		
		$adresy = $fpe->addChild ( 'ADRESY' );
	
		global $app_list_strings;

			
			$header = new SimpleXMLExtended ( '<ADRES></ADRES>' );
			$fpc = $header->addChild ( 'ADRES' );
			$fpc->addChild ( 'STATUS','aktualny' );
			$this->addIfNotEmpty ( $fpc, 'GLN', $acc->sic_code);
			
			
		$acc_name = $acc->name;
	
		if (strlen ( $acc_name ) > 50) {
			$this->addIfNotEmpty ( $fpc, 'NAZWA1', mb_substr( $acc_name, 0, 50,'UTF-8' ) );
	
			if (strlen ( $acc_name ) > 100) {
				$this->addIfNotEmpty ( $fpc, 'NAZWA2', mb_substr( $acc_name, 50, 50,'UTF-8' ) );
				$this->addIfNotEmpty ( $fpc, 'NAZWA3', mb_substr( $acc_name, 100,null,'UTF-8' ) );
			} else {
				$this->addIfNotEmpty ( $fpc, 'NAZWA2', mb_substr( $acc_name, 50,null,'UTF-8' ) );
			}
		} else {
			$this->addIfNotEmpty ( $fpc, 'NAZWA1', $acc_name );
		}

		$acc->to_vatid=str_replace(" ","",str_replace("-","",$acc->to_vatid));
		if ($acc->invoice_type == "K") {
			$this->addIfNotEmpty ( $fpc, 'NIP_KRAJ', 'PL' );
			$this->addIfNotEmpty ( $fpc, 'NIP', $acc->to_vatid );
		} else {
			$this->addIfNotEmpty ( $fpc, 'NIP_KRAJ', mb_substr( $acc->to_vatid, 0, 2,'UTF-8' ) );
			$replace=mb_substr( $acc->to_vatid, 0, 2,'UTF-8' );
			$this->addIfNotEmpty ( $fpc, 'NIP', str_replace($replace,'',$acc->to_vatid) );
		}
		
		if($acc->parent_id!=""){
			$payer = new Account();
			$payer->retrieve($acc->parent_id);
			$this->addIfNotEmpty ( $fpc, 'TYP_PLATNIKA','kontrahent' );
		#	$this->addIfNotEmpty ( $fpc, 'PLATNIK', $acc->to_vatid );
			$this->addIfNotEmpty ( $fpc, 'PLATNIK_ID', $payer->id );
			$this->addIfNotEmpty ( $fpc, 'PLATNIK_NIP',$payer->to_vatid);
		}
		
	
		
		$acc->billing_address_street=str_replace("\r\n","",$acc->billing_address_street);
		
		preg_match ( '/^([^\d]*[^\d\s]) *(\d.*)$/', $acc->billing_address_street, $matches );
		
		$this->addIfNotEmpty ( $fpc, 'KRAJ', $acc->billing_address_country );
		
		$this->addIfNotEmpty ( $fpc, 'WOJEWODZTWO', $acc->billing_address_state );
		// $fpe->addChild('POWIAT',$acc->to_vatid);
		$this->addIfNotEmpty ( $fpc, 'GMINA', $acc->billing_address_ecmcommune_name );
		
		$this->addIfNotEmpty ( $fpc, 'ULICA', $matches [1] );
		
		$numbers = $this->findHomeAndLocale ( $matches [2] );
		$this->addIfNotEmpty ( $fpc, 'NR_DOMU', $numbers [0] );
		$this->addIfNotEmpty ( $fpc, 'NR_LOKALU', $numbers [1] );
		$this->addIfNotEmpty ( $fpc, 'MIASTO', $acc->billing_address_city );
		$this->addIfNotEmpty ( $fpc, 'KOD_POCZTOWY', $acc->billing_address_postalcode );
		
		
		$this->xml_adopt ( $adresy, $fpc );
		$this->xml_adopt ( $fpn, $fpe );
		
		return $fpn;
	}
	
	public function addInvoiceDocuments() {
		global $app_list_strings;
		
		$this->getInvoicesObject ();
		
		$payment_methods = $app_list_strings ['payment_method_dom'];
		
		$fpn = new SimpleXMLExtended ( '<REJESTRY_SPRZEDAZY_VAT></REJESTRY_SPRZEDAZY_VAT>' );
		
		$fpn->addChild ( 'WERSJA', OptimaXMLConstant::WERSJA );
		$fpn->addChild ( 'BAZA_ZRD_ID', OptimaXMLConstant::BAZA_ZRD_ID );
		$fpn->addChild ( 'BAZA_DOC_ID', OptimaXMLConstant::BAZA_DOC_ID );
		
		$i=0;
		foreach ( $this->getInvoicesObject () as $value ) {

			$fpn = $this->addInvoiceDocument ( $value, $fpn );
			
		}

		$this->xml_adopt ( $this->optimaXML->basicXML, $fpn );
		
	
	}
	
	
	public function addInvoiceDocument($value, $fpn) {
		$header = new SimpleXMLExtended ( '<REJESTR_SPRZEDAZY_VAT></REJESTR_SPRZEDAZY_VAT>' );
		$fpe = $header->addChild ( 'REJESTR_SPRZEDAZY_VAT' );
		
		$this->addIfNotEmpty ( $fpe, 'ID_ZRODLA', $value->id );
		$this->addIfNotEmpty ( $fpe, 'MODUL', 'HANDEL' );
		$this->addIfNotEmpty ( $fpe, 'REJESTR', 'SPRZEDAŻ' );
		$this->addIfNotEmpty ( $fpe, 'DATA_WYSTAWIENIA', date ( "Y-m-d", strtotime ( $value->register_date ) ) );
		$this->addIfNotEmpty ( $fpe, 'DATA_SPRZEDAZY', date ( "Y-m-d", strtotime ( $value->sell_date ) ) );
		$this->addIfNotEmpty ( $fpe, 'TERMIN', date ( "Y-m-d", strtotime ( $value->payment_date ) ) );
		$this->addIfNotEmpty ( $fpe, 'NUMER', $value->document_no );
		$this->addIfNotEmpty ( $fpe, 'KOREKTA', ($value->type == 'normal' ? 'Nie' : 'Tak') );
		
		if ($value->type == 'correct') {
			$cor = new EcmInvoiceOut ();
			$cor->retrieve ( $value->ecminvoiceout_id );
			$this->addIfNotEmpty ( $fpe, 'KOREKTA_NUMER', $cor->document_no );
			$this->addIfNotEmpty ( $fpe, 'TYP', 'Faktura sprzedaży' );
		} else {
			$this->addIfNotEmpty ( $fpe, 'TYP', 'Faktura sprzedaży' );
		}
		
		$this->addIfNotEmpty ( $fpe, 'WEWNETRZNA', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'METODA_KASOWA', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'FISKALNA', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'DETALICZNA', 'Nie' );
		if ($value->pdf_type == 'K') {
			$dek_7 = date ( "Ym", strtotime ( $value->register_date ) );
			$dek_ue = "Nie";
			$export = 'nie';
		} else if ($value->pdf_type == 'U') {
			$dek_7 = "";
			$dek_ue = 'Tak';
			$export = 'wewnątrzunijny';
		} else if ($value->pdf_type == 'E') {
			$export = 'tak';
			$dek_7 = date ( "Ym", strtotime ( $value->register_date ) );
			$dek_ue = 'Nie';
		}
		
		$this->addIfNotEmpty ( $fpe, 'EKSPORT', $export );
		
		$acc = new Account ();
		$acc->retrieve ( $value->parent_id );
		$this->addIfNotEmpty ( $fpe, 'FINALNY', ($acc->natural_person ? 'Tak' : 'Nie') );
		$this->addIfNotEmpty ( $fpe, 'PODATNIK_CZYNNY', ($acc->vat_payer ? 'Tak' : 'Nie') );
		
		$this->addIfNotEmpty ( $fpe, 'TYP_PODMIOTU', 'kontrahent' );
		
		$this->addIfNotEmpty ( $fpe, 'PODMIOT',trim(preg_replace('/\s+/', ' ', $acc->name)));
		$this->addIfNotEmpty ( $fpe, 'PODMIOT_ID', $acc->id );
		
		if ($acc->invoice_type == "K") {

			$this->addIfNotEmpty ( $fpe, 'PODMIOT_NIP', $acc->to_vatid );
		} else {
			$replace=  substr ( $acc->to_vatid, 0, 2 ) ;
			$this->addIfNotEmpty ( $fpe, 'PODMIOT_NIP', str_replace($replace,"",$acc->to_vatid) );
		}
		
		$acc_name  = trim(preg_replace('/\s+/', ' ', $acc->name));
		
		if (strlen ( $acc_name ) > 50) {
			$this->addIfNotEmpty ( $fpe, 'NAZWA1', mb_substr ( $acc_name, 0, 50,'UTF-8' ) );
			if (strlen ( $acc_name ) > 100) {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', mb_substr( $acc_name, 50, 50,'UTF-8' ) );
				$this->addIfNotEmpty ( $fpe, 'NAZWA3', mb_substr( $acc_name, 100,null,'UTF-8' ) );
			} else {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', mb_substr( $acc_name, 50,null,'UTF-8' ) );
			}
		} else {
			$this->addIfNotEmpty ( $fpe, 'NAZWA1', $acc_name );
		}
		
		if ($acc->invoice_type == "K") {
			$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', 'PL' );
			$this->addIfNotEmpty ( $fpe, 'NIP', $acc->to_vatid );
		} else {
			$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', substr ( $acc->to_vatid, 0, 2 ) );
			$replace=  substr ( $acc->to_vatid, 0, 2 ) ;
			$this->addIfNotEmpty ( $fpe, 'NIP', str_replace($replace,"",$acc->to_vatid) );
		}
		
	
		
		$acc->billing_address_street=trim(preg_replace('/\s+/', ' ', $acc->billing_address_street));
		
		preg_match ( '/^([^\d]*[^\d\s]) *(\d.*)$/', $acc->billing_address_street, $matches );
		
		$this->addIfNotEmpty ( $fpe, 'KRAJ', $acc->billing_address_country );
		
		$this->addIfNotEmpty ( $fpe, 'WOJEWÓDZTWO', $acc->billing_address_state );
		// $fpe->addChild('POWIAT',$acc->to_vatid);
		$this->addIfNotEmpty ( $fpe, 'GMINA', $acc->billing_address_ecmcommune_name );
		
		$this->addIfNotEmpty ( $fpe, 'ULICA', $matches [1] );
	
		$numbers = $this->findHomeAndLocale ( $matches [2] );
		$this->addIfNotEmpty ( $fpe, 'NR_DOMU', $numbers [0] );
		$this->addIfNotEmpty ( $fpe, 'NR_LOKALU', $numbers [1] );
		$this->addIfNotEmpty ( $fpe, 'MIASTO', $acc->billing_address_city );
		$this->addIfNotEmpty ( $fpe, 'KOD_POCZTOWY', $acc->billing_address_postalcode );
		
		if($value->parent_payer_address_name!=""){
			$obj= new Account();
			$obj->retrieve_by_string_fields(['to_vatid'=>$value->parent_payer_address_nip]);
			
			$this->addIfNotEmpty ( $fpe, 'PLATNIK_ID', $obj->id );
			$this->addIfNotEmpty ( $fpe, 'PLATNIK_NIP',$value->parent_payer_address_nip);
		} else {
			$this->addIfNotEmpty ( $fpe, 'PLATNIK_ID', $value->parent_id );
			$this->addIfNotEmpty ( $fpe, 'PLATNIK_NIP',$value->parent_nip);
		}
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT7', $dek_7 );
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VATUE', $dek_ue );
		
		if ($value->currency_id!='PLN') {
			$cur = new Currency ();
			$cur->retrieve ( $value->currency_id );
			$date = $this->getCurrencyDate ( $value->currency_table, $cur->id );
			$this->addIfNotEmpty ( $fpe, 'WALUTA', $cur->name );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', '' . $value->currency_value_nbp );
			$this->addIfNotEmpty ( $fpe, 'DATA_KURSU', date ( "Y-m-d", strtotime ( $date ) ) );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', $value->currency_value_nbp );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', $value->currency_value_nbp );
			$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', 'Nie' );
		} else {
			$this->addIfNotEmpty ( $fpe, 'WALUTA', '' );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', 'NBP' );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', '1' );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', '1' );
			$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', "Nie" );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY_2', 'NBP' );
		}
		$this->addIfNotEmpty ( $fpe, 'PLATNOSC_VAT_W_PLN', "Nie" );
		$this->addIfNotEmpty ( $fpe, 'JPK_FA', "Tak" );
		$this->addIfNotEmpty ( $fpe, 'AKCYZA_NA_WEGIEL', "Nie" );
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT27', "Nie" );
		$this->addIfNotEmpty ( $fpe, 'WARTOSC_ZAKUPU', $value->purchase_price );
		
		$this->addInvoicePositions ( $fpe, $value );
		
		
		$platnosci = $fpe->addChild ( 'PLATNOSCI' );
		
		$header = new SimpleXMLExtended ( '<PLATNOSC></PLATNOSC>', LIBXML_NOEMPTYTAG);
		$platnosc = $header->addChild ( 'PLATNOSC' );
		
		$platnosc->addChild ( 'ID_ZRODLA_PLAT',$value->id);
		$platnosc->addChild ( 'TERMIN_PLAT',date("Y-m-d",strtotime($value->payment_date)));
	
		if($value->payment_method=='PRZELEW'){
			$forma='przelew';
		}
		if($value->payment_method=='GOTÓWKĄ'){
			$forma='gotówka';
		} else {
			$forma='przelew';
		}
		$platnosc->addChild ( 'FORMA_PLATNOSCI_PLAT',$forma);
		$platnosc->addChild ( 'FORMA_PLATNOSCI_ID_PLAT',$value->parent_id);
		if($value->type=='correct'){
			$platnosc->addChild ( 'KWOTA_PLAT',abs($value->total_brutto));
		} else {
			$platnosc->addChild ( 'KWOTA_PLAT',$value->total_brutto);
		}
		
		if ($value->currency_id!='PLN') {

		$platnosc->addChild ('WALUTA_PLAT',$cur->name);
		$platnosc->addChild ('WALUTA_DOK',$cur->name);
		$platnosc->addChild ('KURS_WALUTY_PLAT','NBP');
		$platnosc->addChild ('NOTOWANIE_WALUTY_ILE_PLAT',$value->currency_value_nbp);
		$platnosc->addChild ('NOTOWANIE_WALUTY_ZA_ILE_PLAT',$value->currency_value_nbp);
		if($value->type=='correct'){
			$platnosc->addChild ( 'KWOTA_PLN_PLAT',abs(round($value->total_brutto*$value->currency_value_nbp,2)));
		} else {
			$platnosc->addChild ( 'KWOTA_PLN_PLAT',round($value->total_brutto*$value->currency_value_nbp,2));
		}
		
	
		$date = $this->getCurrencyDate ( $value->currency_table, $cur->id );
		$this->addIfNotEmpty ( $platnosc, 'DATA_KURSU_PLAT', date ( "Y-m-d", strtotime ( $date ) ) );
		
		} else {
			
			$platnosc->WALUTA_PLAT='<![CDATA[]]>';
			$platnosc->WALUTA_DOK='<![CDATA[]]>';
	
			$platnosc->addChild ('KURS_WALUTY_PLAT','NBP');
			$platnosc->addChild ('NOTOWANIE_WALUTY_ILE_PLAT','1');
			$platnosc->addChild ('NOTOWANIE_WALUTY_ZA_ILE_PLAT','1');
			
			if($value->type=='correct'){
				$platnosc->addChild ( 'KWOTA_PLN_PLAT',abs($value->total_brutto));
			} else {
				$platnosc->addChild ( 'KWOTA_PLN_PLAT',$value->total_brutto);
			}
			
		
			
		}
		$platnosc->addChild ( 'KIERUNEK','przychód');
		$platnosc->addChild ( 'PODLEGA_ROZLICZENIU','tak');
		//$platnosc->addChild ( 'KONTO','');
		$platnosc->addChild ( 'NIE_NALICZAJ_ODSETEK','Nie');
		$platnosc->addChild ( 'PRZELEW_SEPA','Nie');
	//	$platnosc->addChild ( 'DATA_KURSU_PLAT','przychód'); 
		$platnosc->addChild ( 'PLATNOSC_TYP_PODMIOTU','kontrahent');

		
		if($value->parent_payer_address_name!=""){
			$obj= new Account();
			$obj->retrieve_by_string_fields(['to_vatid'=>$value->parent_payer_address_nip]);
			
			$platnosc->addChild ( 'PLATNOSC_PODMIOT',$obj->name);
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_ID',$obj->id );
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_NIP',$value->parent_payer_address_nip);
		} else {
			
			$platnosc->addChild ( 'PLATNOSC_PODMIOT',$value->parent_name);
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_ID',$value->parent_id);
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_NIP',$value->p);
		}
		/*
		$platnosc->addChild ( 'PLAT_ELIXIR_O1','');
		$platnosc->addChild ( 'PLAT_ELIXIR_O2','');
		$platnosc->addChild ( 'PLAT_ELIXIR_O3','');
		$platnosc->addChild ( 'PLAT_ELIXIR_O4','');
*/
		$this->xml_adopt ( $platnosci, $platnosc);
		//$this->xml_adopt ( $fpe, $platnosci);
		
		$this->xml_adopt ( $fpn, $fpe );
		
		return $fpn;
	}
	
	public function addInvoicePositions($node, $object) {
		$pozycje = $node->addChild ( 'POZYCJE' );
		$positions = $object->getPositionList ( true );
		
		global $app_list_strings;
		
		foreach ( $positions as $position ) {
			
			$header = new SimpleXMLExtended ( '<POZYCJA></POZYCJA>' );
			$fpe = $header->addChild ( 'POZYCJA' );
			if($object->type=='correct'){
				$fpe->addChild ( 'STAWKA_VAT', str_replace("%","",$position ['ecmvat_name'] ));
				$fpe->addChild ( 'STATUS_VAT', 'opodatkowana' );
				$fpe->addChild ( 'NETTO', $position ['total_netto_corrected'] );
				$fpe->addChild ( 'VAT', $position ['total_vat_corrected'] );
				
			
					
					$fpe->addChild ( 'NETTO_SYS', round ( $position ['total_netto_corrected'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
					$fpe->addChild ( 'VAT_SYS', round ( $position ['total_vat_corrected'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
					
					$fpe->addChild ( 'NETTO_SYS2', round ( $position ['total_netto_corrected'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
					$fpe->addChild ( 'VAT_SYS2', round ( $position ['total_vat_corrected'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
				
				
				if($position['product_ks_group']=='1'){
					$typeP='towary';
				}
				if($position['product_ks_group']=='2'){
					$typeP='towary';
				}
				if($position['product_ks_group']=='3'){
					$typeP='towary';
				}
				if($position['product_ks_group']=='4'){
					$typeP='środki transportu';
				}
				$cdata=$fpe->addChild( 'RODZAJ_SPRZEDAZY');
				
				$cdata->addCData($typeP);
				
				
				
			
			} else {
				

				$fpe->addChild ( 'STAWKA_VAT', str_replace("%","",$position ['ecmvat_name'] ));
				$fpe->addChild ( 'STATUS_VAT', 'opodatkowana' );
				$fpe->addChild ( 'NETTO',round ( $position ['total_netto'], 2 ));
				$fpe->addChild ( 'VAT', round ( $position ['total_vat'], 2 ) );
				
				
					
					$fpe->addChild ( 'NETTO_SYS', round ( $position ['total_netto'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
					$fpe->addChild ( 'VAT_SYS', round ( $position ['total_vat'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
					
					$fpe->addChild ( 'NETTO_SYS2', round ( $position ['total_netto'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
					$fpe->addChild ( 'VAT_SYS2', round ( $position ['total_vat'] * ($object->currency_value_nbp!="0" ? $object->currency_value_nbp : '1'), 2 ) );
				
				
				if($position['product_ks_group']=='1'){
					$typeP='towary';
				}
				if($position['product_ks_group']=='2'){
					$typeP='towary';
				}
				if($position['product_ks_group']=='3'){
					$typeP='towary';
				}
				if($position['product_ks_group']=='4'){
					$typeP='środki transportu';
				}
				
				$cdata=$fpe->addChild( 'RODZAJ_SPRZEDAZY');
				
				$cdata->addCData($typeP);
				
				$fpe->addChild ( 'UWZ_W_PROPORCJI','TAK' );
			}
	
			
			$this->xml_adopt ( $pozycje, $fpe );
		}
	}
	
	public function addPurchaseDocuments() {
		global $app_list_strings;
		

		
		$payment_methods = $app_list_strings ['payment_method_dom'];
		
		$fpn = new SimpleXMLExtended ( '<REJESTRY_ZAKUPU_VAT></REJESTRY_ZAKUPU_VAT>' );
		
		$fpn->addChild ( 'WERSJA', OptimaXMLConstant::WERSJA );
		$fpn->addChild ( 'BAZA_ZRD_ID', OptimaXMLConstant::BAZA_ZRD_ID );
		$fpn->addChild ( 'BAZA_DOC_ID', OptimaXMLConstant::BAZA_DOC_ID );
		
$i=0;
		foreach ( $this->getDocumentsObiect() as $value ) {
	
			$fpn = $this->addPurchaseDocument ( $value, $fpn );
	
		}
		
		$this->xml_adopt ( $this->optimaXML->basicXML, $fpn );

	}
	
	public function addPurchaseDocument($value, $fpn) {
		$header = new SimpleXMLExtended ( '<REJESTR_ZAKUPU_VAT></REJESTR_ZAKUPU_VAT>' );
		$fpe = $header->addChild ( 'REJESTR_ZAKUPU_VAT' );
		
		$this->addIfNotEmpty ( $fpe, 'ID_ZRODLA', $value->id );
		$this->addIfNotEmpty ( $fpe, 'MODUL', 'HANDEL' );
		

		$this->addIfNotEmpty ( $fpe, 'DATA_WYSTAWIENIA', date ( "Y-m-d", strtotime ( $value->document_date) ) );
		$this->addIfNotEmpty ( $fpe, 'DATA_ZAKUPU', date ( "Y-m-d", strtotime ( $value->document_date) ) );
		$this->addIfNotEmpty ( $fpe, 'DATA_WPLYWU', date ( "Y-m-d", strtotime ( $value->document_date) ) );
		$this->addIfNotEmpty ( $fpe, 'TERMIN', date ( "Y-m-d", strtotime ( $value->payment_date) ) );
		$this->addIfNotEmpty ( $fpe, 'NUMER', $value->document_name);
		$this->addIfNotEmpty ( $fpe, 'KOREKTA', ($value->corrected_document_name!=null ? 'Tak' : 'Nie') );
		
		if ($value->corrected_document_name!=null) {
		
			$this->addIfNotEmpty ( $fpe, 'KOREKTA_NUMER', $value->corrected_document_name);
		}
		$this->addIfNotEmpty ( $fpe, 'WEWNETRZNA', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'METODA_KASOWA', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'FISKALNA', 'Nie' );
		$this->addIfNotEmpty ( $fpe, 'DETALICZNA', 'Nie' );
		$dek_ue = "Nie";
		$export = 'nie';
		$rejestr='kraj';
		if ($value->document_type == 'k') {
			$dek_7 = date ( "Ym", strtotime ( $value->active_date ) );
			$dek_ue = "Nie";
			$export = 'nie';
			$rejestr='kraj';
		} else if ($value->document_type== 'u') {
			$dek_7 = "";
			$dek_ue = 'Tak';
			$export = 'wewnątrzunijny';
			$rejestr='WNT';
		} else if ($value->document_type== 'e') {
			$export = 'tak';
			$dek_7 = date ( "Ym", strtotime ( $value->active_date ) );
			$dek_ue = 'Nie';
			$rejestr='eksport';
		}
		
		if( $value->category_id=='invoice'){
			$nazwaRej='Koszty';
		}
		if( $value->category_id=='compain_note'){
			$nazwaRej="Materiały";
		}
		if( $value->category_id=='return_note'){
			$nazwaRej="Towary";
		}
		
		$this->addIfNotEmpty ( $fpe, 'REJESTR', $nazwaRej.' '.$rejestr);
		
		$this->addIfNotEmpty ( $fpe, 'EKSPORT', $export );
		
		$relations=$value->getParentList(true);
		$acc = new Account ();
		$acc->retrieve ( $relations[0]['parent_id']);
		$this->addIfNotEmpty ( $fpe, 'FINALNY', ($acc->natural_person ? 'Tak' : 'Nie') );
		$this->addIfNotEmpty ( $fpe, 'PODATNIK_CZYNNY', ($acc->vat_payer ? 'Tak' : 'Nie') );
		
		$this->addIfNotEmpty ( $fpe, 'TYP_PODMIOTU', 'kontrahent' );
		$acc->name=trim(preg_replace('/\s+/', ' ', $acc->name));
		$this->addIfNotEmpty ( $fpe, 'PODMIOT', $acc->name);
		$this->addIfNotEmpty ( $fpe, 'PODMIOT_ID', $acc->id );
		$this->addIfNotEmpty ( $fpe, 'PODMIOT_NIP', $acc->to_vatid );
		
		
		$acc_name = $acc->name;
		
		if (strlen ( $acc_name ) > 50) {
			$this->addIfNotEmpty ( $fpe, 'NAZWA1', mb_substr( $acc_name, 0, 50,'UTF-8') );
			if (strlen ( $acc_name ) > 100) {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', mb_substr( $acc_name, 50, 50,'UTF-8') );
				$this->addIfNotEmpty ( $fpe, 'NAZWA3', mb_substr( $acc_name, 100,null,'UTF-8') );
			} else {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', mb_substr( $acc_name, 50,null,'UTF-8') );
			}
		} else {
			$this->addIfNotEmpty ( $fpe, 'NAZWA1', $acc_name );
		}

		if ($acc->invoice_type == "K") {
			$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', 'PL' );
			$this->addIfNotEmpty ( $fpe, 'NIP', $acc->to_vatid );
		} else {
			$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', substr ( $acc->to_vatid, 0, 2 ) );
			$replace=  substr ( $acc->to_vatid, 0, 2 ) ;
			$this->addIfNotEmpty ( $fpe, 'NIP', str_replace($replace,"",$acc->to_vatid) );
		}
		
	
		
		$acc->billing_address_street=trim(preg_replace('/\s+/', ' ', $acc->billing_address_street));
		preg_match ( '/^([^\d]*[^\d\s]) *(\d.*)$/', $acc->billing_address_street, $matches );
		
		$this->addIfNotEmpty ( $fpe, 'KRAJ', $acc->billing_address_country );
		
		$this->addIfNotEmpty ( $fpe, 'WOJEWÓDZTWO', $acc->billing_address_state );
		// $fpe->addChild('POWIAT',$acc->to_vatid);
		$this->addIfNotEmpty ( $fpe, 'GMINA', $acc->billing_address_ecmcommune_name );
		
		$this->addIfNotEmpty ( $fpe, 'ULICA', $matches [1] );
		
		$numbers = $this->findHomeAndLocale ( $matches [2] );
		$this->addIfNotEmpty ( $fpe, 'NR_DOMU', $numbers [0] );
		$this->addIfNotEmpty ( $fpe, 'NR_LOKALU', $numbers [1] );
		$this->addIfNotEmpty ( $fpe, 'MIASTO', $acc->billing_address_city );
		$this->addIfNotEmpty ( $fpe, 'KOD_POCZTOWY', $acc->billing_address_postalcode );
		$this->addIfNotEmpty ( $fpe, 'ROLNIK', 'NIE' );
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT7', $dek_7 );
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VATUE', $dek_ue );
		
		if ($value->currency_id!='PLN') {
			$cur = new Currency ();
			$cur->retrieve ( $value->currency_id );
			$date = $this->getCurrencyDate ( $value->currency_table, $cur->id );
			$this->addIfNotEmpty ( $fpe, 'WALUTA', $cur->name );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', '--' . $value->currency_value);
		
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', $value->currency_value);
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', $value->currency_value);
			$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', 'Nie' );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY_2', '--' . $value->currency_value);
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE_2', $value->currency_value);
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE_2', $value->currency_value);
			$date = new DateTime( $value->document_date);
			$date->modify("-1 day");
			$this->addIfNotEmpty ( $fpe, 'DATA_KURSU_2',$date->format("Y-m-d"));
			$this->addIfNotEmpty ( $fpe, 'DATA_KURSU', $date->format("Y-m-d"));
			$this->addIfNotEmpty ( $fpe, 'PLATNOSC_VAT_W_PLN', "Nie" );

		} else {
			$fpe->WALUTA='<![CDATA[]]>';
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', 'NBP' );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', '1' );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', '1' );
			$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', "Nie" );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY_2', "NBP" );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE_2', "1" );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE_2', "1" );
			$date = new DateTime( $value->document_date);
			$date->modify("-1 day");
			$this->addIfNotEmpty ( $fpe, 'DATA_KURSU_2',$date->format("Y-m-d"));
			$this->addIfNotEmpty ( $fpe, 'DATA_KURSU',$date->format("Y-m-d"));
			$this->addIfNotEmpty ( $fpe, 'PLATNOSC_VAT_W_PLN', "Nie" );
			
	
		}
		
		$this->addIfNotEmpty ( $fpe, 'JPK_FA', "Tak" );
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT27', "Nie" );
		
		$this->addPurchasePositions ( $fpe, $value );
		
		$platnosci = $fpe->addChild ( 'PLATNOSCI' );
		$header = new SimpleXMLExtended ( '<PLATNOSC></PLATNOSC>', LIBXML_NOEMPTYTAG);
		$platnosc = $header->addChild ( 'PLATNOSC' );
		
		$platnosc->addChild ( 'ID_ZRODLA_PLAT',$value->id);
		$platnosc->addChild ( 'TERMIN_PLAT',date("Y-m-d",strtotime($value->payment_date)));
		
		if($value->left_paid!=""){
			$forma='przelew';
		}
		if($value->payment_method=='GOTÓWKĄ'){
			$forma='gotówka';
		} else {
			$forma='przelew';
		}
		$platnosc->addChild ( 'FORMA_PLATNOSCI_PLAT',$forma);
		$platnosc->addChild ( 'FORMA_PLATNOSCI_ID_PLAT',$acc->id);
		
		
		if ($value->currency_id!='PLN') {
			
			$platnosc->addChild ('WALUTA_PLAT',$cur->name);
			$platnosc->addChild ('WALUTA_DOK',$cur->name);
			$platnosc->addChild ('KURS_WALUTY_PLAT','NBP');
			$platnosc->addChild ('NOTOWANIE_WALUTY_ILE_PLAT',$value->currency_value);
			$platnosc->addChild ('NOTOWANIE_WALUTY_ZA_ILE_PLAT',$value->currency_value);
			
			if($value->corrected_document_name!=null){
				$platnosc->addChild ( 'KWOTA_PLAT',abs($value->value));
				$platnosc->addChild ( 'KWOTA_PLN_PLAT',round(abs($value->value*$value->currency_value),2));
			} else {
				$platnosc->addChild ( 'KWOTA_PLAT',$value->value);
				$platnosc->addChild ( 'KWOTA_PLN_PLAT',round($value->value*$value->currency_value,2));
			}
		
			
			
			$date = $this->getCurrencyDate ( $value->currency_table, $cur->id );
			
			$date = new DateTime( $value->document_date);
			$date->modify("-1 day");
	
			$this->addIfNotEmpty ( $platnosc, 'DATA_KURSU_PLAT',$date->format("Y-m-d"));
			
		} else {
			
			$platnosc->WALUTA_PLAT='<![CDATA[]]>';
			$platnosc->WALUTA_DOK='<![CDATA[]]>';
			
			$platnosc->addChild ('KURS_WALUTY_PLAT','NBP');
			$platnosc->addChild ('NOTOWANIE_WALUTY_ILE_PLAT','1');
			$platnosc->addChild ('NOTOWANIE_WALUTY_ZA_ILE_PLAT','1');
			if($value->corrected_document_name!=null){
				$platnosc->addChild ( 'KWOTA_PLAT',abs($value->value));
				$platnosc->addChild ( 'KWOTA_PLN_PLAT',abs($value->value));
			}
			else {
				$platnosc->addChild ( 'KWOTA_PLAT',$value->value);
				$platnosc->addChild ( 'KWOTA_PLN_PLAT',$value->value);
			}
		
			
			
		}
		$platnosc->addChild ( 'KIERUNEK','rozchód');
		$platnosc->addChild ( 'PODLEGA_ROZLICZENIU','tak');
		//$platnosc->addChild ( 'KONTO','');
		$platnosc->addChild ( 'NIE_NALICZAJ_ODSETEK','Nie');
		$platnosc->addChild ( 'PRZELEW_SEPA','Nie');
		//	$platnosc->addChild ( 'DATA_KURSU_PLAT','przychód');
		$platnosc->addChild ( 'PLATNOSC_TYP_PODMIOTU','kontrahent');
		
		
		if($value->parent_payer_address_name!=""){
			$obj= new Account();
			$value->parent_payer_address_nip=str_replace("-","",str_replace(" ","",$value->parent_payer_address_nip));
			$obj->retrieve_by_string_fields(['to_vatid'=>$value->parent_payer_address_nip]);
			
			$platnosc->addChild ( 'PLATNOSC_PODMIOT',$obj->name);
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_ID',$obj->id );
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_NIP',$value->parent_payer_address_nip);
		} else {
			
			$platnosc->addChild ( 'PLATNOSC_PODMIOT',$acc->name);
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_ID',$acc->name);
			$platnosc->addChild ( 'PLATNOSC_PODMIOT_NIP',$acc->to_vatid);
		}
		/*
		 $platnosc->addChild ( 'PLAT_ELIXIR_O1','');
		 $platnosc->addChild ( 'PLAT_ELIXIR_O2','');
		 $platnosc->addChild ( 'PLAT_ELIXIR_O3','');
		 $platnosc->addChild ( 'PLAT_ELIXIR_O4','');
		 */
		$this->xml_adopt ( $platnosci, $platnosc);
		
		$this->xml_adopt ( $fpn, $fpe );
		
		return $fpn;
	}
	#showVatList
	public function addPurchasePositions($node, $object) {
		$pozycje = $node->addChild ( 'POZYCJE' );
		$positions = $object->showVatList( true );
		
		global $app_list_strings;
		
		foreach ( $positions as $position ) {
			if($position['netto']=='NaN' || $position['vat']=='NaN')continue;
			if($position['netto']=='0')continue;
			$header = new SimpleXMLExtended ( '<POZYCJA></POZYCJA>' );
			$fpe = $header->addChild ( 'POZYCJA' );
			$fpe->addChild ( 'STAWKA_VAT', str_replace("%","",$position ['vat_id'] ));
			$fpe->addChild ( 'STATUS_VAT', 'opodatkowana' );
			$fpe->addChild ( 'NETTO', $position ['netto'] );
			$fpe->addChild ( 'VAT', $position ['vat'] );
			
		
			
				
				$fpe->addChild ( 'NETTO_SYS', round ( $position ['netto'] * ($object->currency_value!="" ? $object->currency_value : 1), 2 ) );
				$fpe->addChild ( 'VAT_SYS', round ( $position ['vat'] * ($object->currency_value!="" ? $object->currency_value : 1), 2 ) );
				
				$fpe->addChild ( 'NETTO_SYS2', round ( $position ['netto'] * ($object->currency_value!="" ? $object->currency_value : 1), 2 ) );
				$fpe->addChild ( 'VAT_SYS2', round ( $position ['vat'] * ($object->currency_value!="" ? $object->currency_value : 1), 2 ) );
			
			$fpe->addChild ( 'RODZAJ_ZAKUPU','towary' );
			
			$this->xml_adopt ( $pozycje, $fpe );
		}
	}
	
	public function getCurrencyDate($nbp, $cur_id) {
		$res = $this->db->query ( "select date from currency_nbp_archive where currency_id='" . $cur_id . "' and nbp_table_name='" . $nbp . "'" );
		
		$dane = $this->db->fetchByAssoc ( $res );
		
		return $dane ['date'];
	}
	public function addIfNotEmpty(&$object, $key, $value) {
		if ($value) {
			if ($value != "") {
				$object->addChild ( $key, $value );
			}
		}
	}
	public function findHomeAndLocale($numbers) {
		$numbers = str_replace ( " ", "", $numbers );
		
		$pos = strpos ( $numbers, '/' );
		if ($pos !== false) {
			return implode ( '/', $numbers );
		}
		
		return [$numbers];
	}
	public function xml_adopt($root, $new) {
		$node = $root->addChild ( $new->getName (), ( string ) $new );
		foreach ( $new->attributes () as $attr => $value ) {
			$node->addAttribute ( $attr, $value );
		}
		foreach ( $new->children () as $ch ) {
			self::xml_adopt ( $node, $ch );
		}
	}
	public function getInvoicesObject() {
		$invoices = new EcmInvoiceOut ();
		$invoices = $invoices->get_full_list ( null, "register_date>='" . $this->date_from . "' and register_date<='" . $this->date_to . "'" );
		#$invoices = $invoices->get_full_list ( null, "ecminvoiceouts.id='104e0cd3-1aac-2927-e76f-599d1ce26b60'" );
		
		return $invoices;
	}
	public function getAccounts() {
		$invoices = new Account();
		$invoices = $invoices->get_full_list ( null, "" );

		return $invoices;
	}
	
	
	
	public function getDocumentsObiect() {
		$documents = new Document ();
		$documents= $documents->get_full_list ( null, "document_date>='" . $this->date_from . "' and document_date<='" . $this->date_to . "' and category_id in ('invoice','compain_note','return_note')" );
		
		return $documents;
	}
	
	public function getPzObiect() {
		$documents = new EcmStockDocIn ();
		$documents= $documents->get_full_list ( null, "register_date>='" . $this->date_from . "' and register_date<='" . $this->date_to . "'" );
		
		return $documents;
	}
	
	public function getPwObiect() {
		$documents = new EcmStockDocInsideIn ();
		$documents= $documents->get_full_list ( null, "register_date>='" . $this->date_from . "' and register_date<='" . $this->date_to . "'" );
		
		return $documents;
	}
	
	public function adPzDocuments() {
		global $app_list_strings;
		
		$payment_methods = $app_list_strings ['payment_method_dom'];
		
		$fpn = new SimpleXMLExtended ( '<DOKUMENTY_INNE_PRZYCHOD></DOKUMENTY_INNE_PRZYCHOD>' );
		
		$fpn->addChild ( 'WERSJA', OptimaXMLConstant::WERSJA );
		$fpn->addChild ( 'BAZA_ZRD_ID', OptimaXMLConstant::BAZA_ZRD_ID );
		$fpn->addChild ( 'BAZA_DOC_ID', OptimaXMLConstant::BAZA_DOC_ID );
		
		
		foreach ( $this->getPzObiect() as $value ) {
			
			$fpn = $this->adPzDocument( $value, $fpn );
		}
		
		$this->xml_adopt ( $this->optimaXML->basicXML, $fpn );

		echo $this->optimaXML->basicXML->asXml();
		
	}
	
	public function adPzDocument($value, $fpn) {
		$header = new SimpleXMLExtended ( '<DOKUMENT_INNY_PRZYCHOD></DOKUMENT_INNY_PRZYCHOD>' );
		$fpe = $header->addChild ( 'DOKUMENT_INNY_PRZYCHOD' );
		
		$this->addIfNotEmpty ( $fpe, 'ID_ZRODLA', $value->id );
		$this->addIfNotEmpty ( $fpe, 'SYMBOL_DOKUMENTU', '777D9054-1C7D-4B4D-970D-4FFFF7EA84E1' );
		$this->addIfNotEmpty ( $fpe, 'REJESTR', 'PRZYCHODY' );
		$this->addIfNotEmpty ( $fpe, 'DATA_WYSTAWIENIA', date ( "Y-m-d", strtotime ( $value->register_date) ) );
		$this->addIfNotEmpty ( $fpe, 'DATA_OPERACJI', date ( "Y-m-d", strtotime ( $value->register_date) ) );
		$this->addIfNotEmpty ( $fpe, 'DATA_WPLYWU', date ( "Y-m-d", strtotime ( $value->data_fk) ) );
		$fpe->addChildWithCDATA('NUMER', $value->document_no);
		
		$acc = new Account ();
		$acc->retrieve($value->parent_id);
		$this->addIfNotEmpty ( $fpe, 'TYP_PODMIOTU', 'kontrahent' );
		
		$this->addIfNotEmpty ( $fpe, 'PODMIOT', $acc->index_dbf );
		$this->addIfNotEmpty ( $fpe, 'PODMIOT_ID', $acc->id );
		$this->addIfNotEmpty ( $fpe, 'PODMIOT_NIP', $acc->to_vatid );
		
		$acc_name = $acc->name;
		
		if (strlen ( $acc_name ) > 50) {
			$this->addIfNotEmpty ( $fpe, 'NAZWA1', mb_substr ( $acc_name, 0, 50,'UTF-8' ) );
			if (strlen ( $acc_name ) > 100) {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', mb_substr( $acc_name, 50, 50,'UTF-8') );
				$this->addIfNotEmpty ( $fpe, 'NAZWA3', mb_substr( $acc_name, 100,null,'UTF-8') );
			} else {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', mb_substr( $acc_name, 50,null,'UTF-8') );
			}
		} else {
			$this->addIfNotEmpty ( $fpe, 'NAZWA1', $acc_name );
		}
		
		if ($acc->invoice_type == "K") {
			$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', 'PL' );
		} else {
			$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', substr ( $acc->to_vatid, 0, 2 ) );
		}
		
		$this->addIfNotEmpty ( $fpe, 'NIP', $acc->to_vatid );
		
		preg_match ( '/^([^\d]*[^\d\s]) *(\d.*)$/', $acc->billing_address_street, $matches );
		
		$this->addIfNotEmpty ( $fpe, 'KRAJ', $acc->billing_address_country );
		
		$this->addIfNotEmpty ( $fpe, 'WOJEWÓDZTWO', $acc->billing_address_state );
		// $fpe->addChild('POWIAT',$acc->to_vatid);
		$this->addIfNotEmpty ( $fpe, 'GMINA', $acc->billing_address_ecmcommune_name );
		
		$this->addIfNotEmpty ( $fpe, 'ULICA', $matches [1] );
		
		$numbers = $this->findHomeAndLocale ( $matches [2] );
		$this->addIfNotEmpty ( $fpe, 'NR_DOMU', $numbers [0] );
		$this->addIfNotEmpty ( $fpe, 'NR_LOKALU', $numbers [1] );
		$this->addIfNotEmpty ( $fpe, 'MIASTO', $acc->billing_address_city );
		$this->addIfNotEmpty ( $fpe, 'KOD_POCZTOWY', $acc->billing_address_postalcode );
		$this->addIfNotEmpty ( $fpe, 'MAGAZYN_ZRODLOWY', $value->stock_name );
		$this->addIfNotEmpty ( $fpe, 'KWOTA_RAZEM', $value->total );
		
		$this->addIfNotEmpty ( $fpe, 'GENERACJA_PLATNOSCI', 'Nie' );
		if ($value->currency_id!='PLN') {
			$cur = new Currency ();
			$cur->retrieve ( $value->currency_id );
			$date = $this->getCurrencyDate ( $value->currency_table, $cur->id );
			$this->addIfNotEmpty ( $fpe, 'WALUTA', $cur->name );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', '--' . $value->currency_value);
			$this->addIfNotEmpty ( $fpe, 'DATA_KURSU', date ( "Y-m-d", strtotime ( $date ) ) );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', $value->currency_value);
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', $value->currency_value);
			$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', 'Nie' );
			
		} else {
			$this->addIfNotEmpty ( $fpe, 'WALUTA', 'PLN' );
			$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', 'Nie' );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', '1' );
			$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', '1' );
			$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', "Nie" );
			
		}
		
		$this->addPzPositions ( $fpe, $value );
		
		$this->xml_adopt ( $fpn, $fpe );
		
		return $fpn;
	}

	public function addPzPositions($node, $object) {
		$pozycje = $node->addChild ( 'POZYCJE' );
		$positions = $object->getPositionList( true );
		
		global $app_list_strings;
		
		foreach ( $positions as $position ) {
			$header = new SimpleXMLExtended ( '<POZYCJA></POZYCJA>' );
			$fpe = $header->addChild ( 'POZYCJA' );

			$fpe->addChild ( 'KWOTA_SYS', $position ['total'] );
		

			
			$this->xml_adopt ( $pozycje, $fpe );
		}
	}
	
	function xml_entities($string) {
		return strtr(
				$string,
				array(
						 "&lt;"=>"<",
						"&gt;" => 	">",
					
				)
				);
	}
	public function saveFile(){
		 
		$dom=new DOMDocument("1.0","UTF-8");
		unlink('2.xml'); 
		file_put_contents("2.xml",$this->optimaXML->basicXML->asXML ());
	$dom->loadXML(file_get_contents("2.xml"));  
//		$dom->loadXML(mb_convert_encoding(str_replace('"',"'",$this->optimaXML->basicXML->asXML ()), 'HTML-ENTITIES', 'UTF-8'));
		$dom->formatOutput=false;
	
		$content= $dom->saveXML(null,LIBXML_NOEMPTYTAG);
		unlink('xx.xml');
		file_put_contents('xx.xml',$this->xml_entities($content));
	}
}

$exportOptima = new ExportOptima ( '04.08.2017', new OptimaXML () );
$exportOptima->loadXmlObject ();
$exportOptima->addAccounts();
$exportOptima->addInvoiceDocuments ();
$exportOptima->addPurchaseDocuments ();
#$exportOptima->adPzDocuments();
#$exportOptima->adPwDocuments();

$exportOptima->saveFile();
?>