<?php
/**
 * 
 * Sample IPN V2 Handler for Item Payments
 * 
 * The purpose of this code is to help you to understand how to process the Instant Payment Notification 
 * variables for a payment received through Payza's buttons and integrate it in your PHP site. The following
 * code will ONLY handle ITEM payments. For handling IPNs for SUBSCRIPTIONS, please refer to the appropriate
 * sample code file.
 *	
 * Put this code into the page which you have specified as Alert URL.
 * The conditional blocks provide you the logical placeholders to process the IPN variables. It is your responsibility
 * to write appropriate code as per your requirements.
 *	
 * If you have any questions about this script or any suggestions, please visit us at: dev.payza.com
 * 
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY
 * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
 * LIMITED TO THE IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE.
 * 
 * @author Payza
 * @copyright 2011
 */
 
 if (!file_exists('../config.php')) {
     die('[ipn.php] config.php not exist');
 }
 require_once '../config.php';
 
 // Include the paypal library
 include_once ('payza.php');
 
$sendmail = 0;

// Create an instance of the paypal library
$myPayza = new Payza();

// Log the IPN results
$myPayza->ipnLog = TRUE;

// Enable test mode if needed
//$myPayza->enableTestMode();

$response = $myPayza->validateIpn();
 	
 	if ($response) {
 	
 		if (urldecode($response) == "INVALID TOKEN") {
 			// log for manual investigation
 			$mail = new PHPMailer(); // defaults to using php "mail()"
 			$mail->SetFrom($payer_email, JAK_TITLE);
 			$mail->AddAddress(JAK_SHOPEMAIL, JAK_TITLE);
 			$mail->Subject = JAK_TITLE.' - AlertPay HTTP Token error';
 			$mail->Body = 'There is an error with AlertPay Token, please check the text file.';
 			
 		} else {
 			//urldecode the received response from Alertpay's IPN V2
 			$response = urldecode($response);
 			
 			//split the response string by the delimeter "&"
 			$aps = explode("&", $response);
 			
 			//define an array to put the IPN information
 			$info = array();
 			
 			foreach ($aps as $ap)
 			{
 				//put the IPN information into an associative array $info
 				$ele = explode("=", $ap);
 				$info[$ele[0]] = $ele[1];
 			}
 			
 			$item_name = $info['ap_itemname'];
 			$payment_currency = $info['ap_currency'];
 			$payment_status = $info['ap_status'];
 			$txn_id = $info['ap_referencenumber'];
 			$receiver_email = $info['ap_merchant'];
 			$payment_amount = $info['ap_amount'];
 			$payer_email = $info['ap_custemailaddress'];
 			
 			$custom = $info['apc_1'];
 			$customA = explode(":#:", $custom);
 			
 			// check that payment_amount/payment_currency are correct
 				global $jakdb;
 				
 				// process payment
 				$result = $jakdb->query('INSERT INTO '.DB_PREFIX.'shop_payment_ipn SET 
 				ordernr = "'.smartsql($customA[1]).'",
 				time = NOW(),
 				status = "'.smartsql($payment_status).'",
 				amount = "'.smartsql($payment_amount).'",
 				currency = "'.smartsql($payment_currency).'",
 				txn_id = "'.smartsql($txn_id).'",
 				receiver_email = "'.smartsql($receiver_email).'",
 				payer_email = "'.smartsql($payer_email).'",
 				paid_with = "AlertPay"');
 				
 				// check that txn_id has not been previously processed
 				$jakdb->query('SELECT id FROM '.DB_PREFIX.'shop_payment_ipn WHERE txn_id = "'.smartsql($txn_id).'"');
 				if ($jakdb->affected_rows == 1) {
 				
 					// Select price and item
 					$result1 = $jakdb->query('SELECT id, total_price, email, name FROM '.DB_PREFIX.'shop_order WHERE id = "'.smartsql($customA[0]).'" AND ordernumber = "'.smartsql($customA[1]).'"');
 					$row1 = $result1->fetch_assoc();
 						
 				if ($row1['total_price'] == $payment_amount) {
 				
 					$sendmail = 1;
 					
 					$jakdb->query('UPDATE '.DB_PREFIX.'shop_order SET paid = 1, paidtime = NOW() WHERE id = "'.smartsql($row1['id']).'"');
 					
 				}
 				   
 				   // Send email to customer if everything is paid
 				   if ($sendmail) {
 				   
 				   		// Send email to administrator
 				   		// log for manual investigation
 				   		$maila = new PHPMailer(); // defaults to using php "mail()"
 				   		$maila->SetFrom($payer_email, $payer_email);
 				   		$maila->AddAddress(JAK_SHOPEMAIL, JAK_E_TITLE);
 				   		$maila->Subject = JAK_E_TITLE.' - AlertPay Success';
 				   		$maila->Body = 'There is a new payment thru Paypal, order number: '.$customA[1].' - '.$item_name.' - '.$payment_status.' - '.$payment_amount.' - '.$payment_currency.' - '.$txn_id.' - '.$receiver_email.' - '.$payer_email;
 				   		$maila->Send(); // Send email without any warnings
 				   		
 				   		// Send Email to customer
 				   		$mail = new PHPMailer(); // defaults to using php "mail()"
 			   	   		$body = str_ireplace("[\]", '', utf8_decode(JAK_THANKYOU_MESSAGE));
 				   		$mail->SetFrom(JAK_EMAIL, JAK_E_TITLE);
 				   		$mail->AddAddress($payer_email, utf8_decode($customer));
 				   		$mail->Subject = JAK_TITLE.' - Payment approved';
 				   		$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
 				   		$mail->MsgHTML($body);
 				   		$mail->Send(); // Send email without any warnings
 				   		
 				   		// Now let's send the digital files if there are any
 				   		$result_option = $jakdb->query('SELECT t2.title, t2.digital_file FROM '.DB_PREFIX.'shop_order_details AS t1 LEFT JOIN '.DB_PREFIX.'shop AS t2 ON (t1.shopid = t2.id) WHERE t1.orderid = "'.smartsql($row1['id']).'" AND t2.digital_file != "" GROUP BY t1.shopid ');
 				   		
 				   		if ($jakdb->affected_rows >= 1) while ($row_option = $result_option->fetch_assoc()) {
 				   			
 				   			$getAttach = str_replace("//", "/", APP_PATH.$row_option['digital_file']);
 				   			$getAttachBase = basename($getAttach);
 				   			
 				   			if (round(filesize($getAttach) / 1024, 0) <= 2048) {
 				   				
 				   			$mailf = new PHPMailer(); // defaults to using php "mail()"
 				   			$bodyf = file_get_contents('../digital.html');
 				   			$bodyf = str_ireplace("[\]",'',$bodyf);
 				   			$mailf->SetFrom(JAK_EMAIL, JAK_E_TITLE);
 				   			$mailf->AddAddress($row1['email'], utf8_decode($row1['name']));
 				   			$mailf->Subject = JAK_TITLE.' - Digital File  - '.$row_option['title'];
 				   			$mailf->AltBody = 'To view the message, please use an HTML compatible email viewer!';
 				   			$mailf->AddAttachment($getAttach, $getAttachBase);
 				   			$mailf->MsgHTML($bodyf);
 				   			//$mailf->Send(); // Send email without any warnings
 				   			
 				   			if ($mailf->Send()) {
 				   			
 				   				$maila1 = new PHPMailer(); // defaults to using php "mail()"
 				   				$maila1->SetFrom(JAK_EMAIL, JAK_TITLE);
 				   				$maila1->AddReplyTo($defaults['email'], $defaults['name']);
 				   				$maila1->AddAddress(JAK_EMAIL, JAK_E_TITLE);
 				   				$maila1->Subject = JAK_E_TITLE.' - AlertPay Success - Digital File';
 				   				$maila1->Body = 'File has been sent...';
 				   				$maila1->Send(); // Send email without any warnings
 				   			
 				   			}
 				   			
 				   			} else {
 				   				
 				   				$maila1 = new PHPMailer(); // defaults to using php "mail()"
 				   				$maila1->SetFrom(JAK_EMAIL, JAK_TITLE);
 				   				$maila1->AddReplyTo($defaults['email'], $defaults['name']);
 				   				$maila1->AddAddress(JAK_EMAIL, JAK_TITLE);
 				   				$maila1->Subject = JAK_TITLE.' - PAYPAL Success - Digital File too big';
 				   				$maila1->Body = 'Please send the link for download thru the administration panel...';
 				   				$maila1->Send(); // Send email without any warnings
 				   			}
 				   			    
 				   		}
 				   		
 				   	} else {
 				   	
 				   		// log for manual investigation amount is not the same
 				   		$mail = new PHPMailer(); // defaults to using php "mail()"
 				   		$mail->SetFrom($payer_email, $payer_email);
 				   		$mail->AddAddress(JAK_EMAIL, JAK_EMAIL);
 				   		$mail->Subject = JAK_E_TITLE.' - AlertPay Success, but...';
 				   		$mail->Body = 'There is a new payment thru AlertPay, order number: '.$customA[1].' - '.$item_name.' - '.$payment_status.' - '.$payment_amount.' - '.$payment_currency.' - '.$txn_id.' - '.$receiver_email.' - '.$payer_email.' But the amount was paid is not the same amount was ordered, please check in the shop order details.';
 				   		$mail->Send(); // Send email without any warnings
 				   	
 				   	}
 				   	
 				   	// Finally Delete the shopping Cart
 				   	$jakdb->query('DELETE FROM '.DB_PREFIX.'shopping_cart WHERE session = "'.smartsql($customA[2]).'"');
 				   	
 				}
 			}
 		
 	} else {
 		file_put_contents('payza.txt', "FAILURE\n\n" . $myPayza->ipnData);
 		
 		// log for manual investigation
 		$mail = new PHPMailer(); // defaults to using php "mail()"
 		$mail->SetFrom($payer_email, 'AlertPay HTTP error');
 		$mail->AddAddress(JAK_EMAIL, JAK_TITLE);
 		$mail->Subject = JAK_TITLE.' - AlertPay HTTP error';
 		$mail->Body = 'There is an error with AlertPay, please check the text file.';
 	}
?>