<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Payment extends Site_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->load->library(array('encrypt', 'email'));
		$this->load->model("mod_payment","payment");
	}

	function VPC_PHP_3P_DO()
	{
	   $session_id = $this->session->userdata('lastreffnumber');
	   $session_price = $this->session->userdata('price');
	   $lastreffnumber = $this->encrypt->decode($session_id);
	   $price = $this->encrypt->decode($session_price);
	   
	   $_POST['vpc_Version'] = 1;
	   $_POST['vpc_Command'] = 'pay';
	   $_POST['vpc_AccessCode'] = '998446D6'; // '157307BF';
	   //  $_POST['vpc_MerchTxnRef'] = 1;
	   $_POST['vpc_Merchant'] = 'CUBCKH110'; //'SBC113';
	   $_POST['vpc_OrderInfo'] = 'VPC CHANNELLIMO.COM';
	   $_POST['vpc_Locale'] = 'en';
	   $_POST['virtualPaymentClientURL'] = 'https://migs.mastercard.com.au/vpcpay'; 
	   //$_POST['vpc_ReturnURL'] = 'http://mychannelpayment.com/onlinepayment/system/VPC_PHP_3P_DR';
	   $_POST['vpc_ReturnURL'] = site_url('payment/VPC_PHP_3P_DR');
	   /*$_POST['vpc_MerchTxnRef'] = $lastreffnumber;
		$amount = $_POST['txtamount'];*/
		$_POST['vpc_MerchTxnRef'] = $lastreffnumber;
		$amount = number_format($price, 2);
		$actaulamount0 = str_replace("$", "", $amount);
		$actaulamount = str_replace(",", "", $actaulamount0);
		$actaulamount1 = str_replace(".", "", $actaulamount);
	    $_POST['vpc_Amount'] = $actaulamount1;
		$this->load->view("payment/VPC_PHP_3P_DO");

	}	

	

	function VPC_PHP_3P_DR()
	{
		$this->responeURL();	
	}



	private function responeURL()
	{

		$SECURE_SECRET = "112B46771AA040C362AB8669AE4A6768";
		$vpc_Txn_Secure_Hash = $this->input->get('vpc_SecureHash', TRUE);
		//unset($_GET["vpc_SecureHash"]); 
		//unset($this->input->get('vpc_SecureHash', TRUE));
		// set a flag to indicate if hash has been validated
		$errorExists = false;
		if (strlen($SECURE_SECRET) > 0 && $this->input->get_post('vpc_TxnResponseCode', TRUE) != "7" && $this->input->get_post('vpc_TxnResponseCode', TRUE) != "No Value Returned") 
		{
			$md5HashData = $SECURE_SECRET;
			// sort all the incoming vpc response fields and leave out any with no value
			foreach($_GET as $key => $value) 
			{
				if ($key != "vpc_SecureHash" or strlen($value) > 0) 
				{
					$md5HashData .= $value;
				}
			}
			// Validate the Secure Hash (remember MD5 hashes are not case sensitive)
			// This is just one way of displaying the result of checking the hash.
			// In production, you would work out your own way of presenting the result.
			// The hash check is all about detecting if the data has changed in transit.

			if (strtoupper($vpc_Txn_Secure_Hash) == strtoupper(md5($md5HashData))) 
			{
				// Secure Hash validation succeeded, add a data field to be displayed
				// later.
				$hashValidated = "<FONT color='#00AA00'><strong>CORRECT</strong></FONT>";
			} else {
				// Secure Hash validation failed, add a data field to be displayed
				// later.
				$hashValidated = "<FONT color='#FF0066'><strong>INVALID HASH</strong></FONT>";
				$errorExists = true;
			}

		} else {
			// Secure Hash was not validated, add a data field to be displayed later.
			$hashValidated = "<FONT color='orange'><strong>Not Calculated - No 'SECURE_SECRET' present.</strong></FONT>";
		}

		// Define Variables
		// ----------------
		// Extract the available receipt fields from the VPC Response
		// If not present then let the value be equal to 'No Value Returned'
		// Standard Receipt Data 

		$amount          = $this->null2unknown($this->input->get('vpc_Amount', TRUE));
		$locale          = $this->null2unknown($this->input->get('vpc_Locale', TRUE));
		$command         = $this->null2unknown($this->input->get('vpc_Command', TRUE));
		$message         = $this->null2unknown($this->input->get('vpc_Message', TRUE));
		$version         = $this->null2unknown($this->input->get('vpc_Version', TRUE));
		$cardType        = $this->null2unknown($this->input->get('vpc_Card', TRUE));
		$orderInfo       = $this->null2unknown($this->input->get('vpc_OrderInfo', TRUE));
		$receiptNo       = $this->null2unknown($this->input->get('vpc_ReceiptNo', TRUE));
		$merchantID      = $this->null2unknown($this->input->get('vpc_Merchant', TRUE));
		$authorizeID     = $this->null2unknown($this->input->get('vpc_AuthorizeId', TRUE));
		$merchTxnRef     = $this->null2unknown($this->input->get('vpc_MerchTxnRef', TRUE));
		$transactionNo   = $this->null2unknown($this->input->get('vpc_TransactionNo', TRUE));
		$acqResponseCode = $this->null2unknown($this->input->get('vpc_AcqResponseCode', TRUE));
		$txnResponseCode = $this->null2unknown($this->input->get('vpc_TxnResponseCode', TRUE));

		// 3-D Secure Data 
		$verType         = array_key_exists("vpc_VerType", $_GET)      	   ? $this->input->get('vpc_VerType',TRUE) 				: "No Value Returned";
		$verStatus       = array_key_exists("vpc_VerStatus", $_GET)        ? $this->input->get('vpc_VerStatus',TRUE)        : "No Value Returned";
		$token           = array_key_exists("vpc_VerToken", $_GET)         ? $this->input->get('vpc_VerToken',TRUE)         : "No Value Returned";
		$verSecurLevel   = array_key_exists("vpc_VerSecurityLevel", $_GET) ? $this->input->get('vpc_VerSecurityLevel',TRUE) : "No Value Returned";
		$enrolled        = array_key_exists("vpc_3DSenrolled", $_GET)      ? $this->input->get('vpc_3DSenrolled', TRUE)      : "No Value Returned";
		$xid             = array_key_exists("vpc_3DSXID", $_GET)           ? $this->input->get('vpc_3DSXID', TRUE)           : "No Value Returned";
		$acqECI          = array_key_exists("vpc_3DSECI", $_GET)           ? $this->input->get('vpc_3DSECI', TRUE)           : "No Value Returned";
		$authStatus      = array_key_exists("vpc_3DSstatus", $_GET)        ? $this->input->get('vpc_3DSstatus', TRUE)        : "No Value Returned";

			

			// *******************

			// END OF MAIN PROGRAM

			// *******************

			

			// FINISH TRANSACTION - Process the VPC Response Data

			// =====================================================

			// For the purposes of demonstration, we simply display the Result fields on a

			// web page.

			

			// Show 'Error' in title if an error condition

			$errorTxt = "";

			

				//$reciepnumber = mysql_query("insert into tbl_online_payment_details set 	

//											pay_reftid = '$merchTxnRef', 

//											purchase_amount= '$amount', 

//											vpctrc ='$txnResponseCode',

//											trc_d = '$receiptNo', 

//											message= '$message',

//											trn_number= '$transactionNo' ,

//											a_r_c= '$acqResponseCode', 

//											

//											b_n= '$batchNo',

//											card_type= '$cardType',

//											auth_suc= '$authStatus' " );

			

			

			    // Show this page as an error page if vpc_TxnResponseCode equals '7'

				$session_id = $this->session->userdata('lastreffnumber');
				$session_price = $this->session->userdata('price');
				$amount = $this->encrypt->decode($session_price);
				$lastreffnumber = $this->encrypt->decode($session_id);
				$ip = $this->input->ip_address();

				if ($txnResponseCode == "7" || $txnResponseCode == "No Value Returned" || $errorExists) 
				{
					//error payment
					$errorTxt = "Error";
					$payment = array(
						'ip' =>$ip,
						'reserve_id' => $lastreffnumber,
						'pay_status' => 0,
						'pay_reftid' => $merchTxnRef,
						'amount' => $amount,
						'createdate' => date('y/m/d H:i:sa'),
					);
					$this->payment->add($payment);
					redirect("payment/uncomplete");	
					exit();

				}

				if($txnResponseCode == "0")	
				{
					//sucessfull payment
					$payment = array(
						'ip' =>$ip,
						'reserve_id' => $lastreffnumber,
						'pay_status' => 0,
						'pay_reftid' => $merchTxnRef,
						'amount' => $amount,
						'createdate' => date('y/m/d H:i:sa'),
					);

					$this->payment->add($payment);
					$post = array(
						'confirm' => 1,
					);

					$this->payment->payment_complete($post,$lastreffnumber);
					redirect("payment/complete");	
					exit();
				}
				else 
				{
					//unexpected error
				}
		$this->load->view("payment/VPC_PHP_3P_DR");	

	}

	

	function uncomplete()
	{
	    $session_id = $this->session->userdata('lastreffnumber');
	    $id = $this->encrypt->decode($session_id);
		$reservation = $this->payment->getById($id);

		if(!$reservation)
		{
			redirect("home");
		}

		$data['reservation'] = $reservation;
		$this->load->view('header');
		$this->load->view('payment/payment_uncomplete',$data);
		$this->load->view('footer');		
	} 

		

	function complete()
	{
	    $session_id = $this->session->userdata('lastreffnumber');
	    $id = $this->encrypt->decode($session_id);
		$payment = $this->payment->payComplete($id);
		if(!$payment)
		{
			$this->session->set_flashdata('message',"Sorry for Inconvenience. Please try again!");
			redirect("home");
		}
		
		$reservation = $this->payment->getById($id);
		if(!$reservation)
		{
			redirect("home");
		}

		$data['reservation'] = $reservation;
		$this->load->view('header');
		$this->load->view('payment/payment_complete',$data);
		$this->load->view('footer');	
	}

	private function null2unknown($data) 
	{
	    if ($data == "") 
		{
			return "No Value Returned";
		}else{
			return $data;
		}
	}

}