<?php
/***************************************************************************
*                                                                          *
* Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
*                                                                          *
* This  is  commercial  software,  only  users  who have purchased a valid *
* license  and  accept  to the terms of the  License Agreement can install *
* and use this program.                                                    *
*                                                                          *
****************************************************************************
* PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
* "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
****************************************************************************/
 //
 //$Id: PaytmModel.php, v 1.0 2011/06/14 20:52:11
 
//
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");

class PaytmNetBankingModel extends PaymentModel{ 
//Function to Process to orders		
	public function process($order='',$orderItems='',$type='',$paramList=array()) 
	{
			parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);	
			require_once("Paytm/config_paytm.php");
			require_once("Paytm/encdec_paytm.php");
			$isValidChecksum = "FALSE";
			if($type!='') {				
				$paytmChecksum = isset($paramList["CHECKSUMHASH"]) ? $paramList["CHECKSUMHASH"] : ""; //Sent by Paytm pg
				//echo "<pre>";print_r($paramList);exit;
				//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your application’s MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
				$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.				
				//echo $isValidChecksum;exit;
				if ($paramList["STATUS"] == "TXN_SUCCESS") {
					$isValidChecksum = "TRUE";
				}
				if($isValidChecksum == "TRUE") {
					//echo "<b>Checksum matched and following are the transaction details:</b>" . "<br/>";
                                        $failure  = 0;
					if ($paramList["STATUS"] == "TXN_SUCCESS") {
                                                $failure  = 1;
						//echo "<b>Transaction status is success</b>" . "<br/>";
						//Process your transaction here as success transaction.
						//Verify amount & order id received from Payment gateway with your application's order id and amount.
						$ORDER_ID = $order['tempOrderID'];
                                                $requestParamList = array("MID" => PAYTM_MERCHANT_MID , "ORDERID" => $ORDER_ID);  		
                                                $StatusCheckSum = getChecksumFromArray($requestParamList,PAYTM_MERCHANT_KEY);
                                                $requestParamList['CHECKSUMHASH'] = $StatusCheckSum;
                                                // Call the PG's getTxnStatusNew() function for verifying the transaction status.
                                                $responseParamList = getTxnStatusNew($requestParamList); 
                                                if ($responseParamList['STATUS'] == 'TXN_SUCCESS') {
                                                    $paymentMethodName			=	$this->settingsVars["payment_method_name"];
                                                    parent::createTransaction($order,  $paramList['TXNID'],$paramList, "", $order['authValue'],
                                                    0,$paymentMethodName,$supportedCurrencyID,$order['orderTotalAmount']);
                                                    $this->isError = false;
                                                    $this->errorMessage = "";
                                                    return "Pending";
                                                } else {
                                                    $failure  = 0;
                                                }
                                                
					}                                        
					if($failure<=0) {
                                                $paymentMethodName			=	$this->settingsVars["payment_method_name"];
						parent::createTransactionError($order,  $paramList['TXNID'],$paramList, "", $order['authValue'],
						0,$paymentMethodName);
						//echo "<b>Transaction status is failure</b>" . "<br/>";
						$this->isError = true;
						$this->errorMessage = $paramList["RESPMSG"];
					}

				}
				else {
					//echo "<b>Checksum mismatched.</b>";
					//Process transaction as suspicious.
                                        $paymentMethodName			=	$this->settingsVars["payment_method_name"];
						parent::createTransactionError($order,  $paramList['TXNID'],$paramList, "Checksum mismatched.", $order['authValue'],
						0,$paymentMethodName);
					$this->isError = true;
					$this->errorMessage = "Checksum mismatched. Please try later...";
				}		
				return !$this->isError;
			}
			$ObjCurrency		= 	new CurrencyModel();			
			$payAmount			=	$order['orderTotalAmount'];
			$taxAmount			=	$order["orderTaxAmount"];
			$shippingAmount		=	$order["shippingAmount"];
			$serviceCharge   	= 	$order["orderOtherServiceCharge"];
			$orderPromoDiscountAmount 	= $order["orderPromoDiscountAmount"];
			$orderUserCreditAmount 		= $order["orderUserCreditAmount"];
			$supportedCurrencyID		= $order["purchasedCurrency"];
			$paymentCurrency			= $this->settingsVars["payment_currency"];
			
			$currencyArr	=	'';
			$itemsArray  	= '';
			$itemCounter	=	1;
			
