<?php

# Required File Includes
include("../../../dbconnect.php");
include("../../../includes/functions.php");
include("../../../includes/gatewayfunctions.php");
include("../../../includes/invoicefunctions.php");

$gatewaymodule = "coinpayments"; # Enter your gateway module name here replacing template
$GATEWAY = getGatewayVariables($gatewaymodule);
if (!$GATEWAY["type"]) die("Module Not Activated"); # Checks gateway module is active before accepting callback

function coinpayments_error($msg) {
	global $GATEWAY;
	
	if (!empty($GATEWAY['coinpayments_email'])) {
		$report = "AUTH User: ".$_SERVER['PHP_AUTH_USER']."\n";
		$report .= "AUTH Pass: ".$_SERVER['PHP_AUTH_PW']."\n\n";
				
		if ($msg) {
			$report .= "Error Message: ".$msg."\n\n";
		}
			
		$report .= "POST Fields\n\n";
		foreach ($_POST as $key => $value) {
			$report .= $key . '=' . $value. "\n";
		}
			
		mail($GATEWAY['coinpayments_email'], "CoinPayments.net Invalid IPN", $report);
	}
	die($msg);
}

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != $GATEWAY['coinpayments_merchant'] || $_SERVER['PHP_AUTH_PW'] != $GATEWAY['coinpayments_ipn_secret']) {
	coinpayments_error("Invalid AUTH merchant ID/IPN secret!");
}	

# Get Returned Variables - Adjust for Post Variable Names from your Gateway's Documentation
$ipn_type = $_POST["ipn_type"];
$merchant = $_POST["merchant"];
$status = $_POST["status"];
$status_text = $_POST["status_text"];
$invoiceid = $_POST["invoice"];
$transid = $_POST["txn_id"];
$amount1 = $_POST["amount1"];
$amount2 = $_POST["amount2"];
$currency1 = $_POST["currency1"];
$currency2 = $_POST["currency2"];
	
if ($ipn_type != "button") {
	coinpayments_error("ipn_type != button");
}
if ($merchant != $GATEWAY['coinpayments_merchant']) {
	coinpayments_error("Invalid merchant ID!");
}
if ($amount1 <= 0) {
	coinpayments_error("Amount must be > 0!");
}

$invoiceid = checkCbInvoiceID($invoiceid,$GATEWAY["name"]); # Checks invoice ID is a valid invoice number or ends processing

checkCbTransID($transid); # Checks transaction number isn't already in the database and ends processing if it does

if ($status >= 100 || $status == 2) {
	addInvoicePayment($invoiceid,$transid,$amount1,0.00,$gatewaymodule); # Apply Payment to Invoice: invoiceid, transactionid, amount paid, fees, modulename
	logTransaction($GATEWAY["name"],$_POST,$status_text.' (Original currency: '.$currency1.', make sure it matches your WHMCS currency!)'); # Save to Gateway Log: name, data array, status
} else if ($status >= 0) {
	logTransaction($GATEWAY["name"],$_POST,'Pending: '.$status_text);
} else {
	logTransaction($GATEWAY["name"],$_POST,'Error: '.$status_text);
	coinpayments_error($status_text);
}

?>