<?php
require_once( $config['dir_libraries'] . 'paczkomaty/inpost.php' );
if( $a == 'nearest' ){
	$aPaczkomaty = inpost_find_nearest_machines( $_GET['postcode'], $_GET['paid_on_delivery'] );
	if( !empty( $_GET['email'] ) ){
		$aCustomer = inpost_find_customer( $_GET['email'] );
		$aAllMachinesT = inpost_get_machine_list( null, $_GET['paid_on_delivery'] );
		$aAllMachines = Array();
		foreach( $aAllMachinesT as $aMachine ){
			$aAllMachines[$aMachine['name']] = $aMachine;
		}
		if( !empty( $aCustomer['alternativeBoxMachineName'] ) ){
			if( isset( $aAllMachines[$aCustomer['alternativeBoxMachineName']] ) ){
				array_unshift( $aPaczkomaty, $aAllMachines[$aCustomer['alternativeBoxMachineName']] );
			}
		}
		if( !empty( $aCustomer['preferedBoxMachineName'] ) ){
			if( isset( $aAllMachines[$aCustomer['preferedBoxMachineName']] ) ){
				array_unshift( $aPaczkomaty, $aAllMachines[$aCustomer['preferedBoxMachineName']] );
			}
		}
	}
	if( is_array( $aPaczkomaty ) ){
		$oTpl->assign( 'aPaczkomaty', $aPaczkomaty );
		$oTpl->assign( 'aPaczkomatyInfo', Array( 'bNearest' => true ) );
		echo $oTpl->parse( 'paczkomaty.tpl' );
	} else{
		header( 'Location: index.php?p=paczkomaty-towns' );
	}
	exit;
} elseif( $a == 'towns' ){
	$aTowns = inpost_get_towns( );
	$oTpl->assign( 'aTowns', $aTowns );
	$oTpl->assign( 'aPaczkomatyInfo', Array( 'bNearest' => false ) );
	echo $oTpl->parse( 'paczkomaty.tpl' );
	exit;
} elseif( $a == 'in_town' && isset( $_GET['town'] ) ){
	$aPaczkomaty = inpost_get_machine_list( $_GET['town'] );
	$aPaczkomatyToJSON = Array( );
	if( is_array( $aPaczkomaty ) ) foreach( $aPaczkomaty as $aPaczkomat ){
		$aPaczkomatyToJSON[] = Array( 'id' => $aPaczkomat['name'], 'name' => $aPaczkomat['town'] . ' ' . $aPaczkomat['street'] . ' ' . $aPaczkomat['buildingnumber'] . ' ' . $aPaczkomat['postcode'] . ' (' . $aPaczkomat['locationdescription'] . ')' );
	}
	echo ( json_encode( $aPaczkomatyToJSON ) );
	exit;
} else{
	echo ( 'Error!' );
	exit;
}
