<?php 

namespace Encgateway;

class ApiResource {
	
	protected static function _create($params = null, $options = null)
    {
        self::_validateArray($params);
		return $params;
    }
	
	public function _validateArray($params = null)
    {
		$t = true;
        if ($params && !is_array($params)) {
			$t = false;
        }
		return $t; 
    }
	
	public function _doTrans($params,$processors){
		$Apib  = new Apib;
		$url = '';
		$error = array();
		$baseUrl = $Apib->getApiBase(); 
		$url = $baseUrl.'/ws/encgateway2.asmx/'.$processors;
		
		if($processors == 'GetCardTrx'){$url = $baseUrl.'/ws/encgateway.asmx/'.$processors;}
		
		if($processors == 'ManageCustomer' || $processors == 'CaptureReceipt' || $processors == 'ManageContract' || $processors == 'ManageCreditCardInfo' || $processors == 'ManageCheckInfo' || $processors == 'ManageContractAddDaysToNextBillDt' ){$url = $baseUrl.'/ws/recurring.asmx/'.$processors;}
		
		if($processors == 'StoreCard') { $url = $baseUrl.'ws/cardsafe.asmx/'.$processors; }
		
		if($processors == 'ProcessStoredCard') { $url = $baseUrl.'ws/cardsafe.asmx/'.$processors; }
		
		$req =  urldecode(http_build_query($params));
		$_FOLLOWLOCATION = true;
		$_RETURNTRANSFER = true;
		if(isset($params['ReturnTransfer'])) {
			$_FOLLOWLOCATION = true;
			$_RETURNTRANSFER = false;
		}
		
		$ch = curl_init();
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, $_FOLLOWLOCATION);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, $_RETURNTRANSFER);
		curl_setopt ($ch, CURLOPT_POST, 1);
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $req);
		
		curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
		curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, false);
		$xmlRaw = curl_exec ($ch);
		
		if($processors == 'GetCardTrx') { 
			$responce = json_decode($xmlRaw,1); 
		}else {
			$xml = simplexml_load_string ($xmlRaw);
			$responce = json_decode(json_encode ($xml),true);
		}
		curl_close($ch);
		return $responce;
	}
	
	public function responseFormat($data = array(),$format){
		$ret = '';
		switch(trim($format)) {
			case 'json':
				$ret = json_encode($data);
			break;
			case 'xml' :
				$ret = generate_valid_xml_from_array($data);
			break;
			case 'array':
				$ret = $data;
			break;	
			default : 
				echo 'not valid';
				exit;
			break;
			
		}
		return $ret;
		
	}
	
}