<?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 ('twoco.php');

// Create an instance of the authorize.net library
$my2CO = new TwoCo();

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

// First get the paypal address out, if exist keep going
global $jakdb;
$sql = 'SELECT field1, field2 FROM '.DB_PREFIX.'shop_payment WHERE id = 5 AND status = 1 LIMIT 1';
$result = $jakdb->query($sql);
$row = $result->fetch_assoc();

// Specify your authorize login and secret
$my2CO->setSecret(base64_decode($row['field2']));

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

// Check validity and write down it
if ($my2CO->validateIpn())
{
    
    $item_name = base64_decode($my2CO->ipnData['custom']);
    $payment_currency = $my2CO->ipnData['tco_currency'];
    $payment_status = $my2CO->ipnData['invoice_status'];
    $txn_id = $my2CO->ipnData['vendor_order_id'];
    $payment_amount = $my2CO->ipnData['total'];
    $payer_email = $my2CO->ipnData['vendor_id'];
    $custom = base64_decode($my2CO->ipnData['order_number']);
    
    $customA = explode(":#:", $item_name);
    
    // 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 = "2CheckOut"');
    
    // 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.' - 2Checkout Success';
       		$maila->Body = 'There is a new payment thru 2Checkout, order number: '.$customA[1].' - '.$item_name.' - '.$payment_status.' - '.$payment_amount.' - '.$payment_currency.' - '.$txn_id.' - '.$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.' - 2CheckOut 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_TITLE);
       		$mail->Subject = JAK_TITLE.' - 2Checkout Success, but...';
       		$mail->Body = 'There is a new payment thru 2Checkout, order number: '.$customA[1].' - '.$item_name.' - '.$payment_status.' - '.$payment_amount.' - '.$payment_currency.' - '.$txn_id.' - '.$payer_email.' But the amount was paid is not the same amount was ordered, please check in the shopping 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('2co_ipn.txt', 'SUCCESS');

} else {
	
	// log for manual investigation
	$mail = new PHPMailer(); // defaults to using php "mail()"
	$mail->SetFrom($payer_email, '2CheckOut HTTP error');
	$mail->AddAddress(JAK_EMAIL, JAK_TITLE);
	$mail->Subject = JAK_TITLE.' - 2CheckOut HTTP error';
	$mail->Body = 'There is an error with 2CheckOut, please check the text file.';
	
    file_put_contents('2co_ipn.txt', "FAILURE\n\n" . $my2CO->ipnData);
}
?>