<?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('ajax/[addtocart.php] config.php not exist');
}
require_once '../config.php';

require_once '../class/shopping_cart.php';

if (!file_exists('../class/currency_converter.php')) {
    die('ajax/[addtocart.php] currency_converter.php not exist');
}
require_once '../class/currency_converter.php';


if(!$_SERVER['HTTP_X_REQUESTED_WITH']) {
	die("Nothing to see here");
}

if (!$_POST['id'] && !is_numeric($_POST['id'])) die("There is no such product!");

$result = $jakdb->query('SELECT id, title, content, price, sale, stock, product_weight, previmg, product_options, product_options1, product_options2 FROM '.DB_PREFIX.'shop WHERE id = "'.smartsql($_POST['id']).'" AND active = 1 AND stock > 0');
$row = $result->fetch_assoc();

if(!$row) die(json_encode(array('status' => 0)));

if (JAK_SHOPQUANTITY) {
	
	$resultq = $jakdb->query('SELECT COUNT(*) AS totalProduct FROM '.DB_PREFIX.'shopping_cart WHERE session = "'.smartsql($_SESSION["shopping_cart"]).'" AND shopid = "'.smartsql($_POST['id']).'" GROUP BY shopid');
	$rowq = $resultq->fetch_assoc();
	
	if ($row['stock'] <= $rowq['totalProduct']) die(json_encode(array('status' => 0)));
}

// Import the language file
if (file_exists(APP_PATH.'lang/'.JAK_LANG.'.ini')) {
    $tl = parse_ini_file(APP_PATH.'lang/'.JAK_LANG.'.ini', true);
} else {
    $tl = parse_ini_file(APP_PATH.'lang/en.ini', true);
} 

// Run Option 1
if ($_POST['popt']) {

$poption = explode(",", $row['product_options']);

for ($i = 0; $i < count($poption); $i++) { 

if (in_array($_POST['popt'], $poption)) {

	$optearray = explode('::', $_POST['popt']);
	
	// Display Option Name
	$woption = $optearray[0];
	// Option Name
	$cid = JAK_base::jakCleanurl($optearray[0]);
	// Option Price
	$optpr = $optearray[1];
	// Option Weight
	$optweight = $optearray[2];
}

}

}

// Run Option 2
if ($_POST['popt1']) {

$poption1 = explode(",", $row['product_options1']);

for ($i = 0; $i < count($poption1); $i++) { 

if (in_array($_POST['popt1'], $poption1)) {

	$optearray1 = explode('::', $_POST['popt1']);
	
	// Display Option Name
	$woption1 = ' '.$optearray1[0];
	// Option Name
	$cid1 = JAK_base::jakCleanurl($optearray1[0]);
	// Option Price
	$optpr1 = $optearray1[1];
	// Option Weight
	$optweight1 = $optearray1[2];
}

}

}


// Run Option 3
if ($_POST['popt2']) {

$poption2 = explode(",", $row['product_options2']);

for ($i = 0; $i < count($poption2); $i++) { 

if (in_array($_POST['popt2'], $poption2)) {

	$optearray2 = explode('::', $_POST['popt2']);
	
	// Display Option Name
	$woption2 = ' '.$optearray2[0];
	// Option Name
	$cid2 = JAK_base::jakCleanurl($optearray2[0]);
	// Option Price
	$optpr2 = $optearray2[1];
	// Option Weight
	$optweight2 = $optearray2[2];
}

}

}

// Rewrite path once for the image
$real_base = str_replace('ajax/', '', BASE_URL);

// Image is available so display it or go standard
if ($row['previmg']) {
	$imge = $real_base.$row['previmg'];
} else {
	$imge = $real_base.'img/no_product_photo.png';
}

// Sale is active overwrite price to save some vars
if ($row['sale'] != "0.00") {
	$row['price'] = $row['sale'];
	$tl["shop"]["m"] = $tl["shop"]["m31"];
}

// Options have some price differents!
if ($optpr || $optpr1 || $optpr2) {

	$row['price'] += floatval($optpr);
	
	$row['price'] += floatval($optpr1);
	
	$row['price'] += floatval($optpr2);
	
	$row['price'] = number_format($row['price'], 2, '.', '');

}

// Options have some weight differents!
if ($row['product_weight'] || $optweight || $optweight1 || $optweight2) {

	$row['product_weight'] += floatval($optweight);
	
	$row['product_weight'] += floatval($optweight1);
	
	$row['product_weight'] += floatval($optweight2);
	
	$weight = number_format($row['product_weight'], 3, '.', '');

}

// Uh, we got some different currency then standard, well we need to change
if ($_SESSION['ECOMMERCE_CURRENCY'] != JAK_CURRENCY) {

	$convert = new CurrencyConverter();
		
	$row['price'] = $convert->Convert($row['price'], $_SESSION['ECOMMERCE_CURRENCY']);

}

// Make the option look nice
if ($woption || $woption1 || $woption2) {

	$optarray = $woption.$woption1.$woption2;
	$optarray = trim($optarray);
	$optarray = explode(" ", $optarray);
	$comma_separated = join(",", $optarray);

	$optionlist = 'Option(s): '.$comma_separated;

}

// If optionlist do some cosmetic
if ($optionlist) $brspace = '<br />';

// Start the shopping cart
$shopping_cart = new Shopping_Cart();
$shopping_cart->writeInto($row['id'], $optionlist, $row['id'].$cid.$cid1.$cid2, $row['price'], $weight);

die(json_encode(array('status' => 1, 'id' => $row['id'].$cid.$cid1.$cid2, 'price' => $row['price'], 'txt' => '<figure class="product-inbasket" id="pib_'.$row['id'].$cid.$cid1.$cid2.'">
  	<img src="'.$imge.'" alt="'.$row['title'].'" />
    <h3><span id="'.$row['id'].$cid.$cid1.$cid2.'_count"></span> x '.$row["title"].'</h3>
    <p>'.$optionlist.$brspace.$tl["shop"]["m"].$row['price'].'&nbsp;'.$_SESSION['ECOMMERCE_CURRENCY'].'<br /><a href="#" class="remove" onclick="removeItem(\''.$row['id'].$cid.$cid1.$cid2.'\');return false;">remove</a></p></figure>')));
?>