<?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                        # ||
|| #################################################################### ||
\*======================================================================*/

// Check if the file is accessed only via index.php if not stop the script from running
if(!defined('JAK_PREVENT_ACCESS')){
die('You cannot access this file directly.');
}

$errors = array();
$jaktable = DB_PREFIX.'shop';
$jaktable1 = DB_PREFIX.'shop_payment';
$jaktable2 = DB_PREFIX.'shop_order';
$jaktable3 = DB_PREFIX.'user';
$jaktable4 = DB_PREFIX.'shop_shipping';
$jaktable5 = DB_PREFIX.'shop_order_details';
$jaktable6 = DB_PREFIX.'shopping_cart';
$jaktable7 = DB_PREFIX.'categories';

// parse url
$backtoshop = JAK_rewrite::jakParseurl('', '', '', '', '');
$shopcheckout = JAK_rewrite::jakParseurl('checkout', '', '', '', '');


// Import all classes
include_once 'class/shopping_cart.php';
include_once 'class/currency_converter.php';

// Start the shopping cart
$shopping_cart = new Shopping_Cart();
$shopping_cart->startTheCart();

// Start the Currency Converter
$convert = new CurrencyConverter();

// The new Shop Currency exchange
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['currency'])) {
	
	if ($convert->CheckCurrency($_POST['currency'])) {
	
		$_SESSION['ECOMMERCE_CURRENCY'] = $_POST['currency'];
	
	} else {
	
		$_SESSION['ECOMMERCE_CURRENCY'] = JAK_CURRENCY;
	}	
}

if (!isset($_SESSION['ECOMMERCE_CURRENCY'])) {

	$_SESSION['ECOMMERCE_CURRENCY'] = JAK_CURRENCY;
}

$JAK_CURRENCY = $_SESSION['ECOMMERCE_CURRENCY'];
$E_CURRENCY_CHOOSE = $convert->CurrencyChoose();

// Get the rss if active
if (JAK_ECOMMERCERSS) {
	$JAK_RSS_DISPLAY = 1;
	$P_RSS_LINK = JAK_rewrite::jakParseurl('rss.xml', '', '', '', '');
}
if (is_numeric($page2) && jak_field_not_exist($page1, $jaktable2, 'ordernumber')) {

	// First get the paypal address out, if exist keep going
	$result = $jakdb->query('SELECT total_price, currency, email, name FROM '.$jaktable2.' WHERE ordernumber = "'.smartsql($page1).'"');
	$row = $result->fetch_assoc();
	
	$result_p = $jakdb->query('SELECT field, field1, field2 FROM '.$jaktable1.' WHERE id = "'.smartsql($page2).'"');
	$row_p = $result_p->fetch_assoc();
	
	if ($jakdb->affected_rows > 0) {
	
	$ecfield = $row_p['field'];
	$ecfield1 = base64_decode($row_p['field1']);
	$ecprice = $row['total_price'];
	$eccurrency = $row['currency'];
	
	if ($page2 == 2) {
		$PAGE_TITLE = $tl['shop']['m10'];
		$PAGE_CONTENT = $tl['m']['m13'];
	} elseif ($page2 == 3) {
		$PAGE_TITLE = $tl['shop']['m11'];
		$PAGE_CONTENT = $tl['m']['m78'];
	} elseif ($page2 == 4) {
		$PAGE_TITLE = $tl['shop']['m79'];
		$PAGE_CONTENT = $tl['m']['m51'];
	} elseif ($page2 == 10) {
		$PAGE_TITLE = $tl['shop']['m91'];
		$PAGE_CONTENT = $tl['shop']['m92'];
		
		// Get the keys
		$stripe_key = explode(":#:", base64_decode($row_p['field2']));
		
		require_once('payment/stripe/Stripe.php');
		 
		$stripe = array(
		  secret_key      => $stripe_key[0],
		  publishable_key => $stripe_key[1]
		);
		 
		Stripe::setApiKey($stripe['secret_key']);
		
		// get the currency for stripe
		$stripe_amount = $ecprice * 100;
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		
			$token  = $_POST['stripeToken'];
			
			try {
				$charge = Stripe_Charge::create(array(
				  "amount" => $stripe_amount, // amount in cents, again
				  "currency" => $row['currency'],
				  "card" => $token,
				  "description" => $row['email'])
				);
			// Now we forward the client.
			$jakdb->query('UPDATE '.$jaktable2.' SET paid = 1, paidtime = NOW() WHERE id = "'.smartsql($row['id']).'"');
			
			// Send email to administrator
			// log for manual investigation
			$maila = new PHPMailer(); // defaults to using php "mail()"
			$maila->SetFrom($row['email'], $row['name']);
			$maila->AddAddress(JAK_EMAIL, JAK_TITLE);
			$maila->Subject = JAK_TITLE.' - Stripe Success';
			$maila->Body = 'There is a new payment thru Stripe, order number: '.$page1.' - Paid Stripe - '.$ecprice.' - '.$eccurrency.' - '.$row['email'];
			$maila->Send(); // Send email without any warnings
			
			// Send Email to customer
			$mail = new PHPMailer(); // defaults to using php "mail()"
				$body = str_ireplace("[\]", '', JAK_THANKS.'<p>Order Number:'.$page1.'</p>');
			$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
			$mail->AddAddress($row['email'], $row['name']);
			$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($row['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($row['email'], $row['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
				}
				    
			}
			
			jak_redirect(html_entity_decode(JAK_rewrite::jakParseurl($tl['link']['l8'], '', '', '', '')));
			
			} catch(Stripe_CardError $e) {
				jak_redirect(html_entity_decode(JAK_rewrite::jakParseurl($tl['link']['l9'], '', '', '', '')));
			}
		
		}
			
	} else {
		$PAGE_TITLE = $tl['shop']['m12'];
		$PAGE_CONTENT = $tl['shop']['m8'];
	}
	
	// get the standard template
	$template = 'notify.php';
	
} else {
	jak_redirect(BASE_URL);
}

} else {
	jak_redirect(BASE_URL);
}
?>