<?php
class ControllerExtensionPaymentSagepayUS extends Controller {
	public function index() {
		$this->load->language('extension/payment/sagepay_us');
		$data['button_confirm'] = $this->language->get('button_confirm');

		$data['form_action'] = $this->url->link('extension/payment/sagepay_us/confirm', '', true);

		return $this->load->view('extension/payment/sagepay_us', $data);
	}


	public function confirm() {

		if ($this->request->server['REQUEST_METHOD'] != 'POST') {
			//$this->response->redirect($this->url->link('checkout/checkout', '', true));
		}
		$this->load->model('checkout/order');

		$order_id = $this->session->data['order_id'];
		$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

		//$paymentURL = "https://uat.mepsfpx.com.my/FPXMain/seller2DReceiver.jsp";
		$paymentURL = "https://www.mepsfpx.com.my/FPXMain/seller2DReceiver.jsp";

		// Live
		$exchangeID = "EX00011689";
		$sellerID = "SE00052704";

		/* test */
		//$exchangeID = "EX00013111";
		//$sellerID = "SE00014649";
		/* test */

		$data['merchant_name'] = "VIVA LIFE SCIENCE SDN BHD";
		$data['fpx_reference'] = "VIVAFPX-".date('YmdHis');
		$data['order_number'] = $order_id;
		$data['order_description'] = 'Purchase of order: '.$order_id;
		$data['order_amount'] = number_format($this->currency->format($order_info['total'], $order_info['currency_code'], false, false), 2);

		$data['form_action'] = $this->url->link('extension/payment/sagepay_us/confirm2', '', true);

		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');

		$this->response->setOutput($this->load->view('extension/payment/sagepay_us_confirm', $data));
	}