			if ($paymentCurrency != '')
        	{
            	$paymentCurrency = str_replace(", ", ",", $paymentCurrency);
            	$currencyArr     = explode(",", $paymentCurrency);
        	}
			if(count($currencyArr)<1)
			{
				$this->isError 		= true;
				$this->errorMessage	= "Currency not configured , Please contact the site admin";
				return false;
			}
			else
			{
				$currencyFlag = false;
				$purchasedCurrencyDetails 	= $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
				$currencyCode				= $purchasedCurrencyDetails['currencyCode'];
				$systemCurrencies 			=	$ObjCurrency->listCurrencyCodes();
				if(!in_array($purchasedCurrencyDetails['currencyCode'],$currencyArr))
				{
					foreach ($systemCurrencies as $key => $currency)
        			{
						if(in_array($currency['currencyCode'],$currencyArr))
						{
							$currencyFlag = true;
							$supportedCurrencyCode 	= $currency['currencyCode'];	
							$supportedCurrencyID 	= $currency['currencyID'];
							break;
						}
					}
					if($currencyFlag==true)
					{
						$payAmount = $ObjCurrency->convertValueCustom($payAmount,$order["purchasedCurrency"],$supportedCurrencyID);
						$taxAmount = $ObjCurrency->convertValueCustom($taxAmount,$order["purchasedCurrency"],$supportedCurrencyID);
						$shippingAmount = $ObjCurrency->convertValueCustom($shippingAmount,$order["purchasedCurrency"],
						$supportedCurrencyID);
						$serviceCharge = $ObjCurrency->convertValueCustom($serviceCharge,$order["purchasedCurrency"],
						$supportedCurrencyID);
						$orderPromoDiscountAmount = $ObjCurrency->convertValueCustom($orderPromoDiscountAmount
						,$order["purchasedCurrency"],$supportedCurrencyID);
						$orderUserCreditAmount = $ObjCurrency->convertValueCustom($orderUserCreditAmount
						,$order["purchasedCurrency"],$supportedCurrencyID);
						$currencyCode		=	$supportedCurrencyCode;
					}
					else
					{
						$this->isError 		= true;
						$this->errorMessage	= "Currency not configured , Please contact the site admin";
						return false;
					}
					
				}
			}
			
			$checkSum 	= "";
			$paramList 	= array();
			$genCode        = $this->getRandomCode(2,'Numeric');
			$orderID 	= $order['masterOrderID']."@".$genCode;
			$custID 	= $order['masterOrderID'].$order["userID"];
			$industry   = $this->settingsVars["paytm_industry_type_id"];
			$channelID  = $this->settingsVars["paytm_channel_id"];
			$txnAmount  = number_format($payAmount,2);
			$txnAmount  = str_replace(",","",$txnAmount);
                        
                        //update order id
                        parent::updateTempOrderID($orderID,$order['masterOrderID']);

			// Create an array having all required parameters for creating checksum.
			$paramList["MID"] 		 = PAYTM_MERCHANT_MID;
			$paramList["ORDER_ID"] 	 = $orderID;
			$paramList["CUST_ID"] 	 = $custID;
			$paramList["INDUSTRY_TYPE_ID"] = $industry;
			$paramList["CHANNEL_ID"] = $channelID;
			$paramList["TXN_AMOUNT"] = $txnAmount;
			$paramList["WEBSITE"] 	 = PAYTM_MERCHANT_WEBSITE;
			$paramList["MOBILE_NO"]	 = $order['billingAddress']['billingPhone'];
			$paramList["EMAIL"]	 	 = $order['billingAddress']['billingEmail'];
			//$paramList["ORDER_DETAILS"]	 	 = $order['orderDesc'];
			$paramList["CALLBACK_URL"]	 	 = $order['returnURL'];
			$paramList["AUTH_MODE"]	 	 	 = 'USRPWD';
			$paramList["PAYMENT_TYPE_ID"]	 = 'NB';
			$paramList["BANK_CODE"]	 	 	 = $order['bankCode'];
			//echo "<pre>";print_r($paramList);exit;
			//Here checksum string will return by getChecksumFromArray() function.
			$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
                       /* if($order['userID']=='17') {
                            $html =  '
<html>
<head>
<title>Merchant Check Out Page</title>
</head>
<body>
	<center><h1>Please do not refresh this page...</h1></center>
		<form method="post" action="'.PAYTM_TXN_URL.'" name="f1">
		<table border="1">
			<tbody>';
			foreach($paramList as $name => $value) {
			$html .= '<input type="hidden" name="' . $name .'" value="' . $value . '">';
			}
			$html .= '<input type="hidden" name="CHECKSUMHASH" value="'.$checkSum.'">';			
			$html .= '</tbody>
		</table>
		<script type="text/javascript">
			//document.f1.submit();
		</script>
	</form>
</body>
</html>';
		echo $html;exit;
                        }*/
			$html =  '
<html>
<head>
<title>Merchant Check Out Page</title>
</head>
<body>
	<center><h1>Please do not refresh this page...</h1></center>
		<form method="post" action="'.PAYTM_TXN_URL.'" name="f1">
		<table border="1">
			<tbody>';
			foreach($paramList as $name => $value) {
			$html .= '<input type="hidden" name="' . $name .'" value="' . $value . '">';
			}
			$html .= '<input type="hidden" name="CHECKSUMHASH" value="'.$checkSum.'">';			
			$html .= '</tbody>
		</table>
		<script type="text/javascript">
			document.f1.submit();
		</script>
	</form>
</body>
</html>';
		echo $html;exit;
			
	}
