<?php
// tell PHP to log errors to ipn_errors.log in this directory

$sql_host = '';
$sql_user = '';
$sql_pass = '';
$sql_db = '';

$donate_email = 'seller@paypalsandbox.com';
$donate_amt = '12.34';

ini_set('log_errors', true);
ini_set('error_log', dirname(__FILE__).'/ipn_errors.log');

// intantiate the IPN listener
include('ipnlistener.php');
$listener = new IpnListener();

// tell the IPN listener to use the PayPal test sandbox
$listener->use_sandbox = true;

// try to process the IPN POST
try {
    $listener->requirePostMethod();
    $verified = $listener->processIpn();
} catch (Exception $e) {
    error_log($e->getMessage());
    exit(0);
}

if($verified) {
	
	$errmsg = '';

	//make sure payment status is completed
	if ($_POST['payment_status'] != 'Completed') {
		//ignore it
		exit(0);
	}

	//make sure seller email is ours
	if ($_POST['receiver_email'] != $donate_email) {
		$errmsg .= "'receiver_email' does not match: ";
		$errmsg .= $_POST['receiver_email']."\n";
	}

	//make sure amount paid matches
	if ($_POST['mc_gross'] != $donate_amt) {
		$errmsg .= "'mc_gross' does not match: ";
		$errmsg .= $_POST['mc_gross']."\n";
	}

	//make sure currency code matches
	if ($_POST['mc_currency'] != 'USD') {
		$errmsg .= "'mc_currency' does not match: ";
		$errmsg .= $_POST['mc_currency']."\n";
	}

	//ensure transaction isn't a dupe
	mysql_connect($sql_host, $sql_user, $sql_pass) or exit(0);
	mysql_select_db($sql_db);

	$txn_id = mysql_real_escape_string($_POST['txn_id']);
	$sql = "SELECT COUNT(*) FROM orders WHERE txn_id = '$txn_id'"
	$r = mysql_query($sql);

	if(!$r) {
		error_log(mysql_error());
		exit(0);
	}

	$exists = mysql_result($r, 0);
	mysql_free_result($r);

	if($exists) {
		$errmsg .= "'txn_id' has already been processed: ".$_POST['txn_id']."\n";
	}

	error_log('Valid');

	if(!empty($errmsg)) {
		//manually investigate errors from fraud checking
		$body = "IPN failed fraud checks: \n$errmsg\n\n";
		$body .= $listener->getTextReport();
		error_log($body);		
	} else {
		//add order to table
		$payer_email = mysql_real_escape_string($_POST['payer_email']);
		$mc_gross = mysql_real_escape_string($_POST['mc_gross']);
		$sql = "INSERT INTO orders VALUES
				(NULL, '$txn_id', '$payer_email', $mc_gross)";

		if (!mysql_query($sql)) {
			error_log(mysql_error());
			exit(0);
		}

		// send user confirmation email
		$to = filter_var($_POST['payer_email'], FILTER_SANITIZE_EMAIL);
		$subject = "Thanks for the donation!";
		mail($to, $subject, 'Thank you for donating, you should see your rank change next time you join the server.')
	}

} else {
	//manually investigate invalid ipn
	error_log('Invalid');
	error_log($listener->getTextReport());
}

?>