	public function confirm2() {

		if ($this->request->server['REQUEST_METHOD'] == 'POST') {

			$this->load->model('checkout/order');

			$order_id = $this->session->data['order_id'];
			$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

			$fpx_buyerBankId = $this->request->post['fpx_buyerBankId'];

			//$paymentURL = "https://uat.mepsfpx.com.my/FPXMain/seller2DReceiver.jsp";
			$paymentURL = "https://www.mepsfpx.com.my/FPXMain/seller2DReceiver.jsp";

			// Live
			$exchangeID = "EX00011689";
			$sellerID = "SE00052704";

			/* test */
			//$exchangeID = "EX00013111";
			//$sellerID = "SE00014649";
			/* test */

			$data['merchant_name'] = "VIVA LIFE SCIENCE SDN BHD";
			$data['fpx_reference'] = $this->request->post['fpx_reference'];
			$data['order_number'] = $order_id;
			$data['order_description'] = 'Purchase of order '.$order_id;
			$data['order_amount'] = number_format($this->currency->format($order_info['total'], $order_info['currency_code'], false, false), 2);

			$current_time = date('YmdHis');
			$total_amount = number_format($this->currency->format($order_info['total'], $order_info['currency_code'], false, false),2,'.', '');

			$data['form_action'] = $paymentURL;

			$data['fpx_msgType'] = 'AR';
			$data['fpx_msgToken'] = '01';

			$data['fpx_sellerExId'] = $exchangeID;
			$data['fpx_sellerId'] = $sellerID;

			$data['fpx_sellerExOrderNo'] = $this->request->post['fpx_reference'];
			$data['fpx_sellerTxnTime'] = $current_time;
			$data['fpx_sellerOrderNo'] = $order_id;
			$data['fpx_sellerBankCode'] = '01';
			$data['fpx_txnCurrency'] = 'MYR';
			$data['fpx_txnAmount'] = $total_amount;
			$data['fpx_buyerEmail'] = $order_info['email'];

			$data['fpx_buyerBankId'] = $fpx_buyerBankId;
			$data['fpx_version'] = '7.0';
			$data['fpx_productDesc'] = $data['order_description'];


			$fpx_buyerBankBranch="";
			$fpx_buyerAccNo="";
			$fpx_buyerIban="";
			$fpx_buyerId="";
			$fpx_makerName="";
			$fpx_buyerName="";

			$check_sum = $fpx_buyerAccNo."|".$fpx_buyerBankBranch."|".$data['fpx_buyerBankId']."|".$data['fpx_buyerEmail']."|".$fpx_buyerIban."|".$fpx_buyerId."|".$fpx_buyerName."|".$fpx_makerName."|".$data['fpx_msgToken']."|".$data['fpx_msgType']."|".$data['fpx_productDesc']."|".$data['fpx_sellerBankCode']."|".$data['fpx_sellerExId']."|".$data['fpx_sellerExOrderNo']."|".$data['fpx_sellerId']."|".$data['fpx_sellerOrderNo']."|".$current_time."|".$data['fpx_txnAmount']."|".$data['fpx_txnCurrency']."|".$data['fpx_version'];

			/* Reading key */

			// test
			//$priv_key = file_get_contents('/home/iconcep1/vivalife.com.my/estore/test/cert/EX00013111.key');
			// live
			$priv_key = file_get_contents('/home/iconcep1/vivalife.com.my/estore/test/cert/EX00011689.key');

			$pkeyid = openssl_get_privatekey($priv_key);
			openssl_sign($check_sum, $binary_signature, $pkeyid, OPENSSL_ALGO_SHA1);
			$fpx_checkSum = strtoupper(bin2hex( $binary_signature ) );

			if (!$privateKey = openssl_pkey_get_private($priv_key)) die('Loading Private Key failed');

			$data['fpx_checkSum'] = $fpx_checkSum;


			//UAT
			/*
			$full_list = array(
				'ABB0234' => 'Affin B2C - Test ID',
				'ABB0233' => 'Affin Bank',
				'ABMB0212' => 'Alliance Bank (Personal)',
				'AGRO01' => 'AGRONet',
				'AMBB0209' => 'AmBank',
				'BIMB0340' => 'Bank Islam',
				'BMMB0341' => 'Bank Muamalat',
				'BOCM01' => 'Bank of China',
				'BKRM0602' => 'Bank Rakyat',
				'BSN0601' => 'BSN',
				'BCBB0235' => 'CIMB Clicks',
				'CIT0219' => 'Citibank',
				'HLB0224' => 'Hong Leong Bank',
				'HSBC0223' => 'HSBC Bank',
				'KFH0346' => 'KFH',
				'LOAD001' => 'LOAD001',
				'MBB0228' => 'Maybank2E',
				'MB2U0227' => 'Maybank2U',
				'OCBC0229' => 'OCBC Bank',
				'PBB0233' => 'Public Bank',
				'RHB0218' => 'RHB Bank',
				'TEST0021' => 'SBI Bank A',
				'TEST0022' => 'SBI Bank B',
				'TEST0023' => 'SBI Bank C',
				'SCB0216' => 'Standard Chartered',
				'UOB0226' => 'UOB Bank',
				'UOB0229' => 'UOB Bank - Test ID'
			);
			*/

			//Production

			$full_list = array(
				'ABB0233' => 'Affin Bank',
				'ABMB0212' => 'Alliance Bank (Personal)',
				'AGRO01' => 'AGRONet',
				'AMBB0209' => 'AmBank',
				'BIMB0340' => 'Bank Islam',
				'BMMB0341' => 'Bank Muamalat',
				'BOCM01' => 'Bank of China',
				'BKRM0602' => 'Bank Rakyat',
				'BSN0601' => 'BSN',
				'BCBB0235' => 'CIMB Clicks',
				'CIT0219' => 'Citibank',
				'HLB0224' => 'Hong Leong Bank',
				'HSBC0223' => 'HSBC Bank',
				'KFH0346' => 'KFH',
				'MBB0228' => 'Maybank2E',
				'MB2U0227' => 'Maybank2U',
				'OCBC0229' => 'OCBC Bank',
				'PBB0233' => 'Public Bank',
				'RHB0218' => 'RHB Bank',
				'SCB0216' => 'Standard Chartered',
				'UOB0226' => 'UOB Bank'
			);

			$selected_bank = "";
			foreach( $full_list as $key => $value ) {

				if( $key == $fpx_buyerBankId ) {
					$selected_bank = $value;
				}

			}
			$data['selected_bank'] = $selected_bank;


			// update order data for FPX
			$this->model_checkout_order->update_fpx_details($data['fpx_sellerExOrderNo'],$data['fpx_sellerTxnTime'],$data['fpx_sellerOrderNo'],$data['fpx_buyerBankId'],$data['fpx_productDesc'], $order_id);




			$data['column_left'] = $this->load->controller('common/column_left');
			$data['column_right'] = $this->load->controller('common/column_right');
			$data['content_top'] = $this->load->controller('common/content_top');
			$data['content_bottom'] = $this->load->controller('common/content_bottom');
			$data['footer'] = $this->load->controller('common/footer');
			$data['header'] = $this->load->controller('common/header');

			$this->response->setOutput($this->load->view('extension/payment/sagepay_us_confirm2', $data));

			} else {
					$this->response->redirect($this->url->link('checkout/checkout', '', true));
			}
		}



