<?php

namespace Encgateway;

class Charge extends ApiResource {
	
	public static $data = array(); 
	
	public static $processors = "ProcessCreditCard";
	
	public static $transType = array('Sale','Auth','Return','Force','Capture','Void','Reversal','Refund','Repeat');
	
	public static function validParams($param){
		$TransType = $param['TransType'];
		$is_valid = false;
		if( isset($TransType) && in_array($TransType, self::$transType) ) {
			$is_valid = 1;
			if($TransType == 'Sale' || $TransType == 'Auth' ) {
				$is_valid = GUMP::is_valid($param, array(
					'TransType' => 'required|max_len,256',
					'NameOnCard' => 'required|max_len,256',
					'ExpDate' => 'required|max_len,4',
					'CardNum' => 'required|valid_cc|max_len,16',
					'CVNum' => 'required|max_len,4',
					'InvNum' => 'required',
					'Zip' => 'required',
					'City' => 'required',
					'State' => 'required',
					'Street' => 'required',
					'Amount' => 'required|float',
					'SureChargeAmt' => 'required',
					'CashBackAmt' => 'required',
					'ExtData' => 'required',
					'RegisterNum' => 'max_len,4',
				));		
			}elseif($TransType == 'Force') {
				$is_valid = GUMP::is_valid($param, array(
					'PNRef' => 'required',
				));
			}elseif($TransType == 'Repeat') {
				$is_valid = GUMP::is_valid($param, array(
					'PNRef' => 'required',
				));	
			}elseif($TransType == 'Return') {
				$is_valid = GUMP::is_valid($param, array(
					'PNRef' => 'required',
					'Amount' => 'required|float',
				));		
			}elseif($TransType == 'Void') {
				$is_valid = GUMP::is_valid($param, array(
					'PNRef' => 'required',
				));
			}
		}
		
		/*
		* add validate exception for chinaunionpay
		*/
		if(isset($param['RegisterNum']) && $param['RegisterNum'] == 56) {
			$is_valid = true;
		}
		
		return $is_valid;
	}
	
	public static function create($params = null)
    {	
		$params['apitoken'] 	= Apib::getApiKey();
		if(isset($params['RegisterNum']) && $params['RegisterNum'] == 56) {
			$params['ReturnTransfer'] = true;
		}
		self::$data['params'] 	= $params;
		self::$data['success'] 	= 0;
		self::$data['error'] 	= '';
		if(self::_validateArray($params)){
			$ret = self::validParams($params);
			
			if($ret == 1){
				$response = self::_doTrans($params,self::$processors);
				self::$data['response'] = $response; 
				
				if(isset($response['Result'])) : 
					self::$data['success'] = 1;
				endif;
			}else{
				self::$data['error'] = $ret;
			}
		}else{
			self::$data['error']['invalid_argument'] = 'Array is not valid, You must pass array is argument.';
		}
		
		self::$data = self::responseFormat(self::$data,Apib::getOutputFormat());
		return self::$data;
    }
}