//End of function
        public function getTxnStatus($order='') {
            
                parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);	
                require_once("Paytm/config_paytm.php");
                require_once("Paytm/encdec_paytm.php");
            // In Test Page, we are taking parameters from POST request. In actual implementation these can be collected from session or DB. 
		$ORDER_ID = $order['tempOrderID'];
		// Create an array having all required parameters for status query.
		$requestParamList = array("MID" => PAYTM_MERCHANT_MID , "ORDERID" => $ORDER_ID);  
		
		$StatusCheckSum = getChecksumFromArray($requestParamList,PAYTM_MERCHANT_KEY);
		
		$requestParamList['CHECKSUMHASH'] = $StatusCheckSum;

		// Call the PG's getTxnStatusNew() function for verifying the transaction status.
		$responseParamList = getTxnStatusNew($requestParamList);
                
                return $responseParamList;
        }
	public function getRandomCode($length, $type) {
        if ($type == 'Alphanumerics')
            $characters = '23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        else
            $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string       = '';
        $stringLength = strlen($characters) - 1;
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, $stringLength)];
        }
        return $string;
    }
	public function processCustom($order='') {
			$ObjCurrency			= new CurrencyModel();
			parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
			$getPaymentTransactionDetails = parent::getPaymentTransactionDetails(0,
			$order["masterOrderID"]);
			$this->isError = false;
			//check is transaction completed
			if ($order["paymentType"] != "AUTH_ONLY" || $order["paymentStatus"]=='Received' )
			{
				$this->isError 		= true;
				$this->errorMessage = "Transaction already completed";
				return false;
			}
			//get captured total amount & x_trans_id
			$capturedTotalAmount = $getPaymentTransactionDetails['convertedPaymentAmount'];

			$payAmount				= $capturedTotalAmount;
			$transactionID			= $getPaymentTransactionDetails["transactionID"];
			$taxAmount				= (isset($order["finalTaxAmount"])?$order["finalTaxAmount"]:0);
			
	}
	//Function to Process curl
	public function processCurl($postData, $postUrl)
	{
		$c = curl_init($postUrl);
		curl_setopt($c, CURLOPT_VERBOSE, 0);
		curl_setopt($c, CURLOPT_HEADER, 0);
		curl_setopt($c, CURLOPT_POSTFIELDS, $postData);
		curl_setopt($c, CURLOPT_POST, 1);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 1);
		if (!ini_get('safe_mode')) set_time_limit(3000);
		$buffer = curl_exec($c);
		if (curl_errno($c) > 0)
		{
			$this->isError = true;
			$this->errorMessage = curl_error($c);
			return false;
		}
		return !$buffer ? false : $buffer;
	}
	//End of function	
	
	
	//Function to Process Refund
	public function processRefund($order='',$postValues='') 
	{
		parent::listPaymentSettingsValues($postValues['paymentSettingsGroupID']);
		$ObjRefund			=	new RefundModel();
		$ObjCurrency		= new CurrencyModel();
		$totalAmount		=	$order['orderTotalAmount'];
		
		$supportedCurrencyID = $order["purchasedCurrency"];
		$paymentCurrency	 = $this->settingsVars["payment_currency"];
		
		if ($paymentCurrency != '')
		{
			$paymentCurrency = str_replace(", ", ",", $paymentCurrency);
			$currencyArr     = explode(",", $paymentCurrency);
		}
		if(count($currencyArr)<1)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Currency not configured , Please contact the site admin";
			//return false;
		}
		else
		{
			$currencyFlag = false;
			$purchasedCurrencyDetails 	= $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
			$currencyCode				= $purchasedCurrencyDetails['currencyCode'];
			$systemCurrencies 			= $ObjCurrency->listCurrencyCodes();
			if(!in_array($purchasedCurrencyDetails['currencyCode'],$currencyArr))
			{
				foreach ($systemCurrencies as $key => $currency)
				{
					if(in_array($currency['currencyCode'],$currencyArr))
					{
						$currencyFlag = true;
						$supportedCurrencyCode 	= $currency['currencyCode'];	
						$supportedCurrencyID 	= $currency['currencyID'];
						break;
					}
				}
				if($currencyFlag==true)
				{
					$totalAmount = $ObjCurrency->convertValueCustom($totalAmount,$order["purchasedCurrency"],$supportedCurrencyID);
				}
				else
				{
					$this->isError 		= true;
					$this->errorMessage	= "Currency not configured , Please contact the site admin";
					//return false;
				}
			}
		}
		
		
	}
	//End of function
}
