<?php

/*======================================================================*\
|| #################################################################### ||
|| # Drag'nDrop Shop 1.8                                              # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright 2014 JAKWEB All Rights Reserved.                       # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| #   ----------- Drag'nDrop Shop IS NOT FREE SOFTWARE -----------   # ||
|| #                      http://www.jakweb.ch                        # ||
|| #################################################################### ||
\*======================================================================*/

if (!file_exists('../config.php')) {
    die('[ipn.php] config.php not exist');
}
require_once '../config.php';

// Include the paypal library
include_once ('paypal.php');

$sendmail = 0;

// Create an instance of the paypal library
$myPaypal = new Paypal();

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

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

// Check validity and write down it
if ($myPaypal->validateIpn()) {
    if ($myPaypal->ipnData['payment_status'] == 'Completed')
    {
    	$item_name = $myPaypal->ipnData['item_name'];
    	$payment_currency = $myPaypal->ipnData['mc_currency'];
    	$payment_status = $myPaypal->ipnData['payment_status'];
    	$txn_id = $myPaypal->ipnData['txn_id'];
    	$receiver_email = $myPaypal->ipnData['business_email'];
    	$receiver_email = $myPaypal->ipnData['receiver_email'];
    	$payment_amount = $myPaypal->ipnData['mc_gross'];
    	$payer_email = $myPaypal->ipnData['payer_email'];
    	$custom = base64_decode($myPaypal->ipnData['custom']);
    	
    	// Explode custom field with order number and orderid
    	$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 = "Paypal"');
    	
    	// 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_EMAIL, JAK_TITLE);
    	   		$maila->Subject = JAK_TITLE.' - PAYPAL 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("[\]", '', JAK_THANKYOU_MESSAGE);
    	   		$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
    	   		$mail->AddAddress($payer_email, $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_TITLE);   
    	   			$mailf->AddAddress($row1['email'], $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_TITLE);
    	   				$maila1->Subject = JAK_TITLE.' - PAYPAL 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_SHOPEMAIL);
    	   		$mail->Subject = JAK_TITLE.' - PAYPAL Success, but...';
    	   		$mail->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.' 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]).'"');
    	   	
    	}
    	
    	file_put_contents('paypal_ipn.txt', 'SUCCESS');
    	       	
    } else {
    
         file_put_contents('paypal_ipn.txt', "FAILURE\n\n" . $myPaypal->ipnData);
         
         // log for manual investigation
         $mail = new PHPMailer(); // defaults to using php "mail()"
         $mail->SetFrom($payer_email, 'Paypal HTTP error');
         $mail->AddAddress(JAK_EMAIL, JAK_TITLE);
         $mail->Subject = JAK_TITLE.' - PAYPAL HTTP error';
         $mail->Body = 'There is an error with PAYPAL, please check the text file.';
    }
}