<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require('db_connect.php');
if(isset($_POST)){
	$response = $_POST;
	
	/* It is very important to calculate the hash using the returned value and compare it against the hash that was sent while payment request, to make sure the response is legitimate */
	$salt = SALT_KEY; /* put your salt provided by traknpay here */
	if(isset($salt) && !empty($salt)){
		$response['calculated_hash']=hashCalculate($salt, $response);
		$response['valid_hash'] = ($response['hash']==$response['calculated_hash'])?'Yes':'No';
	} else {
		$response['valid_hash']='Set your salt in return_page.php to do a hash check on receiving response from Traknpay';
	}
}

function hashCalculate($salt,$input){
	/* Remove hash key if it is present */
	unset($input['hash']);
	/*Sort the array before hashing*/
	ksort($input);
	
	/*first value of hash data will be salt*/
	$hash_data = $salt;
	
	/*Create a | (pipe) separated string of all the $input values which are available in $hash_columns*/
	foreach ($input as $key=>$value) {
		if (strlen($value) > 0) {
			$hash_data .= '|' . $value;
		}
	}

	$hash = null;
	if (strlen($hash_data) > 0) {
		$hash = strtoupper(hash("sha512", $hash_data));
	}
		
	return $hash;
}

$id= $response["udf1"];
$userid= $response["udf2"];
$refNO= $response["udf3"];
$transaction_id= $response["transaction_id"];
$payment_mode= $response["payment_mode"];
$payment_channel= $response["payment_channel"];
$payment_datetime= $response["payment_datetime"];
$response_message= $response["response_message"];

if($response_message=="Transaction successful" && $refNO!="")
{
    mysqli_query($conn,"UPDATE tbl_userregistration_ug2 SET transaction_id='$transaction_id',  payment_mode='$payment_mode', payment_channel='$payment_channel',payment_datetime='$payment_datetime',response_message='$response_message',status=1,payment_redirectid='' WHERE id='$id' AND userid='$userid'");
    mysqli_query($conn,"UPDATE tbl_admission_ug2 SET status=1 WHERE regid='$id' AND userid='$userid'");
    
}

$sql="select * from tbl_userregistration_ug2 where id='$id' AND userid='$userid'";
$results=mysqli_query($conn,$sql);
$record = mysqli_fetch_assoc($results);

if($response_message=="Transaction successful" && $refNO!="")
{
    //if($record["course"]=="IA"){
        $chkTable="ia_unique_ug2";
    //} elseif($record["course"]=="ICOM"){
    //    $chkTable="icm_unique_reg";
    //} elseif($record["course"]=="ISC"){
    //    $chkTable="isc_unique_reg";
   // }
    
    $chkUniqExists= mysqli_query($conn,"SELECT * FROM ".$chkTable." WHERE user_id='$userid'");
    if(mysqli_num_rows($chkUniqExists) > 0){
        
    } else {
        mysqli_query($conn,"INSERT INTO ".$chkTable." (user_id) values ('$userid')");
    }
}
?>