<?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';
$jaktable8 = DB_PREFIX.'shop_user';

// 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'];
$CURRENCY_CHOOSE = $convert->CurrencyChoose();

// Customer tries to login
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login-customer'])) {
	
	$useremail = smartsql($_POST['email']);
	$userpass = smartsql($_POST['password']);
	
	$user_check = $customerlogin->lsCheckcustomerdata($useremail, $userpass);
	
	if ($user_check == true) {
		
		// Now login in the user
		$customerlogin->lsLoginCustomer($useremail, $userpass);
		
		// Set session
		$_SESSION['customer_selected'] = "return";
		
		jak_redirect($shopcheckout);
	
	} else {
	    $ErrLogin = 1;
	}
		
}

// Customer is new
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['new-customer'])) {

		$_SESSION['customer_selected'] = "new";
		jak_redirect($shopcheckout);
		
}

// Checkout and do the payment options		    
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['checkout'])) {
	$defaults = $_POST;
	
	if (empty($defaults['jak_agree'])) {
	    $errors['e12'] = $tl['shop']['e'];
	}
	
	if (empty($defaults['name'])) {
	    $errors['e'] = $tl['error']['e'].'<br />';
	}
	
	if (FO_EMAIL_BLOCK) {
		$blockede = explode(',', FO_EMAIL_BLOCK);
		if (in_array($defaults['email'], $blockede) || in_array(strrchr($defaults['email'], "@"), $blockede)) {
			$errors['email'] = $tl['error']['e10'];
		}
	}
	
	if (empty($defaults['email']) || !filter_var($defaults['email'], FILTER_VALIDATE_EMAIL)) {
	    $errors['e1'] = $tl['error']['e1'].'<br />';
	}
	
	if (!empty($defaults['save-userdata']) && strlen(trim($defaults['password'])) <= '5') {
		$errors['e11'] = $tl['error']['e2'].'<br />';
	}
	
	if (empty($defaults['phone'])) {
	    $errors['e3'] = $tl['shop']['e5'].'<br />';
	}
	
	if (empty($defaults['address'])) {
	    $errors['e4'] = $tl['shop']['e1'].'<br />';
	}
	
	if (empty($defaults['city'])) {
	    $errors['e5'] = $tl['shop']['e2'].'<br />';
	}
	
	if (empty($defaults['postal'])) {
	    $errors['e6'] = $tl['shop']['e3'].'<br />';
	}
	
	if (empty($defaults['country'])) {
	    $errors['e7'] = $tl['shop']['e4'].'<br />';
	}
	
	if (isset($defaults['shipping_option']) && empty($defaults['shipping_option'])) {
		$errors['e8'] = $tl['shop']['e6'];
	}
	
	if (empty($defaults['payment_option'])) {
		$errors['e9'] = $tl['shop']['e7'];
	}
	
	// Check coupon code
	if (!empty($defaults['jak_shcode']) && !preg_match('/^([0-9]||[a-z]||[A-Z])+$/', $defaults['jak_shcode']) || !empty($defaults['jak_shcode']) && !jak_shop_coupon_check($defaults['jak_shcode'])) {
	    $errors['e10'] = $tl['shop']['e8'];
	}
	
if (count($errors) == 0) {

	$payment_id = explode(":#:", $defaults['payment_option']);
	$shipping_price = explode(":#:", $defaults['shipping_option']);
	$safeemail = filter_var($defaults['email'], FILTER_SANITIZE_EMAIL);
	$sh_safeemail = filter_var($defaults['sh_email'], FILTER_SANITIZE_EMAIL);
	
	$safecompany = filter_var($defaults['company'], FILTER_SANITIZE_STRING);
	$safename = filter_var($defaults['name'], FILTER_SANITIZE_STRING);
	$safeaddress = filter_var($defaults['address'], FILTER_SANITIZE_STRING);
	$safezip = filter_var($defaults['postal'], FILTER_SANITIZE_STRING);
	$safecity = filter_var($defaults['city'], FILTER_SANITIZE_STRING);
	$safecountry = filter_var($defaults['country'], FILTER_SANITIZE_STRING);
	
	// Create ordernumber
	$ordernumber = 'O-'.mt_rand();
	$_SESSION['ECOMMERCE_ORDNR'] = $ordernumber;
	
	// Get the total price
	$result = $jakdb->query('SELECT SUM(t1.price) AS total_price FROM '.$jaktable6.' AS t1 WHERE t1.session = "'.smartsql($_SESSION['shopping_cart']).'"');
	$row = $result->fetch_assoc();
	
	$total_price = $row['total_price'];
	
	// Calclute the new shop price if currency
	if ($_SESSION['ECOMMERCE_CURRENCY'] != JAK_CURRENCY) {
	
		$total_price = $convert->Convert($row['total_price'], $_SESSION['ECOMMERCE_CURRENCY']);
	
	}
	
	// Calculate the shop taxes
	if (JAK_TAXES && JAK_COUNTRY == $safecountry) {
		$taxTotal = $total_price / 100 * JAK_TAXES;
		$taxSumC = round($taxTotal, 1);
		$total_price += $taxSumC;
	}
	
	// Shipping fees
	if ($payment_id[1] != 7) {
	
		$total_price += $shipping_price[0];
		$shipping_p = $shipping_price[0];
	} else {
	
		$shipping_p = 0;
	}
	
	// Calculate the shop fees
	if ($payment_id[0]) {
		$feeTotal = $total_price / 100 * $payment_id[0];
		$feeSumC = round($feeTotal, 1);
		$total_price += $feeSumC;
	}
	
	// two decimals
	$total_price = number_format($total_price, 2, '.', '');
	
	if ($defaults['show-shipping']) {
		
		$insert .= 'sh_name = "'.smartsql($defaults['sh_name']).'",
		sh_company = "'.smartsql($defaults['sh_company']).'",
		sh_address = "'.smartsql($defaults['sh_address']).'",
		sh_country = "'.smartsql($defaults['sh_country']).'",
		sh_city = "'.smartsql($defaults['sh_city']).'",
		sh_zip_code = "'.smartsql($defaults['sh_postal']).'",
		sh_phone = "'.smartsql($defaults['sh_phone']).'",';
	
	}
	
	if ($defaults['save-userdata'] && $defaults['password']) {
		
		$jakdb->query('INSERT INTO '.$jaktable8.' SET 
		name = "'.smartsql($safename).'",
		password = "'.hash_hmac('sha256', $defaults['password'], DB_PASS_HASH).'",
		company = "'.smartsql($safecompany).'",
		address = "'.smartsql($safeaddress).'",
		country = "'.smartsql($safecountry).'",
		city = "'.smartsql($safecity).'",
		zip_code = "'.smartsql($safezip).'",
		email = "'.smartsql($safeemail).'",
		phone = "'.smartsql($defaults['phone']).'",
		time = NOW()');
		
		$registermsg = '<p>'.$tl["general"]["g28"].'</p><p>'.$tl["general"]["g29"].': '.$safeemail.'<br>'.$tl["general"]["g30"].': '.$defaults['password'].'</p>';
		
		$mail = new PHPMailer(); // defaults to using php "mail()"
		$body = str_ireplace("[\]", '', $registermsg);
		$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
		$mail->AddAddress($safeemail, $safename);
		$mail->Subject = JAK_TITLE.' - '.$tl["general"]["g27"];
		$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
		$mail->MsgHTML($body);
		$mail->Send(); // Send email without any warnings
	}
	
	$jakdb->query('INSERT INTO '.$jaktable2.' SET 
	paid_method = "'.smartsql($payment_id[1]).'",
	total_price = "'.$total_price.'",
	tax = "'.$taxSumC.'",
	shipping = "'.$shipping_p.'",
	currency = "'.smartsql($_SESSION['ECOMMERCE_CURRENCY']).'",
	name = "'.smartsql($safename).'",
	company = "'.smartsql($safecompany).'",
	address = "'.smartsql($safeaddress).'",
	country = "'.smartsql($safecountry).'",
	city = "'.smartsql($safecity).'",
	zip_code = "'.smartsql($safezip).'",
	email = "'.smartsql($safeemail).'",
	phone = "'.smartsql($defaults['phone']).'",
	'.$insert.'
	time = NOW(),
	ordernumber = "'.$ordernumber.'"');
	
	$orderid = $jakdb->jak_last_id();
	
	// Zero all results
	$disc_diff = 0.00;
	$freeshipping = false;
	$couponID = 0;
	
	// Let's start with getting out all of the data and insert into the order table!
	$result = $jakdb->query('SELECT t1.price, t1.weight, t1.product_option, t2.id, t2.title, t2.previmg FROM '.$jaktable6.' AS t1 LEFT JOIN '.$jaktable.' AS t2 ON(t1.shopid = t2.id) WHERE t1.session = "'.smartsql($_SESSION['shopping_cart']).'"');
	
	while ($row = $result->fetch_assoc()) {
		
		if ($_SESSION['ECOMMERCE_CURRENCY'] != JAK_CURRENCY) {
		
			$row['price'] = $convert->Convert($row['price'], $_SESSION['ECOMMERCE_CURRENCY']);
		
		}
		
		// get the discount if there is any.
		if (!empty($defaults['jak_shcode'])) {
		
			$disc_price = 0.00;
		
			$resultc = $jakdb->query('SELECT id, type, discount, freeshipping FROM '.DB_PREFIX.'shop_coupon WHERE code = "'.smartsql($defaults['jak_shcode']).'" AND (FIND_IN_SET('.$row['id'].', products) OR products = 0) AND status = 1 AND datestart < "'.time().'" AND dateend > "'.time().'" AND used < total LIMIT 1');
			$rowc = $resultc->fetch_assoc();
		
			// Check discount type (type1 = percentage)
			if ($rowc['type'] == 1) {
				// Get the discount before taxes
				$totalD = $row['price'] / 100 * $rowc['discount'];
				$disc_price = $row['price'] - number_format(round($totalD, 1), 2, '.', '');
					
			} else {
				// Get the discount before taxes
				$disc_price = $row['price'] - $rowc['discount'];
					
				
			}
			
			if ($rowc['freeshipping'] == 1) {
				$freeshipping = true;
			}
			
		}
		
		$jakdb->query('INSERT INTO '.$jaktable5.' SET 
		orderid = "'.$orderid.'",
		shopid = "'.$row['id'].'",
		title = "'.$row['title'].'",
		product_option = "'.$row['product_option'].'",
		price = "'.$row['price'].'",
		coupon_price = "'.$disc_price.'",
		weight = "'.$row['weight'].'"');
		
		// if we have quantity we subtract the number
		if (JAK_SHOPQUANTITY) {
		
			$jakdb->query('UPDATE '.$jaktable.' SET stock = stock - 1 WHERE id = '.$row['id']);
		
		}
		
		// Get the discount total
		$discount_total += $disc_price;
		
		// Get the id into a var
		if ($rowc["id"]) $couponID = $rowc["id"];
	
	}
	
	// Now update the total order db
	if ($discount_total || $freeshipping) {
	
		if ($discount_total) {
		
			$disc_diff = $total_price - $discount_total;
			$total_price = $total_price - $disc_diff;
			
			// Calculate the shop taxes
			if (JAK_TAXES && JAK_COUNTRY == $safecountry) {
				$taxTotal = $total_price / 100 * JAK_TAXES;
				$taxSumC = round($taxTotal, 1);
				$total_price += $taxSumC;
				
				// total diff
				$taxTotald = $disc_diff / 100 * JAK_TAXES;
				$taxSumCd = round($taxTotald, 1);
				$disc_diff += $taxSumCd;
			}
			
			// Calculate the shop fees
			if ($payment_id[0]) {
				$feeTotal = $total_price / 100 * $payment_id[0];
				$feeSumC = round($feeTotal, 1);
				$total_price += $feeSumC;
				
				// Total diff fees
				$feeTotald = $disc_diff / 100 * $payment_id[0];
				$feeSumCd = round($feeTotald, 1);
				$disc_diff += $feeSumCd;
			}
			
			if ($payment_id[1] != 7) {
			
			if (!$freeshipping) {
				// Add shipping to the new total
				$total_price += $shipping_price[0];
				$shipping_p = $shipping_price[0];
				
				// total diff with shipping
				$coupon_total += $shipping_price[0];
			}
				
			} else {
			
				$shipping_p = 0;
			}
			
			// two decimals
			$total_price = number_format($total_price, 2, '.', '');
			$disc_diff = number_format($disc_diff, 2, '.', '');
			
			$insertc = 'total_price = "'.$total_price.'", discount = "'.$disc_diff.'"';
			
		}
		
		if ($freeshipping) {
			$insertf = ($insertc ? ', freeshipping = 1' : 'freeshipping = 1');
		}
		
		// Update the order table
		$jakdb->query('UPDATE '.$jaktable2.' SET 
		'.$insertc.'
		'.$insertf.'
		WHERE id = '.$orderid);
		
		// Update the coupon table
		if ($couponID) $jakdb->query('UPDATE '.DB_PREFIX.'shop_coupon SET used = used + 1 WHERE id = '.$couponID);
	
	}
	
	// Now get the payment information
	$result_p = $jakdb->query('SELECT field1, field2, field3 FROM '.$jaktable1.' WHERE id = "'.smartsql($payment_id[1]).'" AND status = 1');
	$row_p = $result_p->fetch_assoc();
	
	// Now let's send the invoice
	$resulti = $jakdb->query('SELECT * FROM '.$jaktable2.' WHERE id = "'.smartsql($orderid).'"');
	$rowi = $resulti->fetch_assoc();
	
	$result_option = $jakdb->query('SELECT COUNT(id) AS total_item, title, product_option, price, coupon_price FROM '.$jaktable5.' WHERE orderid = '.$rowi['id'].' GROUP BY product_option, shopid ORDER BY price ASC');
	
	while ($row_option = $result_option->fetch_assoc()) {
	
		$row_option['price'] = $row_option['total_item'] * $row_option['price'];
		
	    $jak_ordered[] = array('title' => $row_option['title'], 'product_option' => $row_option['product_option'], 'price' => number_format($row_option['price'], 2, '.', ''), 'coupon_price' => number_format($row_option['coupon_price'], 2, '.', ''), 'total_item' => $row_option['total_item']);
	}
	
	// Get the right Country
	$JAK_COUNTRY = $shopping_cart->getCountry(239, $rowi['country']);
	$JAK_SHCOUNTRY = $shopping_cart->getCountry(239, $rowi['sh_country']);
	
	if ($rowi["company"]) { 
	
	$inv_address .= $rowi["company"].'<br />'; } $inv_address .= $rowi["name"].'<br />'.$rowi["address"].'<br />'.$rowi["city"].' '.$rowi["zip_code"].'<br />'.$JAK_COUNTRY.'</div>
	<div class="shipping_address"><h4>'.$tl["shop"]["m84"].'</h4>';
	
	if ($rowi['sh_name']) { if ($rowi["sh_company"]) { 
	$inv_address .= $rowi["sh_company"].'<br />'; } $inv_address .= $rowi["sh_name"].'<br />'.$rowi["sh_address"].'<br />'.$rowi["sh_city"].' '.$rowi["sh_zip_code"].'<br />'.$JAK_SHCOUNTRY;
	
	} else {
	
	if ($rowi["company"]) {
	$inv_address .= $rowi["company"].'<br />'; } $inv_address .= $rowi["name"].'<br />'.$rowi["address"].'<br />'.$rowi["city"].' '.$rowi["zip_code"].'<br />'.$JAK_COUNTRY;
	
	}
	
 	if (isset($jak_ordered) && is_array($jak_ordered)) foreach($jak_ordered as $jo) {
 	
 	$inv_options = '';
 	$inv_price = '';
 	
 	if ($jo["product_option"]) $inv_options = '&nbsp;('. $jo["product_option"] .')&nbsp;';
 	if ($jo["coupon_price"] != "0.00" && $jo["price"] != $jo["coupon_price"]) { $inv_price = ' ('.$tl["shop"]["m86"].$jo["coupon_price"].'&nbsp;'.$row["currency"].')';}
	
	$inv_products .= '<li class="unpaid">'.$jo["total_item"].' x '.$jo["title"].$inv_options.'<span>'.$jo["price"].'&nbsp;'.$rowi["currency"].$inv_price.'</span></li>';
	
	}
	
	if ($row["freeshipping"]) { $inv_shipping = $tl["shop"]["m85"]; } else { $inv_shipping = $rowi["shipping"].' '.$rowi["currency"];}
	
	$invoice_template = '<!DOCTYPE html>
	<html lang="en">
	<head>
		<title>'.JAK_TITLE.' - '.$tl["shop"]["m80"].'</title>
		<meta charset="utf-8">
		<meta name="description" content="e-Commerce from JAKWEB" />
		<meta name="keywords" content="JAKWEB" />
		<meta name="author" content="" />
		<style>
		
		body {
			background: #fff;
		}
		
		.invoice_number {
			margin: 20px;
			font-size: 18px;
			font-weight: bold;
		}
		
		.invoice_address {
			float: left;
			margin: 0 0 20px 30px;
			font-size: 14px;
		}
		
		.invoice_address_shop {
			width: 750px;
			margin: 20px;
			text-align: center;
		}
		
		.shipping_address {
			float: right;
			margin: 0 0 20px 30px;
			font-size: 14px;
		}
		
		.shopcat {color:#3b5da3;font-weight:normal;margin:20px;padding:0;}
		.shopcat li {list-style:none;border-bottom:1px solid #e2e2e2;margin:0 20px 10px 10px;padding-bottom:2px;}
		.shopcat li span {
			float: right;
		}
		.shopcat .shopoption {list-style:none;border-bottom:1px solid #e2e2e2;margin:0 20px 10px 40px;padding-bottom:2px;}
		.shopcat a {position:relative;color:#4d97bd;text-decoration:none;}
		.shopcat img {margin-top:-2px;float:right;}
		.shopcat .unpaid {list-style:none;border-bottom:1px solid #c95252;margin:0 20px 10px 10px;padding-bottom:2px;}
		.shopcat .paid {list-style:none;border-bottom:1px solid #5ebe7d;margin:0 20px 10px 10px;padding-bottom:2px;}
		.shoptotalsum {float: right;margin-right:10px;}
		.clear {
			clear: both;
		}
		
		</style>
	</head>
	<body>
	<div style="width:750px; font-family: Arial, Helvetica, sans-serif; font-size: 12px;margin:0 auto 0em">
	<div align="center"><img src="'.BASE_URL.'img/header.jpg" style="height: 90px; width: 750px"></div>
	<div class="invoice_number">'.$tl["shop"]["m80"].': '.$rowi["ordernumber"].'</div>
	<div class="invoice_address"><h4>'.$tl["shop"]["m81"].'</h4>
	'.$inv_address.'
	</div>
	<div style="clear:both;"></div>
	<h1 style="margin-left:20px">'.$tl["shop"]["m82"].'</h1>
	<div>
	<ul class="shopcat">
	'.$inv_products.'
	</ul>
	<div class="shoptotalsum"><strong>'.$tl["shop"]["m83"].': </strong>'.$inv_shipping.'<br /><strong>'.$tl["shop"]["m87"].': </strong>'.$rowi["tax"].'&nbsp;'.$rowi["currency"].'<br /><strong>'.$tl["shop"]["m88"].'</strong>'.$rowi["total_price"].'&nbsp;'.$rowi["currency"].'</div>
	</div>
	<div class="clear"></div>
	<div class="invoice_address_shop">
	<h4>'.$tl["shop"]["m89"].'</h4>
	<p>'.JAK_SHOP_ADDRESS.'</p>
	</div>
	</div>
	</body>
	</html>';
	
	// Send the email with bank details
	$mail = new PHPMailer(); // defaults to using php "mail()"
	$invc = str_ireplace("[\]", '', $invoice_template);
	$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
	$mail->AddAddress($safeemail, $safename);
	$mail->Subject = JAK_TITLE.' - '.$tl["shop"]["m80"];
	$mail->MsgHTML($invc);
	$mail->Send(); // Send email without any warnings
	
	// finish send invoice when order
	
	// Now we start with the payment option, this goes from  1 - 7
	switch($payment_id[1]) {
	
		// Cheque / Money Order
		case 2:
		
			// Send the email with bank details
			$mail = new PHPMailer(); // defaults to using php "mail()"
			$body = str_ireplace("[\]", '', JAK_THANKYOU_MESSAGE.'<br />'.$tl['shop']['m13'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.$tl['shop']['m9'].base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
			$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
			$mail->AddAddress($safeemail, $safename);
			$mail->Subject = JAK_TITLE;
			$mail->MsgHTML($body);
			$mail->Send(); // Send email without any warnings
			
			// Send an email to the owner if wish so
			if (JAK_EMAIL) {
			
				$maila = new PHPMailer(); // defaults to using php "mail()"
				$bodya = str_ireplace("[\]",'',$tl['shop']['m13'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.$tl['shop']['m9'].base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
				$maila->SetFrom(JAK_EMAIL, JAK_TITLE);
				$maila->AddReplyTo($safeemail, $safename);
				$maila->AddAddress(JAK_EMAIL, JAK_TITLE);
				$maila->Subject = JAK_TITLE.' - '.$tl['shop']['m53'];
				$maila->MsgHTML($bodya);
				$maila->Send(); // Send email without any warnings
			}
			
			// Finally Delete the shopping Cart
			$jakdb->query('DELETE FROM '.$jaktable6.' WHERE session = "'.smartsql($_SESSION['shopping_cart']).'"');
			
			jak_redirect(html_entity_decode(JAK_rewrite::jakParseurl($tl['shop']['m6'], $ordernumber, '2', '', '')));
			exit;
				
		break;
		
		// Paypal
		case 3:
		
			// Now we go with thru paypal and verify the payment
			
			// Include the paypal library
			include_once ('payment/paypal.php');
			
			// Create an instance of the paypal library
			$myPaypal = new Paypal();
			
			// Specify your paypal email
			$myPaypal->addField('business', base64_decode($row_p['field1']));
			
			// Specify the currency
			$myPaypal->addField('currency_code', $_SESSION['ECOMMERCE_CURRENCY']);
			
			// Specify the url where paypal will send the user on success/failure
			$myPaypal->addField('return', JAK_rewrite::jakParseurl($tl['link']['l8'], '', '', '', ''));
			$myPaypal->addField('cancel_return', JAK_rewrite::jakParseurl($tl['link']['l9'], '', '', '', ''));
			
			// Specify the url where paypal will send the IPN
			$myPaypal->addField('notify_url', BASE_URL.'payment/paypal_ipn.php');
			
			// Specify the product information
			$myPaypal->addField('item_name', JAK_TITLE);
			$myPaypal->addField('amount', $total_price);
			
			// Specify any custom value
			$myPaypal->addField('custom', base64_encode($orderid.':#:'.$ordernumber.':#:'.$_SESSION['shopping_cart']));
			
			// Enable test mode if needed
			//$myPaypal->enableTestMode();
			
			$JAK_GO_PAY = $myPaypal->submitPayment($tl['shop']['m5']);
		 
		break;
		
		// 2Checkout
		case 4:
			
			// Include the twoco library
			include_once ('payment/twoco.php');
				
			// Create an instance of the authorize.net library
			$my2CO = new TwoCo();
				
			// Specify your 2CheckOut vendor id
			$my2CO->addField('sid', base64_decode($row_p['field1']));
				
			// Specify the order information
			$my2CO->addField('cart_order_id', base64_encode($orderid));
			$my2CO->addField('total', $total_price);
				
			// Specify the url where authorize.net will send the IPN
			$my2CO->addField('x_Receipt_Link_URL', BASE_URL.'payment/twoco_ipn.php');
			$my2CO->addField('tco_currency', $_SESSION['ECOMMERCE_CURRENCY']);
			$my2CO->addField('custom', base64_encode($orderid.':#:'.$ordernumber.':#:'.$_SESSION['shopping_cart']));
				
			// Enable test mode if needed
			//$my2CO->enableTestMode();
				
			$JAK_GO_PAY = $my2CO->submitPayment($tl['shop']['m5']);
										
		break;
		// Authorize.net
		case 5:
		
			// Include the authorize library
			include_once ('payment/authorize.php');
			
			// Create an instance of the authorize.net library
			$myAuthorize = new Authorize();
			
			// Specify your authorize.net login and secret
			$myAuthorize->setUserInfo(base64_decode($row_p['field1']), base64_decode($row_p['field2']));
			
			// Specify the url where authorize.net will send the user on success/failure
			$myAuthorize->addField('x_Receipt_Link_URL', JAK_rewrite::jakParseurl($tl['link']['l8'], '', '', '', ''));
			
			// Specify the url where authorize.net will send the IPN
			$myAuthorize->addField('x_Relay_URL', BASE_URL.'payment/authorize_ipn.php');
			
			// Specify the product information
			$myAuthorize->addField('x_Description', JAK_TITLE);
			$myAuthorize->addField('x_Amount', $total_price);
			$myAuthorize->addField('x_Invoice_num', base64_encode($orderid.':#:'.$ordernumber.':#:'.$_SESSION['shopping_cart']));
			$myAuthorize->addField('x_Cust_ID', $ordernumber);
			
			// Enable test mode if needed
			//$myAuthorize->enableTestMode();
			
			$JAK_GO_PAY = $myAuthorize->submitPayment($tl['shop']['m5']);
			
		break;
		// Cheque or Cash
		case 6:
			
			// Send the email with bank details
			$mail = new PHPMailer(); // defaults to using php "mail()"
			$body = str_ireplace("[\]", '', JAK_THANKYOU_MESSAGE.'<br />'.$tl['shop']['m13'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
			$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
			$mail->AddAddress($safeemail, $safename);
			$mail->Subject = JAK_TITLE;
			$mail->MsgHTML($body);
			$mail->Send(); // Send email without any warnings
			
			// Send an email to the owner if wish so
			if (JAK_EMAIL) {
			
				$maila = new PHPMailer(); // defaults to using php "mail()"
				$bodya = str_ireplace("[\]", '', $tl['shop']['m13'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
				$maila->SetFrom(JAK_EMAIL, JAK_TITLE);
				$maila->AddAddress(JAK_EMAIL, $safename);
				$maila->Subject = JAK_TITLE.' - '.$tl['shop']['m53'];
				$maila->MsgHTML($bodya);
				$maila->Send(); // Send email without any warnings
				
			}
			
			// Finally Delete the shopping Cart
			$jakdb->query('DELETE FROM '.$jaktable6.' WHERE session = "'.smartsql($_SESSION['shopping_cart']).'"');
			
			jak_redirect(html_entity_decode(JAK_rewrite::jakParseurl($tl['shop']['m6'], $ordernumber, '3', '', '')));
			exit;
			
		break;
		// Pickup
		case 7:
			
			// Send the email with bank details
			$mail = new PHPMailer(); // defaults to using php "mail()"
			$body = str_ireplace("[\]", '', JAK_THANKYOU_MESSAGE.'<br />'.$tl['shop']['m51'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
			$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
			$mail->AddAddress($safeemail, $safename);
			$mail->Subject = JAK_TITLE;
			$mail->MsgHTML($body);
			$mail->Send(); // Send email without any warnings
			
			// Send an email to the owner if wish so
			if (JAK_EMAIL) {
			
				$maila = new PHPMailer(); // defaults to using php "mail()"
				$bodya = str_ireplace("[\]", '', $tl['shop']['m51'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
				$maila->SetFrom(JAK_EMAIL, JAK_TITLE);
				$maila->AddAddress(JAK_EMAIL, $safename);
				$maila->Subject = JAK_TITLE.' - '.$tl['shop']['m53'];
				$maila->MsgHTML($bodya);
				$maila->Send(); // Send email without any warnings
				
			}
			
			// Finally Delete the shopping Cart
			$jakdb->query('DELETE FROM '.$jaktable6.' WHERE session = "'.smartsql($_SESSION['shopping_cart']).'"');
			
			jak_redirect(html_entity_decode(JAK_rewrite::jakParseurl($tl['shop']['m6'], $ordernumber, '4', '', '')));
			
		break;
		// PayZa Pay
		case 8:
		
			// Now we go with thru paypal and verify the payment
			
			// Include the paypal library
			include_once ('payment/payza.php');
			
			// Create an instance of the paypal library
			$myPayZa = new PayZa();
			
			// Specify your payza email
			$myPayZa->addField('ap_merchant', base64_decode($row_p['field1']));
			
			// Specify purchase type
			$myPayZa->addField('ap_purchasetype', 'item-goods');
			
			// Specify the product information
			$myPayZa->addField('ap_itemname', JAK_TITLE);
			$myPayZa->addField('ap_amount', $total_price);
			
			// Specify the currency
			$myPayZa->addField('ap_currency', $_SESSION['ECOMMERCE_CURRENCY']);
			
			// Specify the url where paypal will send the user on success/failure
			$myPayZa->addField('ap_returnurl', JAK_rewrite::jakParseurl($tl['link']['l8'], '', '', '', ''));
			$myPayZa->addField('ap_cancelurl', JAK_rewrite::jakParseurl($tl['link']['l9'], '', '', '', ''));
			
			// Specify the url where paypal will send the IPN
			$myPayZa->addField('ap_alerturl', BASE_URL.'payment/payza_ipn.php');
			$myPayZa->addField('ap_ipnversion', '2');
			
			// Specify any custom value
			$myPayZa->addField('apc_1', base64_encode($orderid.':#:'.$ordernumber.':#:'.$_SESSION['shopping_cart']));
			
			// Enable test mode if needed
			//$myPayZa->enableTestMode();
			
			$JAK_GO_PAY = $myPayZa->submitPayment($tl['shop']['m5']);
		 
		break;
		// Skrill (Moneybookers
		case 9:
		
			// Now we go with thru paypal and verify the payment
			
			// Include the paypal library
			include_once ('payment/skrill.php');
			
			// Create an instance of the paypal library
			$mySkrill = new Skrill();
			
			// Specify your skrill email
			$mySkrill->addField('pay_to_email', base64_decode($row_p['field1']));
			
			// Specify purchase type
			$mySkrill->addField('language', JAK_LANG);
			
			// Specify the product information
			$mySkrill->addField('detail1_description', JAK_TITLE);
			$mySkrill->addField('amount', $total_price);
			
			// Specify the currency
			$mySkrill->addField('currency', $_SESSION['ECOMMERCE_CURRENCY']);
			
			// Specify the url where paypal will send the user on success/failure
			$mySkrill->addField('return_url', JAK_rewrite::jakParseurl($tl['link']['l8'], '', '', '', ''));
			$mySkrill->addField('cancel_url', JAK_rewrite::jakParseurl($tl['link']['l9'], '', '', '', ''));
			
			// Specify the url where paypal will send the IPN
			$mySkrill->addField('status_url', BASE_URL.'payment/skrill_ipn.php');
			$mySkrill->addField('transaction_id', $ordernumber);
			
			// Specify any custom value
			$mySkrill->addField('merchant_fields', 'order_nr, session_id');
			$mySkrill->addField('order_nr', $orderid);
			$mySkrill->addField('session_id', $_SESSION['shopping_cart']);
			
			// Enable test mode if needed
			//$myPayZa->enableTestMode();
			
			$JAK_GO_PAY = $mySkrill->submitPayment($tl['shop']['m5']);
		 
		break;
		// Stripe
		case 10:
		
			$url_to_pay = (JAK_USE_APACHE ? substr(BASE_URL, 0, -1) : BASE_URL).JAK_rewrite::jakParseurl($tl['shop']['m6'], $ordernumber, '10', '', '');
		
			// Send the email with the checkout page to pay (also later)
			$mail = new PHPMailer(); // defaults to using php "mail()"
			$body = str_ireplace("[\]", '', JAK_THANKS.'<br />'.$tl['shop']['m8'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.$tl['shop']['m9'].base64_decode($row_p['field1']).'<br />'.$tl['shop']['m93'].$url_to_pay.'<br />'.$tl['shop']['m7'].$ordernumber);
			$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
			$mail->AddAddress($safeemail, $safename);
			$mail->Subject = JAK_TITLE;
			$mail->MsgHTML($body);
			$mail->Send(); // Send email without any warnings
			
			// Send an email to the owner if wish so
			if (JAK_SHOPEMAIL) {
			
				$maila = new PHPMailer(); // defaults to using php "mail()"
				$bodya = str_ireplace("[\]", '', $tl['shop']['m8'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.$tls['shop']['m9'].base64_decode($row_p['field1']).'<br />'.$tl['shop']['m93'].$url_to_pay.'<br />'.$tl['shop']['m7'].$ordernumber);
				$maila->SetFrom(JAK_EMAIL, JAK_TITLE);
				$maila->AddReplyTo($safeemail, $safename);
				$maila->AddAddress(JAK_EMAIL, JAK_TITLE);
				$maila->Subject = JAK_TITLE.' - '.$tl['shop']['m53'];
				$maila->MsgHTML($bodya);
				$maila->Send(); // Send email without any warnings
				
			}
			
			// Finally Delete the shopping Cart
			$jakdb->query('DELETE FROM '.$jaktable6.' WHERE session = "'.smartsql($_SESSION['shopping_cart']).'"');
			
			jak_redirect(html_entity_decode(JAK_rewrite::jakParseurl($tl['shop']['m6'], $ordernumber, '10', '', '')));
		 
		break;
		// Default is always bank transfer
		default:
		
			// Send the email with bank details
			$mail = new PHPMailer(); // defaults to using php "mail()"
			$body = str_ireplace("[\]", '', JAK_THANKYOU_MESSAGE.'<br />'.$tl['shop']['m8'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.$tl['shop']['m9'].base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
			$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
			$mail->AddAddress($safeemail, $safename);
			$mail->Subject = JAK_TITLE;
			$mail->MsgHTML($body);
			$mail->Send(); // Send email without any warnings
			
			// Send an email to the owner if wish so
			if (JAK_EMAIL) {
			
				$maila = new PHPMailer(); // defaults to using php "mail()"
				$bodya = str_ireplace("[\]", '', $tl['shop']['m8'].'<br /><br /><strong>'.$tl['shop']['m'].'</strong>'.$total_price.' '.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><br />'.$tls['shop']['m9'].base64_decode($row_p['field1']).'<br />'.$tl['shop']['m7'].$ordernumber);
				$maila->SetFrom(JAK_EMAIL, JAK_TITLE);
				$maila->AddReplyTo($safeemail, $safename);
				$maila->AddAddress(JAK_EMAIL, JAK_TITLE);
				$maila->Subject = JAK_TITLE.' - '.$tl['shop']['m53'];
				$maila->MsgHTML($bodya);
				$maila->Send(); // Send email without any warnings
				
			}
			
			// Finally Delete the shopping Cart
			$jakdb->query('DELETE FROM '.$jaktable6.' WHERE session = "'.smartsql($_SESSION['shopping_cart']).'"');
			
			jak_redirect(html_entity_decode(JAK_rewrite::jakParseurl($tl['shop']['m6'], $ordernumber, '1', '', '')));
	}

} else {
	$errors = $errors;
}

}

$PAGE_TITLE = $tl['shop']['m29'];

// Get Country list for tax
$getcountry = $shopping_cart->getCountry(239, $customerl->getVar("country"));

// License Agreement		
$AGREEMENT_NAME = $tl['general']['g13'];
$AGREEMENT_URL = JAK_AGREEMENT;

// Get the Payment Details
$result = $jakdb->query('SELECT id, field, fees FROM '.$jaktable1.' WHERE status = 1 ORDER BY msporder ASC');
while ($row = $result->fetch_assoc()) {

	$fees = '';
	
	if ($row['fees']) {
		
		$fees = ' ('.$tl['shop']['m23'].$row['fees'].'%)';
	
	}
	    
	$payment_option[] = array('radio' => '<input type="radio" name="payment_option" value="'.$row['fees'].':#:'.$row['id'].'" /> '.$row['field'].$fees.'<br />');

}

$result = $jakdb->query('SELECT SUM(weight) AS total_weight FROM '.DB_PREFIX.'shopping_cart WHERE session = "'.smartsql($_SESSION['shopping_cart']).'"');
$row = $result->fetch_assoc();

// Get the Shipping Details
$result = $jakdb->query('SELECT t1.id, t1.title, t1.est_shipping, t1.price, t1.handling, t2.name FROM '.$jaktable4.' AS t1 LEFT JOIN '.DB_PREFIX.'shop_country AS t2 ON (t1.country = t2.id) WHERE status = 1 AND (weightfrom <= "'.$row['total_weight'].'" AND weightto >= "'.$row['total_weight'].'") OR (weightfrom = 0.000 AND weightto = 0.000)');
while ($row = $result->fetch_assoc()) {

	$finalprice = $row['price'] + $row['handling'];
	
	if ($_SESSION['ECOMMERCE_CURRENCY'] != JAK_CURRENCY) {
	
		$finalprice = $convert->Convert($finalprice, $_SESSION['ECOMMERCE_CURRENCY']);
		
	}
	    
	$shipping_option[] = array('select' => '<option value="'.$finalprice.':#:'.$row['est_shipping'].'" />'.$row['name'].' - '.$row['title'].' ('.$tl['shop']['m'].$finalprice.' '.$_SESSION['ECOMMERCE_CURRENCY'].')');

}

// Get the url session
$_SESSION['jak_lastURL'] = JAK_rewrite::jakParseurl('checkout', '', '', '', '');

// Fire the template
$template = 'checkout.php';
?>