		public function callback() {

			/// Summary description for Controller
			///  ErrorCode  : Description
			///  00         : Your signature has been verified successfully.
			///  06         : No Certificate found
			///  07         : One Certificate Found and Expired
			///  08         : Both Certificates Expired
			///  09         : Your Data cannot be verified against the Signature.
			function hextobin($hexstr)
			{
				$n = strlen($hexstr);
				$sbin="";
				$i=0;
				while($i<$n)
				{
					$a =substr($hexstr,$i,2);
					$c = pack("H*",$a);
					if ($i==0){$sbin=$c;}
					else {$sbin.=$c;}
					$i+=2;
				}
				return $sbin;
			}


			function validateCertificate($path,$sign, $toSign)
			{
				global  $ErrorCode;

				$d_ate=date("Y");
				//validating Last Three Certificates
				$fpxcert=array($path."fpxprod_current.cer",$path."fpxprod.cer");
				$certs=checkCertExpiry($fpxcert);
				// echo count($certs) ;
				    	$signdata = hextobin($sign);


				if(count($certs)==1)
				{

				   $pkeyid =openssl_pkey_get_public($certs[0]);
			   	   $ret = openssl_verify($toSign, $signdata, $pkeyid);
				      if($ret!=1)
				      {
				  	   $ErrorCode=" Your Data cannot be verified against the Signature. "." ErrorCode :[09]";
				  	   return "09";
				      }
			    }
				 elseif(count($certs)==2)
				{

				 $pkeyid =openssl_pkey_get_public($certs[0]);
			   	 $ret = openssl_verify($toSign, $signdata, $pkeyid);
				   if($ret!=1)
				   {

				    $pkeyid =openssl_pkey_get_public($certs[1]);
			   	    $ret = openssl_verify($toSign, $signdata, $pkeyid);
			         if($ret!=1)
				     {
					  $ErrorCode=" Your Data cannot be verified against the Signature. "." ErrorCode :[09]";
					  return "09";
				      }
				    }

				}
				 if($ret==1)
				 {

			        $ErrorCode=" Your signature has been verified successfully. "." ErrorCode :[00]";
			        return "00";
			 	 }


				return $ErrorCode;



			}
			function verifySign_fpx($sign,$toSign)
			{
			   error_reporting(0);

			return validateCertificate('/home/iconcep1/vivalife.com.my/estore/test/cert/',$sign, $toSign);
			}

			function checkCertExpiry($path)
			{
					global  $ErrorCode;

			      $stack = array();
			    $t_ime= time();
			    $curr_date=date("Ymd",$t_ime);
			     for($x=0;$x<2;$x++)
				 {
					   error_reporting(0);
			          $key_id = file_get_contents($path[$x]);
				       if($key_id==null)
				       {
						   $cert_exists++;
				      	 continue;
				       }
				       $certinfo = openssl_x509_parse($key_id);
			           $s= $certinfo['validTo_time_t'];
			           $crtexpirydate=date("Ymd",$s-86400);
			    	  if($crtexpirydate > $curr_date)
				       {
						    if ($x > 0)
							{
							 if(certRollOver($path[$x], $path[$x-1])=="true")
								 {  array_push($stack,$key_id);
									return $stack;
			                      }
							}
			                array_push($stack,$key_id);
				      	  return $stack;
			           }
				       elseif($crtexpirydate == $curr_date)
				       {
						     if ($x > 0 && (file_exists($path[$x-1])!=1))
							 {
			                       if(certRollOver($path[$x], $path[$x-1])=="true")
								   {  array_push($stack,$key_id);
									  return $stack;
								 }
							 }
							 else if(file_exists($path[$x+1])!=1)
							 {
			                     array_push($stack,file_get_contents($path[$x]),$key_id);
			                     return $stack;
							 }


				      	    array_push($stack,file_get_contents($path[$x+1]),$key_id);

				      		return $stack;
				      	}

				 }
			          if ($cert_exists == 2)
			                $ErrorCode="Invalid Certificates.  " . " ErrorCode : [06]";  //No Certificate (or) All Certificate are Expired
			            else if ($stack.Count == 0 && $cert_exists == 1)
			                $ErrorCode="One Certificate Found and Expired " . "ErrorCode : [07]";
			            else if ($stack.Count == 0 && $cert_exists == 0)
			               $ErrorCode="Both Certificates Expired " . "ErrorCode : [08]";
			            return $stack;


			}
			function certRollOver($old_crt,$new_crt)
			{

			        if (file_exists($new_crt)==1)
			        {

			                rename($new_crt,$new_crt."_".date("YmdHis", time()));//FPXOLD.cer to FPX_CURRENT.cer_<CURRENT TIMESTAMP>

			        }
					if ((file_exists($new_crt)!=1) && (file_exists($old_crt)==1))
			        {
			            rename($old_crt,$new_crt);                                 //FPX.cer to FPX_CURRENT.cer
			        }


					return "true";
			}

			$fpx_buyerBankBranch=$_POST['fpx_buyerBankBranch'];
			$fpx_buyerBankId=$_POST['fpx_buyerBankId'];
			$fpx_buyerIban=$_POST['fpx_buyerIban'];
			$fpx_buyerId=$_POST['fpx_buyerId'];
			$fpx_buyerName=$_POST['fpx_buyerName'];
			$fpx_creditAuthCode=$_POST['fpx_creditAuthCode'];
			$fpx_creditAuthNo=$_POST['fpx_creditAuthNo'];
			$fpx_debitAuthCode=$_POST['fpx_debitAuthCode'];
			$fpx_debitAuthNo=$_POST['fpx_debitAuthNo'];
			$fpx_fpxTxnId=$_POST['fpx_fpxTxnId'];
			$fpx_fpxTxnTime=$_POST['fpx_fpxTxnTime'];
			$fpx_makerName=$_POST['fpx_makerName'];
			$fpx_msgToken=$_POST['fpx_msgToken'];
			$fpx_msgType=$_POST['fpx_msgType'];
			$fpx_sellerExId=$_POST['fpx_sellerExId'];
			$fpx_sellerExOrderNo=$_POST['fpx_sellerExOrderNo'];
			$fpx_sellerId=$_POST['fpx_sellerId'];
			$fpx_sellerOrderNo=$_POST['fpx_sellerOrderNo'];
			$fpx_sellerTxnTime=$_POST['fpx_sellerTxnTime'];
			$fpx_txnAmount=$_POST['fpx_txnAmount'];
			$fpx_txnCurrency=$_POST['fpx_txnCurrency'];
			$fpx_checkSum=$_POST['fpx_checkSum'];

			$data=$fpx_buyerBankBranch."|".$fpx_buyerBankId."|".$fpx_buyerIban."|".$fpx_buyerId."|".$fpx_buyerName."|".$fpx_creditAuthCode."|".$fpx_creditAuthNo."|".$fpx_debitAuthCode."|".$fpx_debitAuthNo."|".$fpx_fpxTxnId."|".$fpx_fpxTxnTime."|".$fpx_makerName."|".$fpx_msgToken."|".$fpx_msgType."|".$fpx_sellerExId."|".$fpx_sellerExOrderNo."|".$fpx_sellerId."|".$fpx_sellerOrderNo."|".$fpx_sellerTxnTime."|".$fpx_txnAmount."|".$fpx_txnCurrency;

			$val=verifySign_fpx($fpx_checkSum, $data);


			/* test webhook */
			//log file write
			$abs_dir = dirname(__FILE__);
			$myfile = fopen($abs_dir."/fpx-log/log.txt", "a+") or die("Unable to open file!");
			$txt = print_r($_POST, true);
			//$txt .= ' ||| '.$val;
			fwrite($myfile, $txt);
			fclose($myfile);
			/* test webhook */

			if( $val == "00"  || $val == "09")  {

				if( $_POST['fpx_debitAuthCode'] == "00" || $_POST['fpx_creditAuthCode'] == "00") {

					$order_id = abs($_POST["fpx_sellerOrderNo"]);
					$this->load->model('checkout/order');
					$order_info = $this->model_checkout_order->getOrder($order_id);

					if ($order_info) {

						$comment = 'Status Code: ' . $_POST['fpx_debitAuthCode'] . ' <br>FPX Transaction ID: ' .$_POST['fpx_fpxTxnId'] . '<br>FPX Payment Reference: ' . $_POST['fpx_sellerExOrderNo'];

						$this->model_checkout_order->addOrderHistory($order_id, $this->config->get('payment_skrill_order_status_id'), $comment, false);


						$this->load->model('account/customer');
						$customer_info = $this->model_account_customer->getCustomer($order_info['customer_id']);
						$customer_id = $customer_info['customer_id'];

						$this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE customer_id = '" . (int)$customer_id . "'");

						// reponse OK to FPX.
						echo "OK";

					}
				}

			}



			//return $this->load->view('extension/payment/sagepay_us', $data);
		}



