<?php
	error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
	$callback_test_mode = true; // for live mode kindly make it false
	if($callback_test_mode)
	{ //Test mode enabled
	//Start - Test parameters
		$input_values='test_mode=0&product_id=13&product=Testshop&marker=&payment_type=INVOICE_CREDIT&tid=12381300001406485&currency=EUR&amount=7300&status=100&subs_billing=&tariff_id=582&status_message=erfolgreich&paid_until=&signup_tid=&signup_date=&signup_time=&login=&password=&firstname=xxx&lastname=xxx&street=xxx&house_no=10&zip=12345&city=xxx&email=xxx@xxx.com&birthday=&country=Deutschland&country_code=DE&tid_payment=12381300001406485&reference=&vendor_id=4';
		$t = explode('&', $input_values);
		foreach($t as $index => $value){
			$t2 = explode('=', $value);
			$_POST[$t2[0]] = $t2[1];
		} 
		}
	//End - Test Parameters
	foreach($_POST as $_k => $_v) {
		if(is_string($_v) && strlen(trim($_v))) {
			$_POST[trim($_k)] = remove_string(trim($_v));
		}
	}
	//Callback Settings	
	$ipAllowed = '195.143.189.210'; // Novalnet IP, is a fixed value
	$callerIp  = getRealIpAddr(); //Current IP address
	//Debug Mode
	$debug = true;
	//Database Settings
	$db_host = 'localhost';
	$db_username = 'root';
	$db_password = '';
	$db_name = 'ubercart3';
	// - Table names - 
	$novalnet_tb = 'uc_novalnet';
	$order_tb = 'uc_orders';
	$payment_receipt_tb = 'uc_payment_receipts';
	$ordercomments_tb = 'uc_order_comments';
	$log_tb = 'uc_order_log';
	// Vendor Details
	$vendor_id  = '4';
	$auth_code  = '';
	$product_id = '';
	$tariff_id  = '';
	// Reporting email address
	$report_from = 'pb@novalnet-solutions.com';
	$report_to   = 'pb@novalnet-solutions.com';
	$report_sub  = 'Vendor Script access report';
	$report_body = '';	
	// Debug Mode
	$debug = true;
	if($callerIp != $ipAllowed ) {
		$report_body  = 'Unauthorised access from the IP [' . $callerIp . ']' . "\n\n";
		$report_body .= 'Request Params: ' . print_r($_POST, true);
		sendMail($report_from, $report_to, $report_sub, $report_body);
		if($debug) {
			echo $report_body;
		}
		exit();
	}
	if($_POST['tid_payment'] == NULL || $_POST['tid'] == NULL || $_POST['vendor_id'] != $vendor_id ) {
		$report_body  = 'Incomplete request from Novalnet AG' . "\n\n";
		$report_body .= 'Request Params: ' . print_r($_POST, true);
		sendMail($report_from, $report_to, $report_sub, $report_body);
		if($debug) {
			echo $report_body;
		}
		exit();
	}
	if('INVOICE_CREDIT' != $_POST['payment_type']) {
		// Nothing to do
		exit();
	}
	if(100 != $_POST['status']) {
		$report_body  = 'The status codes [' . $_request['status'] . '] is not valid' . "\n\n";
		$report_body .= 'Request Params: ' . print_r($_POST, true);
		sendMail($report_from, $report_to, $report_sub, $report_body);
		if($debug) {
			echo $report_body;
		}
		exit();
	}
	$db_obj = mysql_connect($db_host, $db_username, $db_password);
	if(!$db_obj) {
		$report_body  = mysql_errno() . ': ' . mysql_error() . "\n\n";
		$report_body .= 'Request Params: ' . print_r($_POST, true);
		sendMail($report_from, $report_to, $report_sub, $report_body);
		if($debug) {
			echo $report_body;
		}
		exit();
	}
	if(!mysql_select_db($db_name, $db_obj)) {
		$report_body  = mysql_errno() . ': ' . mysql_error() . "\n\n";
		$report_body .= 'Request Params: ' . print_r($_POST, true);
		sendMail($report_from, $report_to, $report_sub, $report_body);
		if($debug) {
			echo $report_body;
		}
		exit();
	}

	$status = $_POST['status'];
	$payment_type = $_POST['payment_type'];
	$tid = $_POST['tid_payment'];
	$amount = sprintf('%0.2f', intval($_POST['amount'])/100);
	
	$tid_payment = $_POST['tid'];
	$currency = $_POST['currency'];
	if($status==100) {
		$result = mysql_query("SELECT order_id FROM ".$novalnet_tb." WHERE tid=".$tid);
		if(!$result) {
			$report_body  = 'The Order Id not found in DB' . "\n\n";
				  $report_body .= 'Request TID: ' . $tid . '\n\n';
				  $report_body .= 'Request Params: ' . print_r($_POST, true);
				  sendMail($report_from, $report_to, $report_sub, $report_body);
				  if($debug) {
					echo $report_body;
				  }
				  exit();
		}
		$order_info = mysql_fetch_array($result);
		$order_id = $order_info['order_id'];
		$amount_set = mysql_query('SELECT order_total FROM '.$order_tb.' WHERE order_id='.$order_id );
		$orderamount = mysql_fetch_array($amount_set);
		$famount = $orderamount['order_total'];
		echo $amount;
		echo "<br>".$famount;
		if($amount != trim($famount) ) {
			$report_body  = 'The order amount[' . $orderamount['order_total'] . '] is not matched with the request amount[' . $famount . ']' . "\n\n";
			$report_body .= 'Request Params: ' . print_r($_POST, true);
			sendMail($report_from, $report_to, $report_sub, $report_body);
			if($debug) {
				echo $report_body;
			}
			exit();
		}
		//balance check
		orderbalancecheck($_POST, $order_id, $report_from, $report_to, $report_sub, $debug, $order_tb, $payment_receipt_tb);
		//Comment from Novalnet AG	
		$currenttime = time();
		$comment = $amount.' '.$currency.' Received by Novalnet AG';
		$insert_set = mysql_query("INSERT INTO ".$payment_receipt_tb." (order_id, method, amount, uid, data, comment, received) VALUES (".$order_id.",'". $payment_type."',". $famount.", 0, '','". $comment."',". $currenttime.")");
		$status_change = mysql_query("update ".$order_tb." set order_status='payment_received' where order_id=".$order_id);
		$comments_update = mysql_query("insert into ".$ordercomments_tb."(order_id, order_status, notified, message, created) values (".$order_id.",'payment_received',0,'".$comment."',".$currenttime.")");
		$log_entry = mysql_query("insert into ".$log_tb."(order_id, changes, created) values(".$order_id.",'".$comment."',".$currenttime.")");
		$report_body  = 'The order\'s status [ID: ' . $order_id . '] is updated' . "\n\n";
		$report_body .= 'Request Params: ' . print_r($_POST, true);
		sendMail($report_from, $report_to, $report_sub, $report_body);			
		if($debug) {
			echo $report_body;
		}
		exit();
	}	
	
	function sendMail($fromAd, $toAd, $subTt, $bodyTt) {
		$header  = 'From: ' . $fromAd . "\r\n";
		$header .= 'Reply-To: ' . $fromAd;
		return mail($toAd, $subTt, $bodyTt, $header);
	}
	
	// Function to remove unwanted string
	function remove_string($string) {
		$toReplaced  = array("'", '"', '^', '`');
		$replacement = array('',  '',  '',  '');
		$string      = str_replace($toReplaced, $replacement, $string);
		return $string;
	}
	
	function getRealIpAddr() {
		if(isPublicIP($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
		if($iplist=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
			if(isPublicIP($iplist[0])) return $iplist[0];
		}
		if (isPublicIP($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
		if (isPublicIP($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
		if (isPublicIP($_SERVER['HTTP_FORWARDED_FOR']) ) return $_SERVER['HTTP_FORWARDED_FOR'];
		return $_SERVER['REMOTE_ADDR'];
	}
	
	function isPublicIP($value) {
		if(!$value || count(explode('.',$value))!=4) return false;
		return !preg_match('~^((0|10|172\.16|192\.168|169\.254|255|127\.0)\.)~', $value);
	}
	
	function orderbalancecheck($post, $orderid,$report_from, $report_to, $report_sub, $debug, $order_tb, $payment_receipt_tb ) {	
		$balance_set = mysql_query('select order_total from '.$order_tb.' where order_id='.$orderid );
		$totalbalance = mysql_fetch_array($balance_set);
		$paidamount_set = mysql_query('select sum(amount) as paid from '.$payment_receipt_tb.' where order_id='.$orderid);
		$paidamount = mysql_fetch_array($paidamount_set);
		if(($totalbalance['order_total'] - $paidamount['paid']) > 0) {
			return TRUE;
		} else {
			$report_body  = 'Already Payment received and status updated for Order [ ID : ' . $orderid . "]\n\n";
			$report_body .= 'Request Params: ' . print_r($post, true);
			sendMail($report_from, $report_to, $report_sub, $report_body);
			if($debug) {
				echo $report_body;
			}
			exit();
		}
	}
?>
