<?php

require_once('../../../../lib/config.inc.php');
$conf['start_session'] = false;
require_once('../../../../lib/app.inc.php');

if(count($_POST) == 0) die('Direct access not allowed!');

function libCurlPost($url,$data)  {

	//build post string
	foreach($data as $i=>$v) {
		$postdata.= $i . "=" . urlencode($v) . "&";
	}

	$postdata.="cmd=_notify-validate";

	$ch=curl_init();

	curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_POST,1);
	curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);

	//Start ob to prevent curl_exec from displaying stuff.
	ob_start();
	curl_exec($ch);

	//Get contents of output buffer
	$info=ob_get_contents();
	curl_close($ch);

	//End ob and erase contents.
	ob_end_clean();

	return $info;
}

$invoice_settings = $app->db->queryOneRecord("SELECT * FROM invoice_settings WHERE invoice_settings_id = 1");


$result = libCurlPost($invoice_settings['paypal_url'],$_POST);
$invoice_number = $app->db->quote(substr($_POST['custom'],0,100));
$error = '';


//check the ipn result received back from paypal
if(eregi("VERIFIED",$result)) {
	// OK
	if($_POST['payment_status'] == 'Completed') {
		
		//* fetch the invoice record
		$invoice = $app->db->queryOneRecord("SELECT * FROM invoice WHERE invoice_number = '$invoice_number'");
		
		if($invoice['invoice_id'] > 0) {
		
			// Check if the paid amount matches
			if((double)$_POST['mc_gross'] == (double)$invoice['invoice_amount']) {
		
				// Set invoice status to paid and insert the payment date
				$payment_date = date('Y-m-d');
				$sql = "UPDATE invoice SET status_paid = 'y', payment_date = '$payment_date' WHERE invoice_id = ".$invoice['invoice_id'];
				$app->db->query($sql);
			} else {
				$error .= 'Invoice amount mismatch.';
			}
		} else {
			//* No invoice found with that invoice number
			$error .= 'No invoice with number '.$invoice_number.' found.';
		}
		
	} else {
		$error .= 'Payment status is not Completed. Status: '.$_POST['payment_status'];
	}
} else {
	// Error
	//* Do something on error, e.g. write to a logfile
	$error .= 'Paypal result can not be verified.';
} 

//* Save the incoming IPN request to the payment log
$client_id = (isset($invoice['clint_id']))?$invoice['clint_id']:0;
$gateway = 'paypal';
$status = $app->db->quote($_POST['payment_status']);
$verification = $app->db->quote($result);
$received_date = date('Y-m-d H:i');
$message = $app->db->quote($error);
$rawdata = $app->db->quote(serialize($_POST));

$sql = "INSERT INTO invoice_payment_log (client_id,invoice_number,gateway,status,verification,received_date,message,rawdata) VALUES ($client_id,'$invoice_number','$gateway','$status','$verification','$received_date','$message','$rawdata')";
$app->db->query($sql);

/*
$out = date('Y-m-d H:i').' '.$error."\n\n\n".var_export($_POST,true)."\n\n\n".var_export($result,true);
file_put_contents('/tmp/ipn-'.date('Y-m-d_H-i').'.txt',$out);
*/


?>