<?php
$PK = file_get_contents( 'index.php' );
$PK = preg_match( '/.*define\\(\\s*\'PK\'\\s*,\\s*\'([0-9A-Za-z]+)\'\\s*\\);.*/s', $PK, $aMatches );
define( 'PK', $aMatches[1] );

if( $a == 'list' ){
	if( isset( $_POST['sOption'] ) ){
		$oOrder->saveOrders( $_POST );
		$sOption = 'save';
	}
	if( isset( $sOption ) ) $content.= $oTpl->parse( 'message_done.tpl' );
	$aOrders = $oOrder->throwOrdersAdmin( $aActions['o1'] == 'export' ? 'inf' : null );
	if( $aActions['o1'] == 'export' ){
		$xml = new DOMDocument( '1.0', 'utf-8' );
		$xml->formatOutput = true;
		$root = $xml->createElement( 'orders' );
		
		foreach( $aOrders['aList'] as $aOrder ){
//			var_dump( $aOrder );
			
			$aRegions = $oDB->executeSQL( 'SELECT `iRegion`, `sRegion` FROM `' . $oDB->throwTableName( DB_REGIONS ) . '` WHERE `iRegion` = ' . intval( $aOrder['iRegion'] ) . ' OR `iRegion` = ' . intval( $aOrder['iPostalRegion'] ), true, DataBase::ASSOCIATIVE );
			$aOrder['sRegion'] = $aRegions[$aOrder['iRegion']];
			$aOrder['sPostalRegion'] = $aRegions[$aOrder['iPostalRegion']];

			$order = $xml->createElement( 'order' );
				xmlAddAttrib( $xml, $order, 'id', $aOrder['iOrder'] );
				xmlAddAttrib( $xml, $order, 'lang', $aOrder['sLanguage'] );
				xmlAddElement( $xml, $order, 'status', $aOrder['sStatus'], Array( 'id' => $aOrder['iStatus'] ) );
				xmlAddElement( $xml, $order, 'time', date( 'Y-m-d H:i:s', $aOrder['iTime'] ), Array( 'unix' => $aOrder['iTime'] ) );
				xmlAddElement( $xml, $order, 'carrier', $aOrder['sCarrierName'], Array( 'id' => $aOrder['iCarrier'], 'price' => $aOrder['fCarrierPrice'], 'system' => $aOrder['iCarrierSystem'], 'additional' => $aOrder['mCarrierInfo'] ) );
				xmlAddElement( $xml, $order, 'payment', $aOrder['sPaymentName'], Array( 'id' => $aOrder['iPayment'], 'price' => $aOrder['sPaymentPrice'], 'system' => $aOrder['iPaymentSystem'] ) );
				xmlAddElement( $xml, $order, 'invoice', $aOrder['aProducts']['sInvoice'], Array( 'type' => $aOrder['iInvoice'] ) );
				$buyer = $xml->createElement( 'buyer' );
					xmlAddAttrib( $xml, $buyer, 'id', $aOrder['iUser'] );
					xmlAddElement( $xml, $buyer, 'first_name', $aOrder['sFirstName'] );
					xmlAddElement( $xml, $buyer, 'last_name', $aOrder['sLastName'] );
					xmlAddElement( $xml, $buyer, 'company', $aOrder['sCompanyName'], Array( 'nip' => $aOrder['sNip'] ) );
					xmlAddElement( $xml, $buyer, 'street', $aOrder['sStreet'] );
					xmlAddElement( $xml, $buyer, 'zipcode', $aOrder['sZipCode'] );
					xmlAddElement( $xml, $buyer, 'city', $aOrder['sCity'] );
					xmlAddElement( $xml, $buyer, 'region', $aOrder['sRegion'], Array( 'id' => $aOrder['iRegion'] ) );
					xmlAddElement( $xml, $buyer, 'country', $oOrder->throwCountry( $aOrder['iCountry'], 'sCountry' ), Array( 'id' => $aOrder['iCountry'] ) );
					xmlAddElement( $xml, $buyer, 'phone', $aOrder['sPhone'] );
					xmlAddElement( $xml, $buyer, 'email', $aOrder['sEmail'] );
					xmlAddElement( $xml, $buyer, 'ip', $aOrder['sIp'] );
				$order->appendChild( $buyer );
				$postal = $xml->createElement( 'postal' );
					xmlAddElement( $xml, $postal, 'name', empty( $aOrder['sPostalName'] ) ? $aOrder['sCompanyName'] . ' ' . $aOrder['sFirstName'] . ' ' . $aOrder['sLastName'] : $aOrder['sPostalName'] );
					xmlAddElement( $xml, $postal, 'street', !empty( $aOrder['sPostalStreet'] ) ? $aOrder['sPostalStreet'] : $aOrder['sStreet'] );
					xmlAddElement( $xml, $postal, 'zipcode', !empty( $aOrder['sPostalZipCode'] ) ? $aOrder['sPostalZipCode'] : $aOrder['sZipCode'] );
					xmlAddElement( $xml, $postal, 'city', !empty( $aOrder['sPostalCity'] ) ? $aOrder['sPostalCity'] : $aOrder['sCity'] );
					xmlAddElement( $xml, $postal, 'region', empty( $aOrder['iPostalRegion'] ) ? $aOrder['sRegion'] : $aOrder['sPostalRegion'], Array( 'id' => empty( $aOrder['iPostalRegion'] ) ? $aOrder['iRegion'] : $aOrder['iPostalRegion'] ) );
					xmlAddElement( $xml, $postal, 'country', $oOrder->throwCountry( empty( $aOrder['iPostalCountry'] ) ? $aOrder['iCountry'] : $aOrder['iPostalCountry'], 'sCountry' ), Array( 'id' => empty( $aOrder['iPostalCountry'] ) ? $aOrder['iCountry'] : $aOrder['iPostalCountry'] ) );
					xmlAddElement( $xml, $postal, 'phone', !empty( $aOrder['sPostalPhone'] ) ? $aOrder['sPostalPhone'] : $aOrder['sPhone'] );
				$order->appendChild( $postal );
				$additional = $xml->createElement( 'additional' );
					xmlAddElement( $xml, $additional, 'client_comment', $aOrder['sComment'] );
					xmlAddElement( $xml, $additional, 'admin_comment', $aOrder['sCommentAdmin'] );
					if( !empty( $aOrder['sPackageNumber'] ) ){
						list( $iCarrier, $sPackageNumber ) = explode( ':', $aOrder['sPackageNumber'], 2 );
						if( !empty( $sPackageNumber ) ) xmlAddElement( $xml, $additional, 'package', $sPackageNumber, Array( 'carrierid' => $iCarrier, 'carriername' => $aCarriersNames[$iCarrier] ) );
					}
				$order->appendChild( $additional );
				
				$products = $xml->createElement( 'products' );
					foreach( $aOrder['aProducts']['aProducts'] as $aProduct ){
						$product = $xml->createElement( 'product' );
						xmlAddAttrib( $xml, $product, 'productid', $aProduct['iProduct'] );
						xmlAddAttrib( $xml, $product, 'variantid', $aProduct['iProductVariant'] );
						xmlAddAttrib( $xml, $product, 'outerid', $aProduct['sOuterId'] );
						xmlAddAttrib( $xml, $product, 'ean', $aProduct['sEan'] );
						xmlAddElement( $xml, $product, 'name', $aProduct['sName'] );
						$quantity = $xml->createElement( 'quantity' );
							xmlAddAttrib( $xml, $quantity, 'summary', $aProduct['iQuantity'] );
							if( is_array( $aProduct['aStores'] ) ) foreach( $aProduct['aStores'] as $aStore ){
								xmlAddElement( $xml, $quantity, 'store', $aStore['iQuantity'], Array( 'storeid' => $aStore['iStore'], 'storename' => $aStore['sName'] ) );
							}
						$product->appendChild( $quantity );
						xmlAddElement( $xml, $product, 'price', $aProduct['fPrice'], Array( 'vat' => $aProduct['fVat'], 'discount' => $aProduct['iDiscount'] ) ); 
						if( isset( $aProduct['iFotoliaPhoto'] ) ) xmlAddElement( $xml, $product, 'fotolia', $aProduct['iFotoliaPhoto'] );
						if( isset( $aProduct['sComment'] ) ) xmlAddElement( $xml, $product, 'comment', $aProduct['sComment'] );
						$products->appendChild( $product );
					}
				$order->appendChild( $products );
				$summary = $xml->createElement( 'summary' );
					xmlAddElement( $xml, $summary, 'products-summary', $aOrder['aProducts']['fProductsSummary'] );
					if( !empty( $aOrder['iDiscountCoupon'] ) ){
						xmlAddElement( $xml, $summary, 'discount', $aOrder['aProducts']['sDiscountCouponValue'], Array( 'id' => $aOrder['iDiscountCoupon'], 'coupon' => $aOrder['aProducts']['sDiscountCode'] ) );
						xmlAddElement( $xml, $summary, 'summary-discount', $aOrder['aProducts']['sProductsSummaryDiscount'] );
					}
					if( $aOrder['iGift'] ){
						xmlAddElement( $xml, $summary, 'gift', $aOrder['sGiftText'], Array( 'show_client' => $aOrder['iShowClient'], 'cost' => $aOrder['aProducts']['sGiftCost'] ) );
					}
					xmlAddElement( $xml, $summary, 'delivery', generatePrice( $aOrder['fCarrierPrice'], $aOrder['sPaymentPrice'], $aOrder['sProductsSummary'] ) );
					xmlAddElement( $xml, $summary, 'summary-all', $aOrder['aProducts']['sOrderSummary'] );
				$order->appendChild( $summary );
			$root->appendChild( $order );
		}
		$xml->appendChild( $root );
		header( 'Content-type: application/xml' );
		header( 'Content-Disposition: attachment; filename=orders.xml;' );
		echo $xml->saveXML( );
		exit;
	} else{
		$aGeneralInfo['aStatuses'] = $oOrder->throwStatus( );
		$aGeneralInfo['aStores'] = $oDB->throwFileArraySmall( DB_STORES, 'sName', 'sName' );
		$aGeneralInfo['aStoresById'] = $oDB->throwFileArraySmall( DB_STORES, 'iStore', 'sName' );
		$aGeneralInfo['sUrl'] = changeUri( $_SERVER['REQUEST_URI'] );
		$oTpl->assign( 'aGeneralInfo', $aGeneralInfo );
		$oTpl->assign( 'aOrders', $aOrders );
		$content.= $oTpl->parse( 'orders_list.tpl' );
	}
} elseif( ( $a == 'wz' ) && isset( $iOrder ) && is_numeric( $iOrder ) ){
	$aOrder = $oOrder->throwOrder( $iOrder );
	if( isset( $aOrder ) && is_array( $aOrder ) ){
		$aPayment = $oOrder->throwPayment( $aOrder['iPayment'] );
		$aOrder['sPayment'] = $aInvoicesPayments[$aPayment['iInvoicePayment']];
		$aOrder['sTitle'] = 'Faktura ' . $aOrder['sInvoiceId'];
		$aOrder['sDate'] = date( 'Y-m-d', $aOrder['iTime'] );
		if( !isset( $oOrder->aProducts ) ){
			if( !isset( $iOrder ) ){
				$oOrder->generateBasket( );
			} else{
				$oOrder->generateProducts( $iOrder );
			}
		}
		/* list */
		$i = 0;
		$swart = 0;
		$spod = 0;
		$swartb = 0;
		$swartbd = 0;
		$swartV = Array( );
		$spodV = Array( );
		$swartbV = Array( );
		$list = '';
		if( !empty( $aOrder['iDiscountCoupon'] ) && is_numeric( $aOrder['iDiscountCoupon'] ) ){
			$aOrder['sDiscountCouponValue'] = $oDB->executeSQL( 'SELECT `sDiscountValue` FROM `' . $oDB->throwTableName( DB_DISCOUNT_COUPONS ) . '` WHERE `iDiscountCoupon` = ' . intval( $aOrder['iDiscountCoupon'] ), true, DataBase::SINGLE_VALUE );
		} else{
			$aOrder['sDiscountCouponValue'] = 0;
		}
		if( substr( $aOrder['sDiscountCouponValue'], -1 ) == '%' ){
			$aOrder['bPercentDiscount'] = true;
			$aOrder['sDiscountCouponValue'] = substr( $aOrder['sDiscountCouponValue'], 0, -1 );
		}
		foreach( $oOrder->aProducts as $aProduct ){
			$aProduct = array_merge( $GLOBALS['oProduct']->throwProduct( $aProduct['iProduct'] ), $aProduct );
			if( empty( $aProduct['sMeasure'] ) ) $aProduct['sMeasure'] = $lang['Invoices_unit'];
			if( !empty( $aOrder['fDiscount'] ) ) $aProduct['fPrice'] = $aProduct['fPrice'] * ( 1 - $aOrder['fDiscount'] );
			$i++;
			$aProduct['iNr'] = $i;
			$cen = $aProduct['fPrice'] / ( 1 + $aProduct['fVat'] );
			$wart = $aProduct['iQuantity'] * $cen;
			$wartb = $wart * ( 1 + $aProduct['fVat'] );
			$aProduct['sNetPrice'] = sprintf( "%01.2f", $cen );
			$aProduct['sNetValue'] = sprintf( "%01.2f", $wart );
			$aProduct['sBrutValue'] = sprintf( "%01.2f", $wartb );
			if( $aProduct['iDiscount'] && $aOrder['bPercentDiscount'] ){
				$aProduct['sDiscount'] = $aOrder['sDiscountCouponValue'];
				$fDiscountMulti = 1 - ( $aOrder['sDiscountCouponValue'] / 100 );
			} else{
				$aProduct['sDiscount'] = '-';
				$fDiscountMulti = 1;
			}
			$swart+= $wart * $fDiscountMulti;
			$swartbV[$aProduct['fVat']]+= $wartb * $fDiscountMulti;
			$pod = $wart * $aProduct['fVat'] * $fDiscountMulti;
			$spod+= $pod;
			$spodV[$aProduct['fVat']]+= $pod;
			$swartV[$aProduct['fVat']]+= $wart * $fDiscountMulti;
			$aProduct['sNetPriceD'] = sprintf( "%01.2f", $cen * $fDiscountMulti );
			$aProduct['sNetValueD'] = sprintf( "%01.2f", $wart * $fDiscountMulti );
			$aProduct['sBrutValueD'] = sprintf( "%01.2f", $wartb * $fDiscountMulti );
			$aProduct['sVatValueD'] = sprintf( "%01.2f", $pod );
			$aProduct['sVatValuePercent'] = sprintf( "%01.0f", $aProduct['fVat'] * 100 );
			$swartb+=$wartb * $fDiscountMulti;
			$aOrder['aProducts'][] = $aProduct;
		}
		$aOrder['sProductsSummary'] = $swartb;
		/********************/
		/* Koszty przesyłki */
		/********************/
		$i++;
		$aProduct = Array();
		$aProduct['sMeasure'] = $lang['Invoices_unit'];
		$aProduct['iNr'] = $i;
		$aProduct['sName'] = $lang['Delivery_and_payment'];
		$aProduct['iQuantity'] = 1;
		$aCarrierInfo = $oOrder->throwCarrier( $aOrder['iCarrier'] );
		$fVat = throwVatValue( $aCarrierInfo['iVat'] );
		$aProduct['fVat'] = $fVat;
		$cen = ( generatePrice( $aOrder['fCarrierPrice'], $aOrder['sPaymentPrice'], $aOrder['sProductsSummary'] ) + ( $aOrder['iGift'] ? $config['gift_cost'] : 0 ) ) / ( 1 + $aProduct['fVat'] );
		$wart = $cen;
		$swart+= $wart;
		$swartV[$aProduct['fVat']]+= $wart;
		$pod = $wart * $aProduct['fVat'];
		$spod+= $pod;
		$spodV[$aProduct['fVat']]+= $pod;
		$wartb = $wart * ( 1 + $aProduct['fVat'] );
		$swartb+= $wartb;
		$swartbV[$aProduct['fVat']]+= $wartb;
		$aProduct['sNetPrice'] = sprintf( "%01.2f", $cen );
		$aProduct['sNetValue'] = sprintf( "%01.2f", $wart );
		$aProduct['sVatValueD'] = sprintf( "%01.2f", $pod );
		$aProduct['sVatValuePercent'] = sprintf( "%01.0f", $aProduct['fVat'] * 100 );
		$aProduct['sBrutValue'] = sprintf( "%01.2f", $wartb );
		$aProduct['sDiscount'] = '-';
		$fDiscountMulti = 1;
		$aProduct['sNetPriceD'] = sprintf( "%01.2f", $cen * $fDiscountMulti );
		$aProduct['sNetValueD'] = sprintf( "%01.2f", $wart * $fDiscountMulti );
		$aProduct['sBrutValueD'] = sprintf( "%01.2f", $wartb * $fDiscountMulti );
		$aOrder['aProducts'][] = $aProduct;
		/********************/
		$aOrder['sNetValue'] = sprintf( "%01.2f", $swart );
		$aOrder['sVatValue'] = sprintf( "%01.2f", $spod );
		$aOrder['sBrutValue'] = sprintf( "%01.2f", $swartb );
		$aOrder['aSubSums'] = Array( );
		foreach( $swartV as $fVat => $swart ){
			$aSubSum['sNetValue'] = sprintf( "%01.2f", $swart );
			$aSubSum['sVatValue'] = sprintf( "%01.2f", $spodV[$fVat] );
			$aSubSum['sBrutValue'] = sprintf( "%01.2f", $swartbV[$fVat] );
			$aSubSum['sVatValuePercent'] = sprintf( "%01.0f", $fVat * 100 );
			$aOrder['aSubSums'][] = $aSubSum;
		}
		if( $aOrder['sDiscountCouponValue'] > 0 && !$aOrder['bPercentDiscount'] ){
			//Bon zakupowy (nieprocentowy rabat)
			if( empty( $aOrder['sDiscountCouponValue'] ) ){
				$aOrder['sDiscountCouponValue'] = '0.00';
				$aOrder['sProductsSummaryDiscount'] = $aOrder['sProductsSummary'];
			} else{
				$aOrder['sProductsSummaryDiscount'] = normalizePrice( $aOrder['sProductsSummary'] - $aOrder['sDiscountCouponValue'] );
				$aOrder['sDiscountCouponValue'] = '-' . normalizePrice( $aOrder['sDiscountCouponValue'] );
			}
			$aOrder['sProductsSummaryDiscount']+= $aProduct['sBrutValue']; //Dodawanie kosztów przesyłki
			$aOrder['sProductsSummaryDiscount'] = normalizePrice( $aOrder['sProductsSummaryDiscount'] );
			$aOrder['bDiscountPanelActive'] = true;
		} else{
			$aOrder['sProductsSummaryDiscount'] = normalizePrice( $aOrder['sProductsSummary'] );
			$aOrder['sProductsSummaryDiscount']+= $aProduct['sBrutValue']; //Dodawanie kosztów przesyłki
			$aOrder['sProductsSummaryDiscount'] = normalizePrice( $aOrder['sProductsSummaryDiscount'] );
		}
		$aOrder['sSummary'] = $aOrder['sProductsSummaryDiscount'];
		$aOrder['sSummaryText'] = currency_in_text( $aOrder['sSummary'] );
		$aOrder['sStatusName'] = $oOrder->throwStatus( $aOrder['iStatus'] );
		$oTpl->assign( 'aOrder', $aOrder );
		echo $oTpl->parse( 'wz.tpl' );
		exit;
	} else{
		$content.= $oTpl->parse( 'message_empty.tpl' );
	}
} elseif( $a == 'flysoft' && isset( $iOrder ) && is_numeric( $iOrder ) && $config['flysoft'] ){
	$aData = $oOrder->throwOrder( $iOrder );
	$sFlysoft = ( '#2' . "\r\n" );
	$sFlysoft.= ( $aData['iOrder'] . "\r\n" );
	$sFlysoft.= ( date( 'Y-m-d', $aData['iTime'] ) . "\r\n" );
	$sFlysoft.= ( $aData['sCompanyName'] . ( ( !empty( $aData['sCompanyName'] ) ) ? ( ' ' ) : ( $aData['sFirstName'] . ' ' . $aData['sLastName'] ) ) . "\r\n" );
	$aStreet = throwStreetDetails( $aData['sStreet'] );
	$sFlysoft.= ( $aStreet['sStreetName'] . "\r\n" );
	$sFlysoft.= ( $aStreet['sStreetNumber1'] . '/' . $aStreet['sStreetNumber2'] . "\r\n" );
	$sFlysoft.= ( $aData['sZipCode'] . "\r\n" );
	$sFlysoft.= ( $aData['sCity'] . "\r\n" );
	$sFlysoft.= ( $aData['sNip'] . "\r\n" );
	$sFlysoft.= ( $aData['sPhone'] . "\r\n" );
	$sFlysoft.= ( $aData['sEmail'] . "\r\n" );
	$sFlysoft.= ( $oOrder->throwInvoice( $aData['iInvoice'] ) . "\r\n" );
	$sFlysoft.= ( $aData['sPaymentName'] . "\r\n" );
	$sFlysoft.= ( ( $aData['fPaymentCarrierPrice'] + ( $aData['iGift'] ? $config['gift_cost'] : 0 ) ) . "\r\n" );
	$sFlysoft.= ( $aData['iCarrier'] . '-' . $aData['iPayment'] . "\r\n" );
	$sFlysoft.= ( "\r\n" );
	$sFlysoft.= ( 'TAK' . "\r\n" );
	$sFlysoft.= ( "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" );
	$aProducts = $oOrder->throwProducts( $iOrder );
	foreach( $aProducts['aProducts'] as $aProduct ){
		$sFlysoft.= ( $aProduct['sOuterId'] . ';' . $aProduct['sEan'] . ';' . $aProduct['iQuantity'] . ';' . $aProduct['fPrice'] . ';' . $aProduct['sName'] . ";\r\n" );
	}
	header( 'Content-Type: text/csv' );
	header( 'Content-Disposition: attachment; filename="order' . $iOrder . '.csv"' );
	echo ( iconv( "UTF-8", "CP1250//IGNORE//TRANSLIT", $sFlysoft ) );
	exit;
} elseif( $a == 'form' && isset( $iOrder ) && is_numeric( $iOrder ) ){
	$aOrder = $oOrder->throwOrder( $iOrder );
	$const_PAID_ON_DELIVERY = PAID_ON_DELIVERY;
	if( isset( $aOrder ) && is_array( $aOrder ) ){
		if( isset( $_POST['sOption'] ) ){
			$sOption = 'save';
			if( $aOrder['sOrderAdvance'] != $_POST['sOrderAdvance'] ){ // if orders advance is set
				$bCorrectAdvance = preg_match( '/^[0-9]+(\.[0-9]{0,2})?%?$/', $_POST['sOrderAdvance'] );
				if( $bCorrectAdvance == 1 ){
					$bPercentAdvance = preg_match( '/%$/', $_POST['sOrderAdvance'] );
					$sOrderAdvance = str_replace( '%', '', $_POST['sOrderAdvance'] ); // remove percent sign
					if( $bPercentAdvance ) $_POST['fOrderAdvance'] = number_format( round( $_POST['fOrderSummary'] * $sOrderAdvance / 100, 2 ), 2 ); // count advance of order
					else $_POST['fOrderAdvance'] = number_format( round( $_POST['fOrderSummary'], 2 ), 2 );
					if( floatval( $_POST['fOrderAdvance'] ) < $_POST['fOrderSummary'] ){ // if sOrderAdvance is percent
						$_POST['iOrderAdvance'] = 1; // 0 - brak zaliczki, 1 - oczekuje na opłacenie zaliczki, 2 - zaliczka zapłacona
						$_POST['iStatus'] = 23;

						require_once( $GLOBALS['config']['dir_libraries'] . 'emogrifier.php' );
						$aUrl = parse_url( 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
						$aUrl['path'] = preg_replace( '|/[^/]*$|', '/', $aUrl['path'] );
						$oTpl->assign( 'aUrl', $aUrl );
						
						$PK = file_get_contents( 'index.php' );
						$PK = preg_match( '/.*define\\(\\s*\'PK\'\\s*,\\s*\'([0-9A-Za-z_]+)\'\\s*\\);.*/s', $PK, $aMatches );
						$PK = $aMatches[1];
						
						$aData = $aOrder;
						$aData['sStatusInfo'] = $GLOBALS['config']['order_status_desc_23'];
						$aData['sOrderKey'] = md5( $PK . $iOrder );
						$aData['fOrderAdvance'] = $_POST['fOrderAdvance'];
						$aData['sOrderSummaryPageLink'] = $GLOBALS['oPage']->getLinkName( $GLOBALS['config']['order_advance_page'] ) . '?';
						$oTpl->assign( 'aOrder', $aData );
						
						$sMailContent = $oTpl->parse( 'orders_advance_email.tpl' );
						$sHtml = $oTpl->parse( 'orders_advance_email_html.tpl' );
						$sCss = file_get_contents( $GLOBALS['config']['dir_templates'] . 'style_orders_email.css' );
						$oEm = new Emogrifier( $sHtml, $sCss );
						$sHtmlContent = $oEm->emogrify( );
						
						if( sendEmail( Array( 'sTopic' => $lang['Advance_order'] . ' ' . $lang['To_Order'] . ' ' . $aOrder['iOrder'], 'sMailContent' => $sMailContent, 'sHtmlContent' => $sHtmlContent, 'sSender' => $config['orders_email'] ), $_POST['sEmail'] ) ){
							$sOption = 'advance_email';
						}else{
							$sOption = 'advance_email_error';
						}
					}else{
						$sOption = 'advance_incorrect';
					}
				}else{
					$_POST['iOrderAdvancePayment'] = 0;
					$_POST['fOrderAdvance'] = 0;
					$_POST['sOrderAdvance'] = null;
					$_POST['iOrderAdvance'] = 0;
				}
			}
			
			if( !empty( $_POST['sSendEmailTitle'] ) && !empty( $_POST['sSendEmailContent'] ) ){
				$aAttachments = Array();
				if( !empty( $_FILES['aAttachments'] ) ){
					$aAttachmentsSRC = array_transpose( $_FILES['aAttachments'] );
					foreach( $aAttachmentsSRC as $aFile ){
						if( empty( $aFile['error'] ) ){
							$aAttachments[] = Array( 'sName' => $aFile['name'], 'sMime' => $aFile['type'], 'sContent' => file_get_contents( $aFile['tmp_name'] ) );
						}
					}
				}
				if( sendEmail( Array( 'sTopic' => $_POST['sSendEmailTitle'], 'sMailContent' => $_POST['sSendEmailContent'], 'sSender' => $config['orders_email'] ), $_POST['sEmail'], $aAttachments ) ){
					$iOrderEmail = $oDB->save( DB_ORDERS_EMAILS, Array( 'iOrder' => $iOrder, 'iTime' => time(), 'sTitle' => $_POST['sSendEmailTitle'], 'sText' => $_POST['sSendEmailContent'] ) );
					if( isset( $aAttachmentsSRC ) && !empty( $aAttachmentsSRC ) ){
						foreach( $aAttachmentsSRC as $aFile ){
							if( empty( $aFile['error'] ) ){
								$iElement = $oDB->save( DB_ORDERS_EMAILS_ATTACHMENTS, Array( 'iOrderEmail' => $iOrderEmail, 'sFileName' => $aFile['name'], 'sMimeType' => $aFile['type'] ) );
								file_put_contents( 'upload/orders_emails/' . $iElement . '_' . $aFile['name'], file_get_contents( $aFile['tmp_name'] ) );
							}
						}
					}
					$sOption = 'save_email';
				} else{
					$sOption = 'save_email_error';
				}
			}
			if( !isset( $_POST['iGift'] ) ) $_POST['iGift'] = 0;
			if( !isset( $_POST['iShowClient'] ) ) $_POST['iShowClient'] = 0;
			$_POST['sPackageNumber'] = $_POST['iPackageNumber1'] . ':' . $_POST['sPackageNumber2'];
			$oOrder->saveOrder( $_POST );
			header( 'Location: ' . $_SERVER['PHP_SELF'] . '?p=' . $p . '&sOption=' . $sOption . '&iOrder=' . $iOrder . '&activeTabId=' . $_POST['activeTabId'] );
			exit;
		}
		if( isset( $aOrder['sComment'] ) ){
			$aOrder['sCommentAdmin'] = changeTxt( $aOrder['sCommentAdmin'], 'nlNds' );
			$aOrder['sComment'] = changeTxt( $aOrder['sComment'], 'nlNds' );
		}
		if( isset( $sOption ) ){
			$content.= $oTpl->parse( 'message_done.tpl' );
			if( $sOption == 'save_email' ){
				$content.= $oTpl->parse( 'message_done_email.tpl' );
			} elseif( $sOption == 'save_email_error' ){
				$content.= $oTpl->parse( 'message_error_email.tpl' );
			} elseif( $sOption == 'advance_email' ){
				$content.= $oTpl->parse( 'message_advance_email.tpl' );
			} elseif( $sOption == 'advance_email_error' ){
				$content.= $oTpl->parse( 'message_advance_email_error.tpl' );
			} elseif( $sOption == 'advance_incorrect' ){
				$content.= $oTpl->parse( 'message_advance_incorrect.tpl' );
			}
		}
		$aOrder['aPackageNumber'] = explode( ':', $aOrder['sPackageNumber'], 2 );
		$aGeneralInfo['aCountries'] = $oOrder->throwCountriesArray( );
		$aGeneralInfo['aPackageCarriers'] = $aCarriersNames;
		$aGeneralInfo['aStatuses'] = $oOrder->throwStatus( );
		$aGeneralInfo['aInvoices'] = $oOrder->throwInvoice( );
		$aOrder['aStatusHistory'] = $oOrder->throwOrderStatuses( $iOrder );
		$aOrder['aPayment'] = $oOrder->throwPayment( $aOrder['iPayment'] );
		$aOrder['aCarrier'] = $oOrder->throwCarrier( $aOrder['iCarrier'] );
		$aOrder['aEmails'] = $oDB->executeSQL( 'SELECT `iOrderEmail`, `sTitle`, `sText`, `iTime` FROM `' . $oDB->throwTableName( DB_ORDERS_EMAILS ) . '` WHERE `iOrder` = ' . intval( $iOrder ) . ' ORDER BY `iTime` DESC', true );
		foreach( $aOrder['aEmails'] as &$aEmail ){
			$aEmail['aAttachments'] = $oDB->executeSQL( 'SELECT `iElement`, `sFileName` FROM `' . $oDB->throwTableName( DB_ORDERS_EMAILS_ATTACHMENTS ) . '` WHERE `iOrderEmail` = ' . intval( $aEmail['iOrderEmail'] ) . ' ORDER BY `iElement`', true );
		}
		require 'configure/lang_' . $aOrder['sLanguage'] . '.php';
		$aOrder['aProducts'] = $oOrder->throwProducts( $iOrder, false );
		$aGeneralInfo['currency_symbol'] = $config['currency_symbol'];
		$aOrder['aProducts']['sOrderSummary'] = displayPrice( $aOrder['aProducts']['fOrderSummary'] );
		require DB_CONFIG_LANG;
		$aRegions = $oDB->executeSQL( 'SELECT `iRegion`, `iCountry`, `sRegion` FROM `' . $oDB->throwTableName( DB_REGIONS ) . '` ORDER BY `iCountry`, `iRegion`', true );
		
		$aAdvanceOrderPayments = $oOrder->throwActivePaymentsAdmin();
		
		$oTpl->assign( 'sRegions', json_encode( $aRegions ) );
		$oTpl->assign( 'aOrder', $aOrder );
		$oTpl->assign( 'aAdvanceOrderPayments', $aAdvanceOrderPayments );
		$oTpl->assign( 'const_PAID_ON_DELIVERY', $const_PAID_ON_DELIVERY );
		$oTpl->assign( 'aGeneralInfo', $aGeneralInfo );
		$content.= $oTpl->parse( 'orders_form.tpl' );
	} else{
		$content.= $oTpl->parse( 'message_empty.tpl' );
	}
} elseif( $a == 'delete' && isset( $iOrder ) && is_numeric( $iOrder ) ){
	$oOrder->deleteOrder( $iOrder );
	header( 'Location: ' . $_SERVER['PHP_SELF'] . '?p=' . $aActions['f'] . '-list&sOption=del' );
	exit;
} elseif( $a == 'enadawca_clear' ){
	require_once DIR_LIBRARIES . 'ENadawca/ElektronicznyNadawca.php';
	$E = new ElektronicznyNadawca( $config['enadawca_test'] ? 'libraries/ENadawca/en-test.wsdl' : 'libraries/ENadawca/en.wsdl' /*'https://en-testwebapi.poczta-polska.pl/websrv/en.wsdl'*/ );
	$CE = new ClearEnvelope();
	$E->clearEnvelope( $CE );
	$content.= $oTpl->parse( 'message_done.tpl' );
} elseif( $a == 'enadawca_protocol' ){
	require_once DIR_LIBRARIES . 'ENadawca/ElektronicznyNadawca.php';
	$sApiURL = $config['enadawca_test'] ? 'libraries/ENadawca/en-test.wsdl' : 'libraries/ENadawca/en.wsdl';
	$E = new ElektronicznyNadawca($sApiURL);
	$GUD = new GetUrzedyNadania();
	$resp = $E->getUrzedyNadania( $GUD );
	$UN = $resp->urzedyNadania;
	foreach( $UN as $un ){
		if( $un->urzadNadania == $config['enadawca_urzad'] ){
			$unf = $un;
			break;
		}
	}
	if( empty( $unf ) ){
		$oTpl->assign( 'sErrorMessage', 'Nie można znaleźć wybranego urzędu nadania. Wybierz inny udząd nadania.' );
		$content.= $oTpl->parse( 'message_other_error.tpl' );
	} else{
		$SE = new sendEnvelope();
		$SE->urzadNadania = $unf;
		$E->sendEnvelope( $SE );
		$content.= $oTpl->parse( 'message_done.tpl' );
	}
} elseif( $a == 'enadawca_add' && isset( $iOrder ) ){
	require_once DIR_LIBRARIES . 'ENadawca/ElektronicznyNadawca.php';
	$aOrder = array_merge( $oOrder->throwOrder( $iOrder ), $oOrder->throwProducts( $iOrder ) );
	if( !empty( $aOrder ) ){
		$sApiURL = $config['enadawca_test'] ? 'libraries/ENadawca/en-test.wsdl' : 'libraries/ENadawca/en.wsdl';
		$E = new ElektronicznyNadawca($sApiURL);
		if( empty( $aOrder['mCarrierInfo'] ) ){
			if( !empty( $_POST ) ){
				$aOrder['aPayment'] = $oOrder->throwPayment( $aOrder['iPayment'] );
				$aOrder['aCarrier'] = $oOrder->throwCarrier( $aOrder['iCarrier'] );
				if( $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_PP || $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_PE ){
					if( $aOrder['aPayment']['iOuterSystem'] == PAID_ON_DELIVERY ){
						$P = new przesylkaPobraniowaType();
					} else{
						$P = new paczkaPocztowaType();
					}
				} elseif( $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_LP || $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_LE ){
					$P = new przesylkaPoleconaKrajowaType(); //Nie ma listu za pobraniem!
				} elseif( $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_B ){
					$P = new przesylkaBiznesowaType();
				}

				if( $aOrder['aPayment']['iOuterSystem'] == PAID_ON_DELIVERY ){
					$Pobranie = new pobranieType();
					$Pobranie->sposobPobrania = sposobPobraniaType::RACHUNEK_BANKOWY;
					$Pobranie->kwotaPobrania = round( $aOrder['fOrderSummary'] * 100 );
					$Pobranie->nrb = preg_replace( '/[^0-9]/', '', $config['enadawca_pobranie_nrb'] );
					$Pobranie->tytulem = 'Pobranie zamowienie ' . $aOrder['iOrder'];
					$P->pobranie = $Pobranie;
				}

				$A = new adresType();

				$G = new getGuid();
				$G->ilosc = 10;
				$guid = $E->getGuid( $G );
				$guid = $guid->guid[ rand( 0, 9 ) ];
				
				$tmp = new addShipment();
				$A->nazwa = isset( $aOrder['sPostalName'] ) ? $aOrder['sPostalName'] : ( $aOrder['sFirstName'] );
				$A->nazwa2 = isset( $aOrder['sPostalName'] ) ? null : ( $aOrder['sLastName'] );
				$A->ulica = isset( $aOrder['sPostalStreet'] ) ? $aOrder['sPostalStreet'] : ( $aOrder['sStreet'] );
				$A->numerDomu = "";
				$A->numerLokalu = "";
				$A->miejscowosc = isset( $aOrder['sPostalCity'] ) ? $aOrder['sPostalCity'] : ( $aOrder['sCity'] );
				$A->kodPocztowy = str_replace( '-', '', isset( $aOrder['sPostalZipCode'] ) ? $aOrder['sPostalZipCode'] : ( $aOrder['sZipCode'] ) );
				$A->telefon = str_replace( Array( '-', ' ' ), '', isset( $aOrder['sPostalPhone'] ) ? $aOrder['sPostalPhone'] : ( $aOrder['sPhone'] ) );

				$P->adres = $A;
				$P->iloscPotwierdzenOdbioru = 0;
				if( $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_PP || $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_LP ){
					$P->kategoria = kategoriaType::PRIORYTETOWA;
				} elseif( $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_PE || $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_LE ){
					$P->kategoria = kategoriaType::EKONOMICZNA;
				}
				$P->gabaryt = $_POST['sGabaryt'];
				$P->masa = $_POST['iWeight'];
				$P->guid = $guid; // wygenerowany guid
				if( $_POST['iOstroznie'] ){
					$P->ostroznie = true;
				}
				if( $_POST['iPosteRestante'] ){
					$P->posteRestante = true;
				}

				$tmp->przesylki[] = $P;
				$resp = $E->addShipment($tmp); // wysłanie zapytania
				
				if( isset( $resp->retval->error ) ){
					var_dump( 'resp. retval. error: ', $resp->retval->error );
					exit;
				}

				$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_ORDERS ) . '` SET `mCarrierInfo` = \'' . $oDB->escape( $guid ) . '\' WHERE `iOrder` = ' . intval( $iOrder ) );
			} else{
				$aOrder['aCarrier'] = $oOrder->throwCarrier( $aOrder['iCarrier'] );
				if( $aOrder['aCarrier']['iOuterCarrier'] == CARRIER_POCZTA_B ){
					$aOrder['aGabaryty'] = Array(
						gabarytBiznesowaType::XS,
						gabarytBiznesowaType::S,
						gabarytBiznesowaType::M,
						gabarytBiznesowaType::L,
						gabarytBiznesowaType::XL,
						gabarytBiznesowaType::XXL,
					);
				} else{
					$aOrder['aGabaryty'] = Array(
						gabarytType::GABARYT_A,
						gabarytType::GABARYT_B,
					);
				}
				$aOrder['iWeight'] = $oDB->executeSQL( 'SELECT SUM( IFNULL( `pv`.`sWeight`, `p`.`sWeight` ) * `op`.`iQuantity` ) FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` `pv` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS ) . '` `p` USING( `iProduct` ) WHERE `op`.`iOrder` = ' . intval( $iOrder ), true, DataBase::SINGLE_VALUE ) * 1000;// masa w gramach
				if( $aOrder['aCarrier']['iOuterCarrier'] != CARRIER_POCZTA_LE && $aOrder['aCarrier']['iOuterCarrier'] != CARRIER_POCZTA_LP ){
					$aOrder['iOstroznie'] = true;
				} else{
					$aOrder['iOstroznie'] = true;
				}
				if( $aOrder['aCarrier']['iOuterCarrier'] != CARRIER_POCZTA_B ){
					$aOrder['iPosteRestante'] = true;
				} else{
					$aOrder['iPosteRestante'] = false;
				}
				$oTpl->assign( 'aOrder', $aOrder );
				echo( $oTpl->parse( 'enadawca_form.tpl' ) );
				exit;
			}
		} else{
			$guid = $aOrder['mCarrierInfo'];
		}

		$guidGet = new getAddresLabelByGuid();
		$guidGet->guid = $guid;
		$label = $E->getAddresLabelByGuid( $guidGet );

		if( isset( $label->error ) ){
			var_dump( 'label error: ', $label->error );
			exit;
		}

		$sql = 'UPDATE `' . $oDB->throwTableName( DB_ORDERS ) . '` SET `sPackageNumber` = \'' . POCZTAPOLSKA_COURIER_ID . ':' . $label->content->nrNadania . '\' WHERE `iOrder` = ' . $iOrder;
		$oDB->executeSQL( $sql );
		$oOrder->changeStatus( $iOrder, 14 );
		header( 'Content-type: application/pdf' );
		header( 'Content-disposition: inline ; filename=e_nadawca_' . $label->content->nrNadania . '.pdf' );
		file_put_contents( DIR_FILES . 'enadawca/e_nadawca_' . $label->content->nrNadania . '.pdf', $label->content->pdfContent );
		echo( $label->content->pdfContent );
		exit;
	}
} elseif( $a == 'dhl' && isset( $iOrder ) && isset( $_GET['packType'] ) ){
	$aOrder = array_merge( $oOrder->throwOrder( $iOrder ), $oOrder->throwProducts( $iOrder ) );
	if( !empty( $aOrder ) ){
		require_once DIR_LIBRARIES . 'dhl-api/Dhl.php';

		$dhlC = new DhlApiServiceCreate($wsdl);
		$dhlG = new DhlApiServiceGet($wsdl);
		$auth = new DhlApiStructAuthData();
		$auth->setUsername( $config['DHL_Login'] );
		$auth->setPassword( $config['DHL_Password'] );
		
		$shipment = new DhlApiStructShipmentFullData();
		$shipper = new DhlApiStructAddressData();
		$shipper->name = $config['invoices_company_name'];
		$shipper->postalCode = str_replace( '-', '', $config['invoices_postal_code'] );
		$shipper->city = $config['invoices_city'];
		$shipper->street = $config['invoices_address'];
		$shipper->houseNumber = '1';
		$shipper->contactPhone = $config['invoices_phone'];
		$shipper->contactEmail = $config['invoices_email'];
		$shipment->shipper = $shipper;
		$receiver = new DhlApiStructReceiverAddressData();
		$receiver->country = 'PL';
		$receiver->name = !empty( $aOrder['sPostalName'] ) ? $aOrder['sPostalName'] : ( $aOrder['sCompanyName'] . ' ' . $aOrder['sFirstName'] . ' ' . $aOrder['sLastName'] );
		$receiver->postalCode = str_replace( '-', '', !empty( $aOrder['sPostalZipCode'] ) ? $aOrder['sPostalZipCode'] : $aOrder['sZipCode'] );
		$receiver->city = !empty( $aOrder['sPostalCity'] ) ? $aOrder['sPostalCity'] : ( $aOrder['sCity'] );
		$receiver->street = !empty( $aOrder['sPostalStreet'] ) ? $aOrder['sPostalStreet'] : $aOrder['sStreet'];
		$receiver->houseNumber = '1';
		$receiver->contactPerson = !empty( $aOrder['sPostalName'] ) ? $aOrder['sPostalName'] : ( $aOrder['sFirstName'] . ' ' . $aOrder['sLastName'] );
		$receiver->contactPhone = !empty( $aOrder['sPostalPhone'] ) ? $aOrder['sPostalPhone'] : $aOrder['sPhone'];
		$receiver->contactEmail = $aOrder['sEmail'];
		$shipment->receiver = $receiver;
		$piece = new DhlApiStructPieceDefinition();
		$piece->type = $_GET['packType'];
		if( $_GET['packType'] != 'ENVELOPE' ){
			$piece->width = $_GET['width'];
			$piece->height = $_GET['height'];
			$piece->length = $_GET['length'];
			$piece->weight = intval( ceil( $_GET['weight'] ) );
		}
		$piece->quantity = $_GET['iPackageCount'];
		$piece->nonStandard = boolval( $_GET['nonStandard'] );
		if( $_GET['packType'] == 'PALLET' ){
			$piece->euroReturn = boolval( $_GET['euroReturn'] );
		}
		$shipment->pieceList = array_fill( 0, $_GET['iPackageCount'], $piece );
		$payment = new DhlApiStructPaymentData();
		$payment->paymentMethod = 'BANK_TRANSFER';
		$payment->payerType = 'SHIPPER';
		$payment->accountNumber = $config['DHL_SAP'];
		$shipment->payment = $payment;
		$service = new DhlApiStructServiceDefinition();
		$service->product = "AH";
		$service->deliveryEvening = boolval( $_GET['deliveryEvening'] );
		$service->deliverySaturday = boolval( $_GET['deliverySaturday'] );
		if( $aOrder['iPaymentSystem'] == PAID_ON_DELIVERY ){
			$service->collectOnDelivery = true;
			if( $aOrder['iOrderAdvance'] == 2 ) $aOrder['fOrderSummary'] - $aOrder['fOrderAdvance'];
			$service->collectOnDeliveryValue = $aOrder['fOrderSummary'];
			$service->collectOnDeliveryForm = 'BANK_TRANSFER';
			$service->collectOnDeliveryReference = 'Zam. ' . $aOrder['iOrder'];
		} else{
			$service->collectOnDelivery = false;
		}
		if( $_GET['insurance'] > 0 ){
			$service->insurance = true;
			$service->insuranceValue = $_GET['insurance'];
		}
		$shipment->service = $service;
		
		$bDr = $piece->type != 'ENVELOPE' && $piece->weight >= 32;
		
		$date = time();
		do{
			if( $dhlG->getPostalCodeServices( new DhlApiStructGetPostalCodeServices( $auth, str_replace( '-', '', $config['invoices_postal_code'] ), date( 'Y-m-d', $date ) ) ) ){
				$info = $dhlG->getResult();
				$info = $bDr ? $info->getPostalCodeServicesResult->drPickupTo : $info->getPostalCodeServicesResult->exPickupTo;
				if( $info == 'brak' ){
				} elseif( date( 'Y-m-d ', $date) . $info < date( 'Y-m-d H:i' ) ){
					break;
				} else{
				}
			} else{
				file_put_contents( 'logs/dhl_errors.log', date( 'Y-m-d H:i:s' ) . "\n" . var_export( $dhlG->getLastError(), true ) . "\n\n", FILE_APPEND );
				break;
			}
			$date += 24 * 3600;
		} while( true );
		
		$shipment->shipmentDate = date( 'Y-m-d', $date );
		$shipment->content = 'Zamówienie ze sklepu';
		
		if( $dhlC->createShipments( new DhlApiStructCreateShipments( $auth, $shipment) ) ){
			$result = $dhlC->getResult();

			$sql = 'UPDATE `' . $oDB->throwTableName( DB_ORDERS ) . '` SET `sPackageNumber` = \'' . DHL_API_COURIER_ID . ':' . $result->createShipmentsResult->item[0]->shipmentId . '\', `mCarrierInfo` = \''.$oDB->escape($sSource).'\' WHERE `iOrder` = ' . $iOrder;
			$oDB->executeSQL( $sql );
			$oOrder->changeStatus( $iOrder, 14 );

			$labelreq = new DhlApiStructItemToPrint( 'BLP', $result->createShipmentsResult->item[0]->shipmentId );
			
			if( $dhlG->getLabels( new DhlApiStructGetLabels( $auth, Array( $labelreq ) ) ) ){
				$result = $dhlG->getResult();
				$label = $result->getLabelsResult->item[0];
				file_put_contents( DIR_FILES . 'dhl/' . $label->labelName, base64_decode( $label->labelData ) );
				header( 'Content-type: application/pdf' );
				header( 'Content-disposition: inline ; filename=' . $label->labelName );
				readfile( DIR_FILES . 'dhl/' . $label->labelName );
				exit;
			} else{
				file_put_contents( 'logs/dhl_errors.log', date( 'Y-m-d H:i:s' ) . "\n" . var_export( $dhlG->getLastError(), true ) . "\n\n", FILE_APPEND );
			}
		} else{
			file_put_contents( 'logs/dhl_errors.log', date( 'Y-m-d H:i:s' ) . "\n" . var_export( $dhlG->getLastError(), true ) . "\n\n", FILE_APPEND );
		}
	}
} elseif( $a == 'dhl' && isset( $iOrder ) ){
	$aOrder = array_merge( $oOrder->throwOrder( $iOrder ), $oOrder->throwProducts( $iOrder ) );
	if( $aOrder['iOrderAdvance'] == 2 ) $aOrder['fOrderSummary'] - $aOrder['fOrderAdvance'];
	echo( '
		<form action="admin.php" method="get" id="dhl_form">
			<input type="hidden" name="p" value="orders-dhl" />
			<input type="hidden" name="iOrder" value="' . intval( $iOrder ) . '" />
			<label>' . $lang['dhl_packType'] . ' <select name="packType" id="packType">
				<option value="ENVELOPE">' . $lang['dhl_packType_ENVELOPE'] . '</option>
				<option value="PACKAGE">' . $lang['dhl_packType_PACKAGE'] . '</option>
				<option value="PALLET">' . $lang['dhl_packType_PALLET'] . '</option>
			</select></label>
			<label class="hide packType-PACKAGE packType-PALLET">' . $lang['dhl_width'] . ' <input type="text" name="width" /></label>
			<label class="hide packType-PACKAGE packType-PALLET">' . $lang['dhl_height'] . ' <input type="text" name="height" /></label>
			<label class="hide packType-PACKAGE packType-PALLET">' . $lang['dhl_length'] . ' <input type="text" name="length" /></label>
			<label class="hide packType-PACKAGE packType-PALLET">' . $lang['dhl_weight'] . ' <input type="text" name="weight" /></label>
			<label class="hide packType-PALLET"><input type="checkbox" name="euroReturn" value="1"/> ' . $lang['dhl_euroReturn'] . '</label>
			<label><input type="checkbox" name="nonStandard" value="1"/> ' . $lang['dhl_nonStandard'] . '</label>
			<label><input type="checkbox" name="deliveryEvening" value="1"/> ' . $lang['dhl_deliveryEvening'] . '</label>
			<label><input type="checkbox" name="deliverySaturday" value="1"/> ' . $lang['dhl_deliverySaturday'] . '</label>
			<label>' . $lang['dhl_insurance'] . ' <input name="insurance" type="text" value="' . $aOrder['fOrderSummary'] . '" /></label>
			<input type="hidden" name="iPackageCount" value="'.$iPackageCount.'" /><input type="hidden" name="sSource" value="'.$sSource.'" />
			<input class="submit" type="submit" value="' . $lang['dhl_show_package'] . '" /></form>' );
	exit;
} elseif( $a == 'dhl_list' && isset( $iOrder ) ){
	$aOrder = $oOrder->throwOrder( $iOrder );
	$aPackageNumber = explode( ':', $aOrder['sPackageNumber'] );
	if( $aPackageNumber[0] == DHL_API_COURIER_ID ){
		header( 'Content-type: application/pdf' );
		header( 'Content-disposition: inline ; filename=' . $aPackageNumber[1] . '.pdf' );
		readfile( DIR_FILES . 'dhl/' . $aPackageNumber[1] . '.pdf' );
	}
} elseif( $a == 'dhl_protocol' ){
	require_once DIR_LIBRARIES . 'dhl-api/Dhl.php';

	$dhlG = new DhlApiServiceGet($wsdl);
	$auth = new DhlApiStructAuthData();
	$auth->setUsername( $config['DHL_Login'] );
	$auth->setPassword( $config['DHL_Password'] );
	
	$pnpReq = new DhlApiStructPnpRequest();
	$pnpReq->authData = $auth;
	$pnpReq->date = date( 'Y-m-d', time() + 24 * 3600 );
	$pnpReq->type = 'ALL';
	if( $dhlG->getPnp( new DhlApiStructGetPnp( $pnpReq ) ) ){
		$result = $dhlG->getResult();
		$raport = $result->getPnpResult;
		file_put_contents( DIR_FILES . 'dhl/' . $raport->fileName, base64_decode( $raport->fileData ) );
		header( 'Content-type: application/pdf' );
		header( 'Content-disposition: inline ; filename=' . $raport->fileName );
		readfile( DIR_FILES . 'dhl/' . $raport->fileName );
		exit;
	} else{
		file_put_contents( 'logs/dhl_errors.log', date( 'Y-m-d H:i:s' ) . "\n" . var_export( $dhlG->getLastError(), true ) . "\n\n", FILE_APPEND );
	}
} elseif( $a == 'dhl_protocol_list' ){
	$aProtocols = glob( DIR_FILES . 'dhl/*.pdf' );
	if( !empty( $aProtocols ) ){
		$content .= '<ul class="protocols_list" id="dhl_protocols">';
		foreach( $aProtocols as $sProtocol ){
			$content .= '<li><a target="_blank" href="' . $sProtocol . '">'.basename( $sProtocol ).'</a></li>';
		}
		$content .= '</ul>';
	}
}	elseif( $a == 'dpd' && isset( $iOrder ) ){
	$aOrder = array_merge( $oOrder->throwOrder( $iOrder ), $oOrder->throwProducts( $iOrder ) );
	if( !empty( $aOrder ) ){
		require_once DIR_LIBRARIES . 'dpd-api/Dpd.php';
		Dpd::registerAutoload( );
		$packageDetails["reference_number"] = strtoupper( 'SS' . VERSION . '_' . PK . '_' . $iOrder );
		try{
			$dpd = new DpdApi( );
			$dpd->setLang( "pl_PL" );
			//webservice host (xml) - ask Your DPD consultant
			$dpd->setHost( $config['DPD_Host'] );
			$dpd->setFolder( DIR_FILES . 'dpd' );
			$dpd->setLogin( $config['DPD_Login'] );
			$dpd->setPassword( $config['DPD_Password'] );
			$dpd->setMasterfid( intval( $config['DPD_Masterfid'] ) );
			$dpd->setDepartment( 1 );
			$dpd->setConnection( );
		}
		catch( Exception$e ){
			$oTpl->assign( 'sErrorMessage', $e->getMessage( ) );
			$content.= $oTpl->parse( 'message_other_error.tpl' );
		}
		$waybill = substr( $aOrder['sPackageNumber'], 2 );
		if( !isset( $aOrder['sPackageNumber'] ) || $aOrder['sPackageNumber'][0] != DPD_API_COURIER_ID || strlen( $aOrder['sPackageNumber'] ) <= 2 ){
			//Generuj paczkę
			$shipFromDpd["Company"] = $config['invoices_company_name'];
			$shipFromDpd["Name"] = $config['invoices_company_name'];
			$shipFromDpd["Street"] = $config['invoices_address'];
			$shipFromDpd["City"] = $config['invoices_city'];
			$shipFromDpd["PostalCode"] = str_replace( '-', '', $config['invoices_postal_code'] );
			$shipFromDpd["CountryCode"] = "PL";
			$shipFromDpd["Phone"] = $config['invoices_phone'];
			$shipFromDpd["Email"] = $config['invoices_email'];
			$shipToDpd["Company"] = $aOrder['sCompanyName'];
			$shipToDpd["Name"] = isset( $aOrder['sPostalName'] ) ? $aOrder['sPostalName'] : ( $aOrder['sFirstName'] );
			$shipToDpd["Surname"] = isset( $aOrder['sPostalName'] ) ? null : ( $aOrder['sLastName'] );
			$shipToDpd["Street"] = isset( $aOrder['sPostalStreet'] ) ? $aOrder['sPostalStreet'] : ( $aOrder['sStreet'] );
			$shipToDpd["City"] = isset( $aOrder['sPostalCity'] ) ? $aOrder['sPostalCity'] : ( $aOrder['sCity'] );
			$shipToDpd["CountryCode"] = $oDB->executeSQL( 'SELECT UPPER( `sCountry2` ) FROM `' . $oDB->throwTableName( DB_COUNTRIES ) . '` WHERE `iCountry` = ' . intval( !empty( $aOrder['iPostalCountry'] ) ? $aOrder['iPostalCountry'] : $aOrder['iCountry'] ), true, DataBase::SINGLE_VALUE );
			$shipToDpd["PostalCode"] = isset( $aOrder['sPostalZipCode'] ) ? $aOrder['sPostalZipCode'] : ( $aOrder['sZipCode'] );
			$shipToDpd["Phone"] = isset( $aOrder['sPostalPhone'] ) ? $aOrder['sPostalPhone'] : $aOrder['sPhone'];
			$shipToDpd["Phone2"] = '';
			$shipToDpd["Email"] = $aOrder['sEmail'];
			if( empty( $iPackageCount ) || !is_numeric( $iPackageCount ) ) $iPackageCount = 1;
			$packageDetails["package_amount"] = $iPackageCount;
			$packageDetails["customer_data_1"] = '';
			$packageDetails["package_content"] = 'Zamówienie ze sklepu internetowego';
			$packageDetails["Ref1"] = 'Zam: ' . $iOrder;
			$packageDetails["Ref2"] = '';
			$packageDetails["Ref3"] = '';
			if( $aOrder['iOrderAdvance'] == 2 ) $aOrder['fOrderSummary'] - $aOrder['fOrderAdvance'];
			$packageDetails["DeclaredValue"] = $aOrder['fOrderSummary'];
			if( $aOrder['iPaymentSystem'] == PAID_ON_DELIVERY ) $packageDetails["COD"] = $packageDetails["DeclaredValue"];
			else $packageDetails["COD"] = 0;
			$packageDetails["Weight"] = $oDB->executeSQL( 'SELECT SUM( IFNULL( `pv`.`sWeight`, `p`.`sWeight` ) * `op`.`iQuantity` ) FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` `pv` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS ) . '` `p` USING( `iProduct` ) WHERE `op`.`iOrder` = ' . intval( $iOrder ), true, DataBase::SINGLE_VALUE );
			if( $packageDetails["Weight"] == 0 ) $packageDetails["Weight"] = 1;
			try{
				$dpd->setShipFrom( $shipFromDpd );
				$dpd->setShipTo( $shipToDpd );
				$dpd->setPackageDetails( $packageDetails );
				//register package
				$paczka = $dpd->registerNewPackage( );
				if( DEBUG_SELLSMART ) file_put_contents( 'logs/dpd.log', var_export( $paczka, true ), FILE_APPEND );
				if( $paczka['type'] == 'error' ){
					die( $paczka['message'] );
				}
				//change status
				$waybills = $paczka['array']['parcels']->xpath( 'Parcel/Waybill' );
				$waybill = strip_tags( $waybills[0]->asXml( ) );
				$sql = 'UPDATE `' . $oDB->throwTableName( DB_ORDERS ) . '` SET `sPackageNumber` = \'' . DPD_API_COURIER_ID . ':' . $waybill . '\', `mCarrierInfo` = \''.$oDB->escape($sSource).'\' WHERE `iOrder` = ' . $iOrder;
				$oDB->executeSQL( $sql );
				$oOrder->changeStatus( $iOrder, 14 );
			}
			catch( Exception$e ){
				$oTpl->assign( 'sErrorMessage', $e->getMessage( ) );
				$content.= $oTpl->parse( 'message_other_error.tpl' );
			}
		}
		try{
			//get label by reference number
			$label = $dpd->getLabelPDF( 1, $packageDetails["reference_number"] );
			if( DEBUG_SELLSMART ) file_put_contents( 'logs/dpd.log', var_export( $label, true ), FILE_APPEND );
			header( 'Content-type: application/pdf' );
			header( 'Content-disposition: inline ; filename=' . $waybill . '.pdf' );
			readfile( DIR_FILES . 'dpd' . $label['filename'] );
			if( !$config['DPD_keephistory'] ) unlink( DIR_FILES . 'dpd' . $label['filename'] );
			exit;
		}
		catch( Exception$e ){
			$oTpl->assign( 'sErrorMessage', $e->getMessage( ) );
			$content.= $oTpl->parse( 'message_other_error.tpl' );
		}
	}
} elseif( $a == 'dpd_protocol' ){
	$aOrders = $oDB->executeSQL( 'SELECT `iOrder` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` WHERE `iCarrierSystem` = ' . CARRIER_DPD_API . ' AND `iStatus` = 14 AND `mCarrierInfo` = \''.$oDB->escape($sSource).'\'', true, DataBase::SINGLE_COLUMN );
	if( is_array( $aOrders ) && count( $aOrders ) > 0 ){
		$aRefNums = Array( );
		foreach( $aOrders as $iOrder ){
			$aRefNums[] = strtoupper( 'SS' . VERSION . '_' . PK . '_' . $iOrder );
		}
		require_once DIR_LIBRARIES . 'dpd-api/Dpd.php';
		Dpd::registerAutoload( );
		try{
			$dpd = new DpdApi( );
			$dpd->setLang( "pl_PL" );
			//webservice host (xml) - ask Your DPD consultant
			$dpd->setHost( $config['DPD_Host'] );
			$dpd->setFolder( DIR_FILES . 'dpd' );
			$dpd->setLogin( $config['DPD_Login'] );
			$dpd->setPassword( $config['DPD_Password'] );
			$dpd->setMasterfid( intval( $config['DPD_Masterfid'] ) );
			$dpd->setDepartment( 1 );
			$dpd->setConnection( );
		}
		catch( Exception$e ){
			$oTpl->assign( 'sErrorMessage', $e->getMessage( ) );
			$content.= $oTpl->parse( 'message_other_error.tpl' );
		}
		$protocol = $dpd->getProtocol( $aRefNums );
		if( DEBUG_SELLSMART ) file_put_contents( 'logs/dpd.log', var_export( $paczka, true ), FILE_APPEND );
		if( $protocol['type'] == 'ok' ){
			//Pokaż protokół i zmień status
			header( 'Content-type: application/pdf' );
			header( 'Content-disposition: inline ; filename=' . basename( $protocol['filename'], '.pdf' ) . '.pdf' );
			readfile( DIR_FILES . 'dpd' . $protocol['filename'] );
			if( !$config['DPD_keephistory'] ) unlink( DIR_FILES . 'dpd' . $protocol['filename'] );
			foreach( $aOrders as $iOrder ){
				$oOrder->changeStatus( $iOrder, 2 );
			}
		} else{
			$oTpl->assign( 'sErrorMessage', $protocol['message'] );
			$content.= $oTpl->parse( 'message_other_error.tpl' );
		}
	} else{
		$oTpl->assign( 'sErrorMessage', $lang['DPD_no_packages'] );
		$content.= $oTpl->parse( 'message_other_error.tpl' );
	}
} elseif( $a == 'dpd_protocol_list' ){
	$aProtocols = glob( DIR_FILES . 'dpd/protocols/*.pdf' );
	if( !empty( $aProtocols ) ){
		$content .= '<ul class="protocols_list" id="dpd_protocols">';
		foreach( $aProtocols as $sProtocol ){
			$content .= '<li><a target="_blank" href="' . $sProtocol . '">'.basename( $sProtocol ).'</a></li>';
		}
		$content .= '</ul>';
	}
}	elseif( $a == 'geis' && isset( $iOrder ) ){
	$aOrder = array_merge( $oOrder->throwOrder( $iOrder ), $oOrder->throwProducts( $iOrder ) );
	if( !empty( $aOrder ) ){
		$PackNumber = substr( $aOrder['sPackageNumber'], strlen( GEIS_API_COURIER_ID ) + 1 );
		if( !isset( $aOrder['sPackageNumber'] ) || substr( $aOrder['sPackageNumber'], 0, strlen( GEIS_API_COURIER_ID ) ) != GEIS_API_COURIER_ID || strlen( $aOrder['sPackageNumber'] ) <= strlen( GEIS_API_COURIER_ID ) + 1 ){
			require_once DIR_LIBRARIES . 'geis.php';
			try{
				if( GService::GetServiceClient( $config['GEIS_Host'] ) == null ){
					$oTpl->assign( 'sErrorMessage', "Błąd połączenia" );
					$content.= $oTpl->parse( 'message_other_error.tpl' );
					return;
				}
				$aSource = $oDB->executeSQL( 'SELECT `sName`, `iGeisClientCode` FROM `' . $oDB->throwTableName( DB_STORES ) . '` WHERE `iStore` = ' . $sSource, true, DataBase::SINGLE_RECORD );
				
				GService::SetRequestHeader( /*'45000731'*/ $aSource['iGeisClientCode'], $config['GEIS_Key'], in_array( strtoupper( $aOrder['sLanguage'] ), Array( 'CZ', 'SK', 'EN', 'DE', 'PL' ) ) ? strtoupper( $aOrder['sLanguage'] ) : 'EN' ); //Jeśli język nie występuje w GEISie, użyj angielskiego
			}
			catch( Exception $e ){
				$oTpl->assign( 'sErrorMessage', $e->getMessage( ) );
				$content.= $oTpl->parse( 'message_other_error.tpl' );
			}

			$types = GService::GetTypesFromWebService();
			$methods = GService::GetMethodsFromWebService();

			//Generuj paczkę
			$SenderAddress = new Address();
			$SenderAddress->City = $config['invoices_city'];
			$SenderAddress->Country = "PL";
			$SenderAddress->Name = $config['invoices_company_name'];
			$SenderAddress->Name2 = null;
			$SenderAddress->Street = $config['invoices_address'];
			$SenderAddress->ZipCode = str_replace( '-', '', $config['invoices_postal_code'] );

			$SenderContact = new Contact();
			$SenderContact->Email = $config['invoices_email'];
			$SenderContact->FullName = $config['invoices_company_name'];
			$SenderContact->Phone = "+48" . str_replace( Array( ' ', '-', '+' ), '', $config['invoices_phone'] );

			$name = $aOrder['sPostalName'];
			if( empty( $name ) ) $name = $aOrder['sCompanyName'];
			if( empty( $name ) ) $name = $aOrder['sFirstName'] . ' ' . $aOrder['sLastName'];

			$DeliveryAddress = new Address();
			$DeliveryAddress->City = isset( $aOrder['sPostalCity'] ) ? $aOrder['sPostalCity'] : ( $aOrder['sCity'] );
			$DeliveryAddress->Country = $oDB->executeSQL( 'SELECT UPPER( `sCountry2` ) FROM `' . $oDB->throwTableName( DB_COUNTRIES ) . '` WHERE `iCountry` = ' . intval( !empty( $aOrder['iPostalCountry'] ) ? $aOrder['iPostalCountry'] : $aOrder['iCountry'] ), true, DataBase::SINGLE_VALUE );
			$DeliveryAddress->Name = $name;
			$DeliveryAddress->Name2 = null;
			$DeliveryAddress->Street = isset( $aOrder['sPostalStreet'] ) ? $aOrder['sPostalStreet'] : ( $aOrder['sStreet'] );
			$DeliveryAddress->ZipCode = str_replace( '-', '', isset( $aOrder['sPostalZipCode'] ) ? $aOrder['sPostalZipCode'] : ( $aOrder['sZipCode'] ) );

			$DeliveryContact = new Contact ();
			$DeliveryContact->Email = $aOrder['sEmail'];
			$DeliveryContact->FullName = $name;
			$DeliveryContact->Phone = "+48" . str_replace( Array( ' ', '-', '+' ), '', isset( $aOrder['sPostalPhone'] ) ? $aOrder['sPostalPhone'] : $aOrder['sPhone'] );
			
//			$OrderRequest = new OrderRequest();
//
//			$OrderRequest->BurstId = null;
//			$OrderRequest->DeliveryAddress = $DeliveryAddress;
//			$OrderRequest->DeliveryContact = $DeliveryContact;
//			$OrderRequest->DistributionChannel = 1;
//
//			if( $aOrder['iPaymentSystem'] == PAID_ON_DELIVERY ){
//				$ExportService = new ExportService();
//				$ExportService->Code = "COD";
//				$ExportService->Parameter_1 = $aOrder['fOrderSummary'];
//				$ExportService->Parameter_2 = $config['currency_symbol_ISO'];
//				
//				$OrderRequest->ExportServices[] = $ExportService;
//			}

			$weight = $oDB->executeSQL( 'SELECT SUM( IFNULL( `pv`.`sWeight`, `p`.`sWeight` ) * `op`.`iQuantity` ) FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` `pv` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS ) . '` `p` USING( `iProduct` ) WHERE `op`.`iOrder` = ' . intval( $iOrder ), true, DataBase::SINGLE_VALUE );
			if( $weight == 0 ) $weight = 1;
			if( empty( $iPackageCount ) ) $iPackageCount = 1;

			
//			$OrderRequest->Note = $aOrder['iOrder'];
//			$OrderRequest->PickUpDate = date( 'Y-m-d\\TH:i:s' );
//			$OrderRequest->SenderAddress = $SenderAddress;
//			$OrderRequest->SenderContact = $SenderContact;
//			$OrderRequest->Weight = $weight / $iPackageCount; //main pack with set weith //glowna paczka wraz z waga 
//			if( $iPackageCount > 1 ){
//				$OrderRequest->MergedOrder = true; //additional packs
//				for( $i = 2; $i <= $iPackageCount; $i++ ){
//					$MergedItem = new MergedItem();
//					$MergedItem->Weight = $weight / $iPackageCount;
//					$OrderRequest->MergedOrders[] = $MergedItem;
//				}
//			} else{
//				$OrderRequest->MergedOrder = false; //additional packs
//			}
			
			$ExportRequest = new ExportRequest();
			$ExportRequest->BurstId = null;
			$ExportRequest->DeliveryAddress = $DeliveryAddress;
			$ExportRequest->DeliveryContact = $DeliveryContact;
			$ExportRequest->DistributionChannel = 1;
			//$ExportRequest->ExportServices[] = $ExportService;
			if( $aOrder['iPaymentSystem'] == PAID_ON_DELIVERY ){
				$ExportService1 = new ExportService();
				$ExportService1->Code = "COD";
				$ExportService1->Parameter_1 = $aOrder['fOrderSummary'];
				$ExportService1->Parameter_2 = $config['currency_symbol_ISO'];
				$ExportService1->Parameter_4 = str_replace( Array( ' ', '-', '_' ), '', $config['invoices_IBAN'] );
				
				$ExportRequest->ExportServices[] = $ExportService1;
			}
			
			$ExportService2 = new ExportService();
			$ExportService2->Code = "B2C";
			$ExportService2->Parameter_1 = $DeliveryContact->Phone;
			
			$ExportRequest->ExportServices[] = $ExportService2;
			
			$ExportRequest->Weight = $weight / $iPackageCount; //main pack with set weith //glowna paczka wraz z waga 
			if( $iPackageCount > 1 ){
				$ExportRequest->MergedShipment = true; //additional packs
				for( $i = 2; $i <= $iPackageCount; $i++ ){
					$MergedItem = new MergedItem();
					$MergedItem->Weight = $weight / $iPackageCount;
					$ExportRequest->MergedPackages[] = $MergedItem;
				}
			} else{
				$ExportRequest->MergedShipment = false;
			}
			$ExportRequest->Note = $config['website_name'] . ' ' . $aOrder['iOrder'];
			$ExportRequest->PickUpDate = date( 'Y-m-d\\TH:i:s' );

			$InsertExportResult = GService::InsertExport($ExportRequest);
			
			if( $InsertExportResult->InsertExportResult->ErrorCode != '0000' ){
				echo( 'Błąd [' . $InsertExportResult->InsertExportResult->ErrorCode . ']: ' . $InsertExportResult->InsertExportResult->ErrorMessage );
				exit;
			}
			
			
			$PackNumber = $InsertExportResult->InsertExportResult->ResponseObject->PackNumber;
			$PackNumbers = Array( $PackNumber );
			if( $iPackageCount > 1 ){
				if( !is_array( $InsertExportResult->InsertExportResult->ResponseObject->MergedPackNumbers->string ) ){
					$PackNumbers[] = $InsertExportResult->InsertExportResult->ResponseObject->MergedPackNumbers->string;
				} else{
					foreach( $InsertExportResult->InsertExportResult->ResponseObject->MergedPackNumbers->string as $PackNumber ){
						$PackNumbers[] = $PackNumber;
					}
				}
				$PackNumber = implode( ';', $PackNumbers );
			}
			
			$sql = 'UPDATE `' . $oDB->throwTableName( DB_ORDERS ) . '` SET `sPackageNumber` = \'' . GEIS_API_COURIER_ID . ':' . $PackNumber . '\', `mCarrierInfo` = \''.$oDB->escape($aSource['sName']).'\' WHERE `iOrder` = ' . $iOrder;
			$oDB->executeSQL( $sql );
			$oOrder->changeStatus( $iOrder, 14 );
			
			$LabelRequest = new LabelRequest();
			$LabelRequest->DistributionChannel = 1;
			$LabelRequest->Format = 5;
			$LabelRequest->Position = 1;
			$LabelRequest->Resolution = 0;
			foreach( $PackNumbers as $PackNumber ){
				$LabelItem = new LabelItem();
				$LabelItem->ShipmentNumber = $PackNumber;
				$LabelRequest->ShipmentNumbers[] = $LabelItem;
			}
			$GetLabelResult = GService::GetLabel($LabelRequest);
			FileHelper::SavePdfToFile( DIR_FILES . 'geis/waybills/'.implode( '_', $PackNumbers ), $GetLabelResult->GetLabelResult->ResponseObject->LabelData->LabelItemData->Data );
		} else{
			$PackNumbers = explode( ';', $PackNumber );
		}
		
		header( 'Content-type: application/pdf' );
		header( 'Content-disposition: inline ; filename=' . implode( '_', $PackNumbers ) . '.pdf' );
		readfile( DIR_FILES . 'geis/waybills/'.implode( '_', $PackNumbers ) . '.pdf' );
		exit;
	}
} elseif( $a == 'geis_protocol' ){
	$aSource = $oDB->executeSQL( 'SELECT `sName`, `iGeisClientCode` FROM `' . $oDB->throwTableName( DB_STORES ) . '` WHERE `iStore` = ' . intval( $sSource ), true, DataBase::SINGLE_RECORD );
	$aOrders = $oDB->executeSQL( 'SELECT `iOrder`, `sPackageNumber` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` WHERE `iCarrierSystem` = ' . CARRIER_GEIS_API . ' AND `iStatus` = 14 AND `mCarrierInfo` = \''.$oDB->escape($aSource['sName']).'\'', true, DataBase::ASSOCIATIVE );
	if( is_array( $aOrders ) && count( $aOrders ) > 0 ){
		require_once DIR_LIBRARIES . 'geis.php';
		try{
			if( GService::GetServiceClient( $config['GEIS_Host'] ) == null ){
				$oTpl->assign( 'sErrorMessage', "Błąd połączenia" );
				$content.= $oTpl->parse( 'message_other_error.tpl' );
				return;
			}
			$aSource = $oDB->executeSQL( 'SELECT `sName`, `iGeisClientCode` FROM `' . $oDB->throwTableName( DB_STORES ) . '` WHERE `iStore` = ' . $sSource, true, DataBase::SINGLE_RECORD );
			
			GService::SetRequestHeader( $aSource['iGeisClientCode'], $config['GEIS_Key'], in_array( strtoupper( $config['default_lang'] ), Array( 'CZ', 'SK', 'EN', 'DE', 'PL' ) ) ? strtoupper( $config['default_lang'] ) : 'EN' ); //Jeśli język nie występuje w GEISie, użyj angielskiego
		}
		catch( Exception $e ){
			$oTpl->assign( 'sErrorMessage', $e->getMessage( ) );
			$content.= $oTpl->parse( 'message_other_error.tpl' );
		}

		$types = GService::GetTypesFromWebService();
		$methods = GService::GetMethodsFromWebService();

		$ArrayOfPickupListShipmItem = new ArrayOfPickupListShipmItem();
		
		foreach( $aOrders as $sPackageNumber ){
			$PackNumbers = explode( ';', explode( ':', $sPackageNumber, 2 )[1] );
			foreach( $PackNumbers as $PackNumber ){
				$PickupListShipmItem = new PickupListShipmItem();
				$PickupListShipmItem->ShipmentNumber = $PackNumber;
				$ArrayOfPickupListShipmItem->PickupListShipmItem[] = $PickupListShipmItem;
			}
		}
		
		$PickupListRequest = new PickupListRequest();
		$PickupListRequest->DistributionChannel = 1;
		$PickupListRequest->ExpeditionCreateDate = Date( 'Y-m-d' );
		$PickupListRequest->ShipmentsNumbers = $ArrayOfPickupListShipmItem;
		
//		var_dump( $PickupListRequest );
//		exit;
		
		$GetPickupListResult = GService::GetPickupList($PickupListRequest);
		if( $GetPickupListResult->GetPickupListResult->ErrorCode != '0000' ){
			die( 'GetPickupListResult - ErrorMessage : ' . $GetPickupListResult->GetPickupListResult->ErrorMessage );
		} else{
			$protocol_filename = date( 'Y-m-d_H-i-s' );
			FileHelper::SavePdfToFile( DIR_FILES . 'geis/protocols/' . $protocol_filename, $GetPickupListResult->GetPickupListResult->ResponseObject->PickupListData );

			foreach( $aOrders as $iOrder => $sPackageNumber ){
				$oOrder->changeStatus( $iOrder, 2 );
			}

			header( 'Content-type: application/pdf' );
			header( 'Content-disposition: inline ; filename=' . $protocol_filename . '.pdf' );
			readfile( DIR_FILES . 'geis/protocols/' . $protocol_filename . '.pdf' );
			exit;
		}
	}
} elseif( $a == 'geis_protocol_list' ){
	$aProtocols = glob( DIR_FILES . 'geis/protocols/*.pdf' );
	if( !empty( $aProtocols ) ){
		$content .= '<ul class="protocols_list" id="geis_protocols">';
		foreach( $aProtocols as $sProtocol ){
			$content .= '<li><a target="_blank" href="' . $sProtocol . '">'.basename( $sProtocol ).'</a></li>';
		}
		$content .= '</ul>';
	}
} elseif( $a == 'paczkomaty' && isset( $iOrder ) && isset( $_GET['packType'] ) ){
	$aOrder = array_merge( $oOrder->throwOrder( $iOrder ), $oOrder->throwProducts( $iOrder ) );
	if( $aOrder['iOrderAdvance'] == 2 ) $aOrder['fOrderSummary'] - $aOrder['fOrderAdvance'];
	if( !empty( $aOrder ) ){
		require_once( $config['dir_libraries'] . 'paczkomaty/inpost.php' );
		$aPacksData = Array( $aOrder['iOrder'] => Array(
			'adreseeEmail' => $aOrder['sEmail'],
			'senderEmail' => $config['paczkomaty_email'],
			'phoneNum' => isset( $aOrder['sPostalPhone'] ) ? $aOrder['sPostalPhone'] : $aOrder['sPhone'],
			'boxMachineName' => substr( $aOrder['mCarrierInfo'], 0, strpos( $aOrder['mCarrierInfo'], ':' ) ),
			'packType' => $_GET['packType'],
			'insuranceAmount' => $_GET['insuranceAmount'],
			'onDeliveryAmount' =>( PAID_ON_DELIVERY == $aOrder['iPaymentSystem'] ? $aOrder['fOrderSummary'] : 0 ),
			'customerRef' => $config['website_name'] . ' - ' . $aOrder['iOrder']
		) );
		$aPacksInfo = inpost_send_packs( $config['paczkomaty_email'], $config['paczkomaty_haslo'], $aPacksData, 1, $config['paczkomaty_self_send'] );
		$aPackInfo = $aPacksInfo[ $aOrder['iOrder'] ];
		if( !empty( $aPackInfo['packcode'] ) ){
			try{
				$sql = 'UPDATE `' . $oDB->throwTableName( DB_ORDERS ) . '` SET `sPackageNumber` = \'' . PACZKOMATY_COURIER_ID . ':' . $aPackInfo['packcode'] . '\', `mCarrierInfo` = \''.$oDB->escape($sSource).'\' WHERE `iOrder` = ' . $iOrder;
				$oDB->executeSQL( $sql );
				$oOrder->changeStatus( $iOrder, 14 );
				//get label by reference number
				$label = inpost_get_sticker( $config['paczkomaty_email'], $config['paczkomaty_haslo'], $aPackInfo['packcode'] );
				if( is_array( $label ) ){
					//var_dump( $label );
					$oTpl->assign( 'sErrorMessage', $label['key'] . ': ' . $label['message'] );
					$content.= $oTpl->parse( 'message_other_error.tpl' );
				} else{
					header( 'Content-type: application/pdf' );
					header( 'Content-disposition: inline ; filename=' . $aPackInfo['packcode'] . '.pdf' );
					echo( $label );
					exit;
				}
			}
			catch( Exception$e ){
				//var_dump( $e );
				$oTpl->assign( 'sErrorMessage', $e->getMessage( ) );
				$content.= $oTpl->parse( 'message_other_error.tpl' );
			}
		} else{
			//var_dump( $aPackInfo );
			$oTpl->assign( 'sErrorMessage', $aPackInfo['error_key'] . ': ' . $aPackInfo['error_message'] );
			$content.= $oTpl->parse( 'message_other_error.tpl' );
		}
	}
} elseif( $a == 'paczkomaty' && isset( $iOrder ) ){
	$aOrder = array_merge( $oOrder->throwOrder( $iOrder ), $oOrder->throwProducts( $iOrder ) );
	if( $aOrder['iOrderAdvance'] == 2 ) $aOrder['fOrderSummary'] - $aOrder['fOrderAdvance'];
	echo( '<form action="admin.php" method="get" id="paczkomaty_form"><input type="hidden" name="p" value="orders-paczkomaty" /><input type="hidden" name="iOrder" value="' . intval( $iOrder ) . '" /><label>' . $lang['paczkomaty_packType'] . ' <select name="packType"><option value="A">A</option><option value="B">B</option><option value="C">C</option></select></label> <label>' . $lang['paczkomaty_insurance'] . ' <input name="insuranceAmount" type="text" value="' . $aOrder['fOrderSummary'] . '" /></label> <input type="hidden" name="sSource" value="' . $sSource . '" /> <input class="submit" type="submit" value="' . $lang['paczkomaty_show_package'] . '" /></form>' );
	exit;
} elseif( $a == 'paczkomaty_list' && isset( $iOrder ) ){
	$sPackage = $oDB->executeSQL( 'SELECT `sPackageNumber` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` WHERE `iOrder` = ' . intval( $iOrder ), true, DataBase::SINGLE_VALUE );
	if( preg_match( '/^([0-9]+):(.+)$/', $sPackage, $aMatches ) && $aMatches[1] == PACZKOMATY_COURIER_ID ){
		require_once( $config['dir_libraries'] . 'paczkomaty/inpost.php' );
		$label = inpost_get_sticker( $config['paczkomaty_email'], $config['paczkomaty_haslo'], $aMatches[2] );
		if( is_array( $label ) ){
			$oTpl->assign( 'sErrorMessage', $label['key'] . ': ' . $label['message'] );
			$content.= $oTpl->parse( 'message_other_error.tpl' );
		} else{
			header( 'Content-type: application/pdf' );
			header( 'Content-disposition: inline ; filename=' . $aMatches[2] . '.pdf' );
			echo( $label );
			exit;
		}		
	} else{
		$oTpl->assign( 'sErrorMessage', 'Wrong order ID: ' . $sPackage );
		$content.= $oTpl->parse( 'message_other_error.tpl' );
	}
} elseif( $a == 'paczkomaty_protocol' ){
	require_once( $config['dir_libraries'] . 'paczkomaty/inpost.php' );
	$packCodes = inpost_get_packs_by_sender( $config['paczkomaty_email'], $config['paczkomaty_haslo'], array( 'status' => 'Prepared', 'is_conf_printed' => 0 ) );
	foreach( $packCodes as &$packCode ){ $packCode = $packCode['packcode']; }
	$protocol = inpost_get_confirm_printout( $config['paczkomaty_email'], $config['paczkomaty_haslo'], $packCodes );
	if( is_array( $protocol ) ){
		$oTpl->assign( 'sErrorMessage', $protocol['error']['key'] . ': ' . $protocol['error']['message'] );
		$content.= $oTpl->parse( 'message_other_error.tpl' );
	} else{
		$filename = 'protocol_' . date( 'Ymd' ) . '_' . date( 'His' ) . '.pdf';
		header( 'Content-type: application/pdf' );
		header( 'Content-disposition: inline ; filename=' . $filename );
		file_put_contents( DIR_FILES . 'paczkomaty/' . $filename, $protocol );
		readfile( DIR_FILES . 'paczkomaty/' . $filename );
		exit;
	}		
} elseif( $a == 'paczkomaty_protocol_list' ){
	$aProtocols = glob( DIR_FILES . 'paczkomaty/*.pdf' );
	if( !empty( $aProtocols ) ){
		$content .= '<ul class="protocols_list" id="paczkomaty_protocols">';
		foreach( $aProtocols as $sProtocol ){
			$content .= '<li><a target="_blank" href="' . $sProtocol . '">'.basename( $sProtocol ).'</a></li>';
		}
		$content .= '</ul>';
	}
} elseif( $a == 'ifirma' && is_numeric( $iOrder ) ){
	list( $iFirmaProforma, $iFirmaFaktura ) = $oDB->executeSQL( 'SELECT `iFirmaProforma`, `iFirmaFaktura` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` WHERE `iOrder` = ' . intval( $iOrder ), true, DataBase::SINGLE_RECORD | MYSQLI_NUM );
	$oTpl->assign( 'iFirmaProforma', $iFirmaProforma );
	$oTpl->assign( 'iFirmaFaktura', $iFirmaFaktura );
	$oTpl->assign( 'iOrder', intval( $iOrder ) );
	echo( $oTpl->parse( 'ifirma_form.tpl' ) ); exit;
} elseif( $a == 'ifirma_proforma' && is_numeric( $iOrder ) ){
	$aOrder = $oOrder->throwOrder( $iOrder );
	if( !empty( $aOrder ) ){
		if( empty( $aOrder['iFirmaProforma'] ) ){
			$aProducts = $oOrder->throwProducts( $aOrder['iOrder'] );
			$aProducts = $aProducts['aProducts'];
			$data = Array(
				"LiczOd" => "BRT",
				"NumerKontaBankowego" => str_replace( ' ', '', $config['invoices_Account'] ),
				"TypFakturyKrajowej" => "sprz",
				"DataWystawienia" => date( 'Y-m-d' ),
				"MiejsceWystawienia" => $config['invoices_city'],
				"TerminPlatnosci" => null,
				"SposobZaplaty" => "PRZ",
				"PodpisWystawcy" => $config['invoices_signature'],
				"Uwagi" => "Zamówienie ze sklepu internetowego nr. " . $iOrder,
				"WidocznyNumerGios" => true,
				"RodzajPodpisuOdbiorcy" => "BPO",
				"NumerZamowienia" => $iOrder,
				"Pozycje" => Array(),
				"Kontrahent" => Array(
					"Nazwa" => empty( $aOrder['sCompanyName'] ) ? ( $aOrder['sFirstName'] . ' ' . $aOrder['sLastName'] ) : $aOrder['sCompanyName'],
					"Identyfikator" => null,
					"PrefiksUE" => null,
					"NIP" => $aOrder['sNip'],
					"Ulica" => $aOrder['sStreet'],
					"KodPocztowy" => $aOrder['sZipCode'],
					"Kraj" => $oDB->executeSQL( 'SELECT `sCountry` FROM `' . $oDB->throwTableName( DB_COUNTRIES ) . '` WHERE `iCountry` = ' . intval( $aOrder['iCountry'] ), true, DataBase::SINGLE_VALUE ),
					"Miejscowosc" => $aOrder['sCity'],
					"Email" => $aOrder['sEmail'],
					"Telefon" => $aOrder['sPhone'],
					"OsobaFizyczna" => empty( $aOrder['sCompanyName'] ) ? true : false
				)
			);
			foreach( $aProducts as $aProduct ){
				$data['Pozycje'][] = Array(
					"StawkaVat" => $aProduct['fVatValue'],
					"Ilosc" => $aProduct['iQuantity'],
					"CenaJednostkowa" => $aProduct['fPrice'],
					"NazwaPelna" => $aProduct['sName'],
					"Jednostka" => empty( $aProduct['sMeasure'] ) ? $lang['Invoices_unit'] : $aProduct['sMeasure'],
					"PKWiU" => "",
					"TypStawkiVat" => "PRC"
				);
			}
			$fCenaPrzes = generatePrice( $aOrder['fCarrierPrice'], $aOrder['sPaymentPrice'], $aOrder['sProductsSummary'] ) + ( $aOrder['iGift'] ? $config['gift_cost'] : 0 );
			if( $fCenaPrzes > 0 ){
				$aCarrierInfo = $oOrder->throwCarrier( $aOrder['iCarrier'] );
				$data['Pozycje'][] = Array(
					"StawkaVat" => throwVatValue( $aCarrierInfo['iVat'] ),
					"Ilosc" => 1,
					"CenaJednostkowa" => $fCenaPrzes,
					"NazwaPelna" => $lang['Delivery_and_payment'],
					"Jednostka" => $lang['Invoices_unit'],
					"PKWiU" => "",
					"TypStawkiVat" => "PRC"
				);
			}
			$data = json_encode( $data );

			$bOk = false;
			
			if( $sType == 'vat' ) $sAdd = 'fakturakraj';
			else $sAdd = 'fakturaproformakraj';
			
			$sUrl = 'https://www.ifirma.pl/iapi/' . $sAdd . '.json';
			$curlHandle = curl_init($sUrl);
			$hashWiadomosci = hash_hmac( 'sha1', 'https://www.ifirma.pl/iapi/' . $sAdd . '.json' . $config['ifirma_login'] . 'faktura' . $data, hex2bin( $config['ifirma_klucz_faktura'] ) );
			$headers = Array( 'Accept: application/json', 'Content-Type: application/json; charset=UTF-8', 'Authentication: IAPIS user=' . $config['ifirma_login'] .', hmac-sha1=' . $hashWiadomosci );
			
			curl_setopt($curlHandle, CURLOPT_TIMEOUT, 300);
			curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 100);
			curl_setopt($curlHandle, CURLOPT_URL, $sUrl);
			curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($curlHandle, CURLOPT_HTTPGET, false);
			curl_setopt($curlHandle, CURLOPT_POST, true);
			curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $data);
			curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, 0);
			
			$result = curl_exec($curlHandle);
			$result = json_decode( $result, true );
			curl_close($curlHandle);
		} else{
			$result = Array( 'response' => Array( 'Kod' => 0, 'Identyfikator' => $aOrder['iFirmaProforma'] ) );
		}
		if( $result['response']['Kod'] == 0 ){
			$oDB->update( DB_ORDERS, Array( 'iFirmaProforma' => $result['response']['Identyfikator'] ), Array( 'iOrder' => $aOrder['iOrder'] ) );
			if( $sType == 'vat' ){
				if( empty( $aOrder['iFirmaFaktura'] ) ){
					
					$sUrl = 'https://www.ifirma.pl/iapi/fakturaproformakraj/add/' . $result['response']['Identyfikator'] . '.json';
					$hashWiadomosci = hash_hmac( 'sha1', $sUrl . $config['ifirma_login'] . 'faktura', hex2bin( $config['ifirma_klucz_faktura'] ) );
					
					$curlHandle = curl_init($sUrl);
					$headers = Array( 'Accept: application/json', 'Content-Type: application/json; charset=UTF-8', 'Authentication: IAPIS user=' . $config['ifirma_login'] .', hmac-sha1=' . $hashWiadomosci );
					
					curl_setopt($curlHandle, CURLOPT_TIMEOUT, 300);
					curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 100);
					curl_setopt($curlHandle, CURLOPT_URL, $sUrl);
					curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
					curl_setopt($curlHandle, CURLOPT_HTTPGET, true);
					curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 0);
					curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, 0);

					$result = curl_exec($curlHandle);
					$result = json_decode( $result, true );
					curl_close($curlHandle);
					
					if( $result['response']['Kod'] == 0 ){
						$oDB->update( DB_ORDERS, Array( 'iFirmaFaktura' => $result['response']['Identyfikator'] ), Array( 'iOrder' => $aOrder['iOrder'] ) );
						$bOk = true;
					} else{
						$oTpl->assign( 'sErrorMessage', $lang['iFirma_error_code'] . ': ' . $result['response']['Kod'] . ': ' . $result['response']['Informacja'] );
						$content .= $oTpl->parse( 'message_other_error.tpl' );
					}
				} else{
					$bOk = true;
					$result = Array( 'response' => Array( 'Kod' => 0, 'Identyfikator' => $aOrder['iFirmaFaktura'] ) );
				}
			} else{
				$bOk = true;
			}
		} else{
			$oTpl->assign( 'sErrorMessage', $lang['iFirma_error_code'] . ': ' . $result['response']['Kod'] . ': ' . $result['response']['Informacja'] );
			$content .= $oTpl->parse( 'message_other_error.tpl' );
		}
		if( $bOk ){
			if( $sReturn == 'pdf' ){
				if( $sType == 'vat' ){
					$sAdd = 'fakturakraj';
				} else{
					$sAdd = 'fakturaproformakraj';
				}
				
				$nazwaUsera = $config['ifirma_login']; //login do ifirma
				$klucz_hex = $config['ifirma_klucz_faktura']; //klucz wygenerowany w ifirmie
				
				$typ_faktury = 'oryg'; //typ faktury w pdfie: np.dup, kopia, oryg, orygkopia
				$nazwaPliku = "./upload/faktura.json";
				$nazwaKlucza = "faktura";
				$typ_pliku = "json"; //rodzaj pliku, ktory wysylamy
				$typ_pobierz = "pdf"; //oczekiwana odpowiedz
				$url = 'https://www.ifirma.pl/iapi/' . $sAdd . '.json';
				$url_get = 'https://www.ifirma.pl/iapi/' . $sAdd . '/';
				
				$curlWysylanieHandle = curl_init($url);
				
				$klucz = hex2bin($klucz_hex);
				$id_faktury = $result['response']['Identyfikator'];
				if (isset($typ_faktury))
					$url_pliku = $url_get.$id_faktury.'.'.$typ_pobierz.'.'.$typ_faktury;
				else
					$url_pliku = $url_get.$id_faktury.'.'.$typ_pobierz;
				$curlHandle = curl_init($url_pliku);

				$hashWiadomosci = hash_hmac( 'sha1', $url_pliku . $nazwaUsera . $nazwaKlucza . $data, $klucz );
				$headers=array(
					'Accept: application/'.$typ_pobierz,
					'Content-type: application/'.$typ_pobierz.'; charset=UTF-8',
					'Authentication: IAPIS user='.$nazwaUsera.', hmac-sha1='.$hashWiadomosci
				);
				curl_setopt($curlHandle, CURLOPT_TIMEOUT, 300);
				curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT,100);
				curl_setopt($curlHandle, CURLOPT_URL, $url_pliku);
				curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($curlHandle, CURLOPT_HTTPGET, true);
				curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST,0);
				curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER,0);

				$tresc = curl_exec($curlHandle);
				$nazwa = $nazwaKlucza."_".$nazwaUsera."_".$id_faktury.'_'.$typ_faktury.'.'.$typ_pobierz;
				curl_close($curlHandle);
				unset($curlHandle);
				header('Content-Type: application/pdf');
				header('Content-disposition: attachment; filename='.$nazwa);
				echo $tresc;	
			} elseif( $sReturn == 'postal_mail' || $sReturn == 'email' ){
				if( $sType == 'vat' ){
					$url = 'fakturakraj/send/' . $result['response']['Identyfikator'] . '.json';
				} else{
					$url = 'fakturaproformakraj/send/' . $result['response']['Identyfikator'] . '.json';
				}
				$data = json_encode( Array(
					'Tekst' => 'Faktura do zamowienia ' . intval( $iOrder ),
					'Przelew' => $aOrder['iPaymentSystem'] != PAID_ON_DELIVERY,
					'Pobranie' => $aOrder['iPaymentSystem'] == PAID_ON_DELIVERY,
					'MTransfer' => 'mtransfer'
				) );
				$hashWiadomosci = hash_hmac( 'sha1', 'https://www.ifirma.pl/iapi/' . $url . $config['ifirma_login'] . 'faktura' . $data, hex2bin( $config['ifirma_klucz_faktura'] ) );
				if( $sReturn == 'postal_mail' ){
					$url .= '?wyslijPoczta=true';
				} else{
					$url .= '?wyslijEfaktura=true';
				}

				$curlHandle = curl_init('https://www.ifirma.pl/iapi/' . $url);
				$headers = Array( 'Accept: application/json', 'Content-Type: application/json; charset=UTF-8', 'Authentication: IAPIS user=' . $config['ifirma_login'] .', hmac-sha1=' . $hashWiadomosci );
				
				curl_setopt($curlHandle, CURLOPT_TIMEOUT, 300);
				curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 100);
				curl_setopt($curlHandle, CURLOPT_URL, 'https://www.ifirma.pl/iapi/' . $url);
				curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($curlHandle, CURLOPT_HTTPGET, false);
				curl_setopt($curlHandle, CURLOPT_POST, true);
				curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $data);
				curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, 0);

				$result = curl_exec($curlHandle);
				$result = json_decode( $result, true );
				curl_close($curlHandle);

				if( $result['response']['Kod'] ){
					$oTpl->assign( 'sErrorMessage', $lang['iFirma_error_code'] . ': ' . $result['response']['Kod'] . ': ' . $result['response']['Informacja'] );
					$content .= $oTpl->parse( 'message_other_error.tpl' );
				} else{
					$content .= $oTpl->parse( 'message_done.tpl' );
				}
			} else{
				$content .= $oTpl->parse( 'message_done.tpl' );
			}
		}
	}
} elseif( $a == 'gt_activate' ){
	if( is_numeric( $iOrder ) ){
		$sOption = null;
		if( $oDB->update( DB_ORDERS, Array( 'iGTExported' => 0 ), Array( 'iOrder' => intval( $iOrder ), 'iGTExported' => -1 ) ) ) $sOption = '&sOption=gt_activate';
		header( 'Location: ?p=orders-list&iStatus=x' . $sOption );
		exit;
	}
} elseif( $a == 'fv_activate' ){
	if( is_numeric( $iOrder ) ){
		if( $_GET['ajax'] == 'ajax' ){
			if( $oDB->update( DB_ORDERS, Array( 'sInvoiceId' => 'tak' ), Array( 'iOrder' => intval( $iOrder ) ) ) ) echo('ok');
			exit;
		} else{
			$sOption = null;
			if( $oDB->update( DB_ORDERS, Array( 'sInvoiceId' => 'tak' ), Array( 'iOrder' => intval( $iOrder ) ) ) ) $sOption = '&sOption=fv_activate';
			header( 'Location: ?p=orders-list&iStatus=x' . $sOption );
			exit;
		}
	}
}
?>