<?php

include("../../../dbconnect.php");
include("../../../includes/functions.php");
include("../../../includes/gatewayfunctions.php");
include("../../../includes/invoicefunctions.php");

$gatewaymodule = "perfectmoney";
$GATEWAY = getGatewayVariables($gatewaymodule);
if (!$GATEWAY["type"]) die("Module Not Activated"); 


$invoiceid = $_POST["PAYMENT_ID"];
$transid = $_POST["PAYMENT_BATCH_NUM"];
$amount = $_POST['PAYMENT_AMOUNT'];
$invoiceid = checkCbInvoiceID($invoiceid,$GATEWAY["name"]);
$perfectmoney_pass=$GATEWAY["perfectmoney_pass"];

checkCbTransID($transid);

define('ALTERNATE_PHRASE_HASH',strtoupper(md5($perfectmoney_pass)));

$string=
      $_POST['PAYMENT_ID'].':'.$_POST['PAYEE_ACCOUNT'].':'.
      $_POST['PAYMENT_AMOUNT'].':'.$_POST['PAYMENT_UNITS'].':'.
      $_POST['PAYMENT_BATCH_NUM'].':'.
      $_POST['PAYER_ACCOUNT'].':'.ALTERNATE_PHRASE_HASH.':'.
      $_POST['TIMESTAMPGMT'];


$hash=strtoupper(md5($string));

function processPOST($hash, $amount, $payee){

		$_POST['whmcs_hash_compare']='CAME: '.$_POST['V2_HASH'].'; WE HAVE: '.$hash;
		$_POST['whmcs_amount_compare']='CAME: '.$_POST['PAYMENT_AMOUNT'].'; WE HAVE: '.$amount;
		$_POST['whmcs_payee_compare']='CAME: '.$_POST['PAYEE_ACCOUNT'].'; WE HAVE: '.$payee;

}

if($hash==$_POST['V2_HASH']){
		
	// proccessing payment if only hash is valid

   /* In section below you must implement comparing of data you recieved
   with data you sent. This means to check if $_POST['PAYMENT_AMOUNT'] is
   particular amount you billed to client and so on. */

	$qry=mysql_query("select * from tblorders where invoiceid='$_POST[PAYMENT_ID]' "); 
	$data=mysql_fetch_array($qry);
	
	
	if($_POST['PAYMENT_AMOUNT']==$data['amount'] && $_POST['PAYEE_ACCOUNT']==$GATEWAY['perfectmoney_id']){

		addInvoicePayment($invoiceid,$transid,$amount,$fee,$gatewaymodule); # Apply Payment to Invoice: invoiceid, transactionid, amount paid, fees, modulename
		processPOST($hash, $data['amount'], $GATEWAY['perfectmoney_id']);
		logTransaction($GATEWAY["name"],$_POST,"Successful"); # Save to Gateway Log: name, data array, status

   }else{ // you can also save invalid payments for debug purposes

		 processPOST($hash, $data['amount'], $GATEWAY['perfectmoney_id']);
     logTransaction($GATEWAY["name"],$_POST,"Fake Data");

   }

}else{
		
	processPOST($hash, 'not defined', $GATEWAY['perfectmoney_id']);
	logTransaction($GATEWAY["name"],$_POST,"Unsuccessful"); # Save to Gateway Log: name, data array, status

}
?>