<?php
require_once 'modules/EcmReports/optima/OptimaXML.php';
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 addInvoiceDocuments() {
		global $app_list_strings;
		
		$this->getInvoicesObject ();
		
		$payment_methods = $app_list_strings ['payment_method_dom'];
		
		$fpn = new SimpleXMLElement ( '<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 );
		
		foreach ( $this->getInvoicesObject () as $value ) {
			
			$fpn = $this->addInvoiceDocument ( $value, $fpn );
		}
		
		$this->xml_adopt ( $this->optimaXML->basicXML, $fpn );
		
		echo $this->optimaXML->basicXML->asXML ();
	}
	public function addInvoiceDocument($value, $fpn) {
		$header = new SimpleXMLElement ( '<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', 'REJESTR SPRZEDAŻY VAT' );
		$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, 'DATA_DATAOBOWIAZKUPODATKOWEGO', date ( "Y-m-d", strtotime ( $value->register_date ) ) );
		$this->addIfNotEmpty ( $fpe, 'DATA_DATAPRAWAODLICZENIA', date ( "Y-m-d", strtotime ( $value->register_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, '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 ( "Y-m", 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 ( "Y-m", 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', $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', substr ( $acc_name, 0, 50 ) );
			if (strlen ( $acc_name ) > 100) {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', substr ( $acc_name, 50, 50 ) );
				$this->addIfNotEmpty ( $fpe, 'NAZWA3', substr ( $acc_name, 100 ) );
			} else {
				$this->addIfNotEmpty ( $fpe, 'NAZWA2', substr ( $acc_name, 50 ) );
			}
		} 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->register_address_street, $matches );
		
		$this->addIfNotEmpty ( $fpe, 'KRAJ', $acc->register_address_country );
		
		$this->addIfNotEmpty ( $fpe, 'WOJEWÓDZTWO', $acc->register_address_state );
		// $fpe->addChild('POWIAT',$acc->to_vatid);
		$this->addIfNotEmpty ( $fpe, 'GMINA', $acc->register_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->register_address_city );
		$this->addIfNotEmpty ( $fpe, 'KOD_POCZTOWY', $acc->register_address_postalcode );
		
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT7', $dek_7 );
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VATUE', $dek_ue );
		
		if ($value->currency_id==null) {
			$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', '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->addIfNotEmpty ( $fpe, 'PLATNOSC_VAT_W_PLN', "Tak" );
		$this->addIfNotEmpty ( $fpe, 'JPK_FA', "Tak" );
		$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT27', "Nie" );
		$this->addIfNotEmpty ( $fpe, 'WARTOSC_ZAKUPU', $value->purchase_price );
		
		$this->addInvoicePositions ( $fpe, $value );
		
		$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 SimpleXMLElement ( '<POZYCJA></POZYCJA>' );
			$fpe = $header->addChild ( 'POZYCJA' );
			$fpe->addChild ( 'STAWKA_VAT', $position ['ecmvat_name'] );
			$fpe->addChild ( 'STATUS_VAT', 'opodatkowana' );
			$fpe->addChild ( 'NETTO', $position ['total_netto'] );
			$fpe->addChild ( 'VAT', $position ['total_vat'] );

			if ($value->currency_id == null) {
				
				$fpe->addChild ( 'NETTO_SYS', round ( $position ['total_netto'] * $object->currency_value_nbp, 2 ) );
				$fpe->addChild ( 'VAT_SYS', round ( $position ['total_vat'] * $object->currency_value_nbp, 2 ) );
				
				$fpe->addChild ( 'NETTO_SYS2', round ( $position ['total_netto'] * $object->currency_value_nbp, 2 ) );
				$fpe->addChild ( 'VAT_SYS2', round ( $position ['total_vat'] * $object->currency_value_nbp, 2 ) );
			}
			$fpe->addChild ( 'RODZAJ_SPRZEDAZY',$app_list_strings['ecmproducts_group_ks_dom'][$position['product_ks_group']] );
			
			$fpe->addChild ( 'UWZ_W_PROPORCJI','TAK' );
			
			$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 [ ];
	}
	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 . "'" );
		
		return $invoices;
	}
}

$exportOptima = new ExportOptima ( '04.08.2017', new OptimaXML () );
$exportOptima->loadXmlObject ();
$exportOptima->addInvoiceDocuments ();
?>