		public function banklist() {

			// return bank list

			// get bank list from FPX
			function hextobin($hexstr)
			{
				$n = strlen($hexstr);
				$sbin="";
				$i=0;
				while($i<$n)
				{
					$a =substr($hexstr,$i,2);
					$c = pack("H*",$a);
					if ($i==0){$sbin=$c;}
					else {$sbin.=$c;}
					$i+=2;
				}
				return $sbin;
			}

			function validateCertificate($path,$sign, $toSign)
			{
				global  $ErrorCode;

				$d_ate = date("Y");
				//validating Last Three Certificates


				$fpxcert=array($path."fpxprod_current.cer",$path."fpxprod.cer");
				$certs = checkCertExpiry($fpxcert);
				$signdata = hextobin($sign);


				if(count($certs) == 1)
				{

					$pkeyid =openssl_pkey_get_public($certs[0]);
						$ret = openssl_verify($toSign, $signdata, $pkeyid);

						 if($ret!=1)
						 {
							$ErrorCode=" Your Data cannot be verified against the Signature. "." ErrorCode :[09]";
							return "09";
						 }
					}
				 elseif(count($certs)==2)
				{

					$pkeyid =openssl_pkey_get_public($certs[0]);
						 $ret = openssl_verify($toSign, $signdata, $pkeyid);
					 if($ret!=1)
					 {

						$pkeyid =openssl_pkey_get_public($certs[1]);
								$ret = openssl_verify($toSign, $signdata, $pkeyid);
								if($ret!=1)
						 {
						$ErrorCode=" Your Data cannot be verified against the Signature. "." ErrorCode :[09]";
						return "09";
							}
						}

				}
				 if($ret==1)
				 {

							$ErrorCode=" Your signature has been verified successfully. "." ErrorCode :[00]";
							return "00";
				 }


				return $ErrorCode;



			}
			
			function verifySign_fpx($sign,$toSign)
			{
				 //error_reporting(1);

			return validateCertificate('/home/iconcep1/vivalife.com.my/estore/test/cert/',$sign, $toSign);
			}

			function checkCertExpiry($path)
			{
					global  $ErrorCode;

						$stack = array();
					$t_ime= time();
					$curr_date=date("Ymd",$t_ime);
					 for($x=0;$x<2;$x++)
				 {

								$key_id = file_get_contents($path[$x]);
							 if($key_id==null)
							 {
							 $cert_exists++;
								 continue;
							 }
							 $certinfo = openssl_x509_parse($key_id);
								 $s= $certinfo['validTo_time_t'];
								 $crtexpirydate=date("Ymd",$s-86400);
							if($crtexpirydate > $curr_date)
							 {
								if ($x > 0)
							{
							 if(certRollOver($path[$x], $path[$x-1])=="true")
								 {  array_push($stack,$key_id);
									return $stack;
														}
							}
											array_push($stack,$key_id);

									return $stack;
								 }
							 elseif($crtexpirydate == $curr_date)
							 {
								 if ($x > 0 && (file_exists($path[$x-1])!=1))
							 {
														 if(certRollOver($path[$x], $path[$x-1])=="true")
									 {  array_push($stack,$key_id);
										return $stack;
								 }
							 }
							 else if(file_exists($path[$x+1])!=1)
							 {
									 array_push($stack,file_get_contents($path[$x]),$key_id);
															 return $stack;
							 }


										array_push($stack,file_get_contents($path[$x+1]),$key_id);

									return $stack;
								}

				 }
								if ($cert_exists == 2)
											$ErrorCode="Invalid Certificates.  " . " ErrorCode : [06]";  //No Certificate (or) All Certificate are Expired
									else if ($stack.Count == 0 && $cert_exists == 1)
											$ErrorCode="One Certificate Found and Expired " . "ErrorCode : [07]";
									else if ($stack.Count == 0 && $cert_exists == 0)
										 $ErrorCode="Both Certificates Expired " . "ErrorCode : [08]";
									return $stack;


			}
			
			function certRollOver($old_crt,$new_crt)
			{

							if (file_exists($new_crt)==1)
							{

											rename($new_crt,$new_crt."_".date("YmdHis", time()));//FPXOLD.cer to FPX_CURRENT.cer_<CURRENT TIMESTAMP>

							}
					if ((file_exists($new_crt)!=1) && (file_exists($old_crt)==1))
							{
									rename($old_crt,$new_crt);                                 //FPX.cer to FPX_CURRENT.cer
							}


					return "true";
			}

			$fpx_msgToken="01";
			$fpx_msgType="BE";
			$fpx_sellerExId="EX00011689";
			$fpx_version="7.0";
			/* Generating signing String */
			$data=$fpx_msgToken."|".$fpx_msgType."|".$fpx_sellerExId."|".$fpx_version;
			/* Reading key */
			$priv_key = file_get_contents('/home/iconcep1/vivalife.com.my/estore/test/cert/EX00011689.key');
			$pkeyid = openssl_get_privatekey($priv_key);
			openssl_sign($data, $binary_signature, $pkeyid, OPENSSL_ALGO_SHA1);
			$fpx_checkSum = strtoupper(bin2hex( $binary_signature ) );



			//extract data from the post

			extract($_POST);
			$fields_string="";

			//set POST variables
			// UAT
			//$url ='https://uat.mepsfpx.com.my/FPXMain/RetrieveBankList';
			// live
			$url ='https://www.mepsfpx.com.my/FPXMain/RetrieveBankList';

			$fields = array(
									'fpx_msgToken' => urlencode($fpx_msgToken),
									'fpx_msgType' => urlencode($fpx_msgType),
									'fpx_sellerExId' => urlencode($fpx_sellerExId),
									'fpx_checkSum' => urlencode($fpx_checkSum),
									'fpx_version' => urlencode($fpx_version)

							);
			$response_value=array();
			$bank_list=array();

			try{
			//url-ify the data for the POST
			foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
			rtrim($fields_string, '&');

			//open connection
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

			//set the url, number of POST vars, POST data
			curl_setopt($ch,CURLOPT_URL, $url);

			curl_setopt($ch,CURLOPT_POST, count($fields));
			curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

			// receive server response ...
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			//execute post
			$result = curl_exec($ch);

			//close connection
			curl_close($ch);

			$token = strtok($result, "&");
			while ($token !== false)
			{
				list($key1,$value1)=explode("=", $token);
				$value1=urldecode($value1);
				$response_value[$key1]=$value1;
				$token = strtok("&");
			}

			$fpx_msgToken=reset($response_value);

			//Response Checksum Calculation String
			$data=$response_value['fpx_bankList']."|".$response_value['fpx_msgToken']."|".$response_value['fpx_msgType']."|".$response_value['fpx_sellerExId'];
			$val=verifySign_fpx($response_value['fpx_checkSum'], $data);

			// val == 00 verification success

			$token = strtok($response_value['fpx_bankList'], ",");

			while ($token !== false)
			{
				list($key1,$value1) = explode("~", $token);
				$value1 = urldecode($value1);
				$bank_list[$key1] = $value1;
				$token = strtok(",");
			}


			}
			catch(Exception $e){
				echo 'Error :', ($e->getMessage());
			}

			//UAT
			/*
			$full_list = array(
				'ABB0234' => 'Affin B2C - Test ID',
				'ABB0233' => 'Affin Bank',
				'ABMB0212' => 'Alliance Bank (Personal)',
				'AGRO01' => 'AGRONet',
				'AMBB0209' => 'AmBank',
				'BIMB0340' => 'Bank Islam',
				'BMMB0341' => 'Bank Muamalat',
				'BOCM01' => 'Bank of China',
				'BKRM0602' => 'Bank Rakyat',
				'BSN0601' => 'BSN',
				'BCBB0235' => 'CIMB Clicks',
				'CIT0219' => 'Citibank',
				'HLB0224' => 'Hong Leong Bank',
				'HSBC0223' => 'HSBC Bank',
				'KFH0346' => 'KFH',
				'LOAD001' => 'LOAD001',
				'MBB0228' => 'Maybank2E',
				'MB2U0227' => 'Maybank2U',
				'OCBC0229' => 'OCBC Bank',
				'PBB0233' => 'Public Bank',
				'RHB0218' => 'RHB Bank',
				'TEST0021' => 'SBI Bank A',
				'TEST0022' => 'SBI Bank B',
				'TEST0023' => 'SBI Bank C',
				'SCB0216' => 'Standard Chartered',
				'UOB0226' => 'UOB Bank',
				'UOB0229' => 'UOB Bank - Test ID'
			);
			*/

			//Production

			$full_list = array(
				'ABB0233' => 'Affin Bank',
				'ABMB0212' => 'Alliance Bank (Personal)',
				'AGRO01' => 'AGRONet',
				'AMBB0209' => 'AmBank',
				'BIMB0340' => 'Bank Islam',
				'BMMB0341' => 'Bank Muamalat',
				'BOCM01' => 'Bank of China',
				'BKRM0602' => 'Bank Rakyat',
				'BSN0601' => 'BSN',
				'BCBB0235' => 'CIMB Clicks',
				'CIT0219' => 'Citibank',
				'HLB0224' => 'Hong Leong Bank',
				'HSBC0223' => 'HSBC Bank',
				'KFH0346' => 'KFH',
				'MBB0228' => 'Maybank2E',
				'MB2U0227' => 'Maybank2U',
				'OCBC0229' => 'OCBC Bank',
				'PBB0233' => 'Public Bank',
				'RHB0218' => 'RHB Bank',
				'SCB0216' => 'Standard Chartered',
				'UOB0226' => 'UOB Bank'
			);

			$list_option = array();
			foreach($full_list as $key1 => $value1) {
				foreach($bank_list as $key => $value) {
					if($key1 ==  $key ) {
						$bank_name = $value1 ;
						$valid = '';
						$disabled = "";
						$offline = "";
						if($value == "B") {
							$disabled = " disabled";
							$offline = " (offline)";
						}
						$list_option[] = '<option class="'.$valid.'" '. $disabled .' value="'. $key1 .'"> '. $bank_name.$offline .'</option>';
					}
				}
			}


			// end bank list
			$this->response->addHeader('Content-Type: application/json');
			$this->response->setOutput(json_encode($list_option));

		}


		// AE message / re-query cron
		public function aequery() {

				//error_reporting(E_ALL);
				$this->load->model('checkout/order');
				$orders = $this->model_checkout_order->query_fpx_orders();

				// Live
				$exchangeID = "EX00011689";
				$sellerID = "SE00052704";

				/* test */
				//$exchangeID = "EX00013111";
				//$sellerID = "SE00014649";
				/* test */
				// echo '<pre>';
				// print_r($orders);die;

				function hextobin($hexstr)
				{
					$n = strlen($hexstr);
					$sbin="";
					$i=0;
					while($i<$n)
					{
						$a =substr($hexstr,$i,2);
						$c = pack("H*",$a);
						if ($i==0){$sbin=$c;}
						else {$sbin.=$c;}
						$i+=2;
					}
					return $sbin;
				}

				function validateCertificate($path,$sign, $toSign)
				{
					global  $ErrorCode;

					$d_ate=date("Y");
					//validating Last Three Certificates
					$fpxcert=array($path."fpxprod_current.cer",$path."fpxprod.cer");
					$certs=checkCertExpiry($fpxcert);
					// echo count($certs) ;
					    	$signdata = hextobin($sign);
					if(count($certs)==1)
					{

					   $pkeyid =openssl_pkey_get_public($certs[0]);
				   	   $ret = openssl_verify($toSign, $signdata, $pkeyid);
					      if($ret!=1)
					      {
					  	   $ErrorCode=" Your Data cannot be verified against the Signature. "." ErrorCode :[09]";
					  	   return "09";
					      }
				    }
					 elseif(count($certs)==2)
					{

					 $pkeyid =openssl_pkey_get_public($certs[0]);
				   	 $ret = openssl_verify($toSign, $signdata, $pkeyid);
					   if($ret!=1)
					   {

					    $pkeyid =openssl_pkey_get_public($certs[1]);
				   	    $ret = openssl_verify($toSign, $signdata, $pkeyid);
				         if($ret!=1)
					     {
						  $ErrorCode=" Your Data cannot be verified against the Signature. "." ErrorCode :[09]";
						  return "09";
					      }
					    }
					}
					 if($ret==1)
					 {

				        $ErrorCode=" Your signature has been verified successfully. "." ErrorCode :[00]";
				        return "00";
				 	 }
					return $ErrorCode;
				}
				function verifySign_fpx($sign,$toSign)
				{
				   error_reporting(0);
					 return validateCertificate('/home/iconcep1/vivalife.com.my/estore/test/cert/',$sign, $toSign);
				}

				function checkCertExpiry($path)
				{
						global  $ErrorCode;

				     $stack = array();
				    $t_ime= time();
				    $curr_date=date("Ymd",$t_ime);
				     for($x=0;$x<2;$x++)
					 {
						   error_reporting(0);
				          $key_id = file_get_contents($path[$x]);
					       if($key_id==null)
					       {
							   $cert_exists++;
					      	 continue;
					       }
					       $certinfo = openssl_x509_parse($key_id);
				           $s= $certinfo['validTo_time_t'];
				           $crtexpirydate=date("Ymd",$s-86400);
				    	  if($crtexpirydate > $curr_date)
					       {
							    if ($x > 0)
								{
								 if(certRollOver($path[$x], $path[$x-1])=="true")
									 {  array_push($stack,$key_id);
										return $stack;
				                      }
								}
				                array_push($stack,$key_id);
					      	  return $stack;
				           }
					       elseif($crtexpirydate == $curr_date)
					       {
							     if ($x > 0 && (file_exists($path[$x-1])!=1))
								 {
				                       if(certRollOver($path[$x], $path[$x-1])=="true")
									   {  array_push($stack,$key_id);
										  return $stack;
									 }
								 }
								 else if(file_exists($path[$x+1])!=1)
								 {
				       			 array_push($stack,file_get_contents($path[$x]),$key_id);
				                         return $stack;
								 }
					      	    array_push($stack,file_get_contents($path[$x+1]),$key_id);
					      		return $stack;
					      	}
					 }
				          if ($cert_exists == 2)
				                $ErrorCode="Invalid Certificates.  " . " ErrorCode : [06]";  //No Certificate (or) All Certificate are Expired
				            else if ($stack.Count == 0 && $cert_exists == 1)
				                $ErrorCode="One Certificate Found and Expired " . "ErrorCode : [07]";
				            else if ($stack.Count == 0 && $cert_exists == 0)
				               $ErrorCode="Both Certificates Expired " . "ErrorCode : [08]";
				            return $stack;
				}
				function certRollOver($old_crt,$new_crt)
				{
				        if (file_exists($new_crt)==1)
				        {
				                rename($new_crt,$new_crt."_".date("YmdHis", time()));//FPXOLD.cer to FPX_CURRENT.cer_<CURRENT TIMESTAMP>
				        }
						if ((file_exists($new_crt)!=1) && (file_exists($old_crt)==1))
				        {
				            rename($old_crt,$new_crt);                                 //FPX.cer to FPX_CURRENT.cer
				        }
						return "true";
				}
				// echo '<pre>';
				// print_r($orders);die;
				$count = 1;
				foreach($orders as $order_info) {

					$total_amount = number_format($this->currency->format($order_info['total'], $order_info['currency_code'], false, false),2,'.', '');
					$fpx_sellerExOrderNo_query 	= $order_info['fpx_sellerExOrderNo'];
					$fpx_sellerTxnTime_query 		= $order_info['fpx_sellerTxnTime'];
					$fpx_sellerOrderNo_query 		= $order_info['fpx_sellerOrderNo'];
					$fpx_buyerBankId_query 			= $order_info['fpx_buyerBankId'];
					$fpx_productDesc_query 			= $order_info['fpx_productDesc'];


				// new =================================


				$fpx_msgType="AE";
				$fpx_msgToken="01";
				$fpx_sellerExId=$exchangeID;
				$fpx_sellerExOrderNo=$fpx_sellerExOrderNo_query;
				$fpx_sellerTxnTime=$fpx_sellerTxnTime_query;
				$fpx_sellerOrderNo=$fpx_sellerOrderNo_query;
				$fpx_sellerId=$sellerID;
				$fpx_sellerBankCode="01";
				$fpx_txnCurrency="MYR";
				$fpx_txnAmount=$total_amount;
				$fpx_buyerEmail="";
				$fpx_checkSum="";
				$fpx_buyerName="";
				$fpx_buyerBankId=$fpx_buyerBankId_query;
				$fpx_buyerBankBranch="";
				$fpx_buyerAccNo="";
				$fpx_buyerId="";
				$fpx_makerName="";
				$fpx_buyerIban="";
				$fpx_productDesc=$fpx_productDesc_query;
				$fpx_version="7.0";


				/* Generating signing String */
				$data=$fpx_buyerAccNo."|".$fpx_buyerBankBranch."|".$fpx_buyerBankId."|".$fpx_buyerEmail."|".$fpx_buyerIban."|".$fpx_buyerId."|".$fpx_buyerName."|".$fpx_makerName."|".$fpx_msgToken."|".$fpx_msgType."|".$fpx_productDesc."|".$fpx_sellerBankCode."|".$fpx_sellerExId."|".$fpx_sellerExOrderNo."|".$fpx_sellerId."|".$fpx_sellerOrderNo."|".$fpx_sellerTxnTime."|".$fpx_txnAmount."|".$fpx_txnCurrency."|".$fpx_version;

				/* Reading key */
				$priv_key = file_get_contents('/home/iconcep1/vivalife.com.my/estore/test/cert/EX00011689.key');
				$pkeyid = openssl_get_privatekey($priv_key);
				openssl_sign($data, $binary_signature, $pkeyid, OPENSSL_ALGO_SHA1);
				$fpx_checkSum = strtoupper(bin2hex( $binary_signature ) );

				//extract data from the post
				extract($_POST);
				$fields_string="";

				//set POST variables
				$url ='https://uat.mepsfpx.com.my/FPXMain/sellerNVPTxnStatus.jsp';

				$fields = array(
										'fpx_msgType' => urlencode($fpx_msgType),
										'fpx_msgToken' => urlencode($fpx_msgToken),
										'fpx_sellerExId' => urlencode($fpx_sellerExId),
										'fpx_sellerExOrderNo' => urlencode($fpx_sellerExOrderNo),
										'fpx_sellerTxnTime' => urlencode($fpx_sellerTxnTime),
										'fpx_sellerOrderNo' => urlencode($fpx_sellerOrderNo),
										'fpx_sellerId' => urlencode($fpx_sellerId),
										'fpx_sellerBankCode' => urlencode($fpx_sellerBankCode),
										'fpx_txnCurrency' => urlencode($fpx_txnCurrency),
										'fpx_txnAmount' => urlencode($fpx_txnAmount),
										'fpx_buyerEmail' => urlencode($fpx_buyerEmail),
										'fpx_checkSum' => urlencode($fpx_checkSum),
										'fpx_buyerName' => urlencode($fpx_buyerName),
										'fpx_buyerBankId' => urlencode($fpx_buyerBankId),
										'fpx_buyerBankBranch' => urlencode($fpx_buyerBankBranch),
										'fpx_buyerAccNo' => urlencode($fpx_buyerAccNo),
										'fpx_buyerId' => urlencode($fpx_buyerId),
										'fpx_makerName' => urlencode($fpx_makerName),
										'fpx_buyerIban' => urlencode($fpx_buyerIban),
										'fpx_productDesc' => urlencode($fpx_productDesc),
										'fpx_version' => urlencode($fpx_version)
								);
				$response_value=array();

				try{
				//url-ify the data for the POST
				foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
				rtrim($fields_string, '&');

				//open connection
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

				//set the url, number of POST vars, POST data
				curl_setopt($ch,CURLOPT_URL, $url);

				curl_setopt($ch,CURLOPT_POST, count($fields));
				curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

				// receive server response ...
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				//execute post
				$result = curl_exec($ch);
				//echo "RESULT";
				//echo $result;

				//close connection
				curl_close($ch);

				$token = strtok($result, "&");
				while ($token !== false)
				{
					list($key1,$value1)=explode("=", $token);
					$value1=urldecode($value1);
					$response_value[$key1]=$value1;
					$token = strtok("&");
				}

				$fpx_debitAuthCode=reset($response_value);
				//Response Checksum Calculation String
				$data=$response_value['fpx_buyerBankBranch']."|".$response_value['fpx_buyerBankId']."|".$response_value['fpx_buyerIban']."|".$response_value['fpx_buyerId']."|".$response_value['fpx_buyerName']."|".$response_value['fpx_creditAuthCode']."|".$response_value['fpx_creditAuthNo']."|".$fpx_debitAuthCode."|".$response_value['fpx_debitAuthNo']."|".$response_value['fpx_fpxTxnId']."|".$response_value['fpx_fpxTxnTime']."|".$response_value['fpx_makerName']."|".$response_value['fpx_msgToken']."|".$response_value['fpx_msgType']."|".$response_value['fpx_sellerExId']."|".$response_value['fpx_sellerExOrderNo']."|".$response_value['fpx_sellerId']."|".$response_value['fpx_sellerOrderNo']."|".$response_value['fpx_sellerTxnTime']."|".$response_value['fpx_txnAmount']."|".$response_value['fpx_txnCurrency'];

				$val=verifySign_fpx($response_value['fpx_checkSum'], $data);

				// val == 00 verification success
				}
				catch(Exception $e){
					echo 'Error :', ($e->getMessage());
				}
				if ($fpx_debitAuthCode == '00' && $fpx_debitAuthCode == '00') {
					//echo $fpx_debitAuthCode .' | '. $fpx_debitAuthCode;
					// update status to 15 if successfully
					$this->model_checkout_order->update_fpx_order_success($order_info['order_id']);
				}


				// update ae_status
				$this->model_checkout_order->update_fpx_ae_status($order_info['order_id']);

				$count++;

			} // end foreach

			echo 'Success';

		}

}
