<?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_ADMIN_PREVENT_ACCESS')) die('You cannot access this file directly.');

// Check if the user has access to this file
if (!JAK_USERID || !JAK_ADMINACCESS) jak_redirect(BASE_URL);

// All the tables we need for this plugin
$errors = array();
$jaktable = DB_PREFIX.'shop';
$jaktable1 = DB_PREFIX.'shop_order';
$jaktable2 = DB_PREFIX.'pagesgrid';
$jaktable3 = DB_PREFIX.'pluginhooks';
$jaktable4 = DB_PREFIX.'shop_payment';
$jaktable5 = DB_PREFIX.'shop_payment_ipn';
$jaktable7 = DB_PREFIX.'shop_shipping';
$jaktable8 = DB_PREFIX.'shop_order_details';
$jaktable9 = DB_PREFIX.'categories';

// Get the data per id
function jak_get_payment($table, $id, $status) 
{

	if ($id) {
	
		$sqlw = ' WHERE id = '.$id.'';
	}
	
	if ($status) {
	
		$sqlw = ' WHERE status = 1';
	}
	
	global $jakdb;
    $sql = 'SELECT * FROM '.$table.$sqlw.' ORDER BY msporder ASC';
    $result = $jakdb->query($sql);
    while ($row = $result->fetch_assoc()) {
            // collect each record into $_data
            $jakdata[] = array('id' => $row['id'], 'title' => $row['title'], 'field' => $row['field'], 'field1' => base64_decode($row['field1']), 'field2' => base64_decode($row['field2']), 'field3' => $row['field3'], 'fees' => $row['fees'], 'status' => $row['status'], 'msporder' => $row['msporder']);
        }

    return $jakdata;
}

function jak_get_shipping($table, $id, $status) 
{

	if ($id) {
	
		$sqlw = ' WHERE t1.id = '.$id.'';
	}
	
	if ($status) {
	
		$sqlw = ' WHERE t1.status = 1';
	}
	
	global $jakdb;
    $sql = 'SELECT t1.id, t1.title, t1.price, t1.time, t1.status, t2.name FROM '.$table.' AS t1 LEFT JOIN '.DB_PREFIX.'shop_country AS t2 ON (t1.country = t2.id)'.$sqlw.' ORDER BY t1.title ASC';
    $result = $jakdb->query($sql);
    while ($row = $result->fetch_assoc()) {
            // collect each record into $_data
            $jakdata[] = $row;
        }

    return $jakdata;
}

function jak_get_shop_orders($limit, $search_term, $check_row, $paid) 
{
	if (empty($check_row)) {
		$sqlwhere = '';
	} else {
		$sqlwhere = 'WHERE '.$check_row.' = "'.$search_term.'" AND paid = '.$paid.' ';
	}
	
	global $jakdb;
    $sql = 'SELECT id, paid_method, email paidtime, time, ordernumber, paid, paidtime, order_booked FROM '.DB_PREFIX.'shop_order '.$sqlwhere.'ORDER BY time DESC '.$limit.'';
    $result = $jakdb->query($sql);
    while ($row = $result->fetch_assoc()) {
    
    	if (!empty($row['paidtime'])) {
    		$paidtime = $row['paidtime'];
    	} else {
    		$paidtime = '';
    	}
    	
        $jakdata[] = array('id' => $row['id'], 'paid_method' => $row['paid_method'], 'ordertime' => $row['time'], 'ordernumber' => $row['ordernumber'], 'paid' => $row['paid'], 'paidtime' => $row['paidtime'], 'booked' => $row['order_booked']);
    }
    return $jakdata;
}

// Now start with the plugin use a switch to access all pages
switch ($page1) {

	// Create new shop
	case 'newitem':
		
		// Get the important template stuff
		$JAK_CAT = jak_get_cat_info($jaktable9, 0);
				
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		    $defaults = $_POST;
		    
		    if (isset($defaults['save'])) {
		
		    if (empty($defaults['jak_title'])) {
		        $errors['e1'] = $tl['error']['e2'];
		    }
		    
		    if ($defaults['jak_price'] == '') {
		        $errors['e3'] = $tl['shop']['e'];
		    }
		    
		    if (isset($defaults['jak_showdate'])) {
		    	$showdate = $defaults['jak_showdate'];
		    } else {
		    	$showdate = '0';
		    }
		    
		    if (isset($defaults['jak_showhome'])) {
		    	$showhome = $defaults['jak_showhome'];
		    } else {
		    	$showhome = '0';
		    }
		    
		    if (count($errors) == 0) {
		    
		    if (!empty($defaults['jak_img'])) {
		    	$insert .= 'previmg = "'.$defaults['jak_img'].'",';
		    }
		    
		    if (!empty($defaults['jak_mimg'])) {
		    	$insert .= 'img = "'.$defaults['jak_mimg'].'",';
		    }
		    
		    if (!empty($defaults['jak_file'])) {
		    	$insert .= 'digital_file = "'.$defaults['jak_file'].'",';
		    }
		
		$sql = 'INSERT INTO '.$jaktable.' SET 
		catid = "'.$defaults['jak_catid'].'",
		title = "'.smartsql($defaults['jak_title']).'",
		content = "'.smartsql($defaults['jak_content']).'",
		product_home = '.$showhome.',
		showdate = '.$showdate.',
		price = "'.smartsql($defaults['jak_price']).'",
		sale = "'.smartsql($defaults['jak_sale']).'",
		product_weight = "'.smartsql($defaults['jak_weight']).'",
		stock = "'.smartsql($defaults['jak_stock']).'",
		product_options = "'.smartsql($defaults['jak_poption']).'",
		product_options1 = "'.smartsql($defaults['jak_poption1']).'",
		product_options2 = "'.smartsql($defaults['jak_poption2']).'",
		'.$insert.'
		time = NOW()';
		$result = $jakdb->query($sql);
		
		$row['id'] = $jakdb->jak_last_id();
		
		if ($defaults['jak_catid'] != 0) {
		
			$jakdb->query('UPDATE '.$jaktable9.' SET count = count + 1 WHERE id = '.$defaults['jak_catid']);			
		}
		
		if (!$result) {
		    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
			} else {		
		        jak_redirect(BASE_URL.'index.php?p=success');
		    }
		 } else {
		    
		   	$errors['e'] = $tl['error']['e'];
		    $errors = $errors;
		    }
		}
		}
		
		// Call the template
		$template = 'newitem.php';
	
	break;
	case 'payment':
	
		// Important Smarty Stuff
		$JAK_PAYMENT_ALL = jak_get_payment($jaktable4, '', '');
		
		switch ($page2) {
		 
		case 'lock':
			
			$sql = 'UPDATE '.$jaktable4.' SET status = IF (status = 1, 0, 1) WHERE id = "'.smartsql($page3).'"';
		    	$result = $jakdb->query($sql);
		    	
		if (!$result) {
			jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
		} else {
			
		    jak_redirect(BASE_URL.'index.php?p=success');
		}
			
		break;
		case 'edit';
		
			if (jak_row_exist($page3, $jaktable4)) {
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		    $defaults = $_POST;
		
		    if (empty($defaults['jak_field'])) {
		        $errors['e1'] = $tl['error']['e2'];
		    }
		    
		    if (empty($defaults['jak_field1'])) {
		        $errors['e2'] = $tl['error']['e32'];
		    }
		        
		    if (count($errors) == 0) {
		    
		    if (!empty($defaults['jak_field2'])) {
		    	$insert .= 'field2 = "'.base64_encode($defaults['jak_field2']).'",';
		    }
		
			$sql = 'UPDATE '.$jaktable4.' SET 
			field = "'.smartsql($defaults['jak_field']).'",
			field1 = "'.base64_encode($defaults['jak_field1']).'",
			'.$insert.'
			fees = "'.smartsql($defaults['jak_fees']).'"
			WHERE id = "'.smartsql($page3).'"';
			$result = $jakdb->query($sql);
		
		if (!$result) {
		    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
			} else {
				
		        jak_redirect(BASE_URL.'index.php?p=success');
		    }
		 } else {
		 
		    $errors = $errors;
		    }
		}
		
		$JAK_FORM_DATA = jak_get_data($page3, $jaktable4);
		$template = 'editpayment.php';
		
		} else {
		    
		   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
		}
		break;
		default:
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			        $defaults = $_POST;
			        
			                $categories = $defaults['corder'];
			                $catid = $defaults['real_mp_id'];
			                $realid = implode(',', $defaults['real_mp_id']);
			                $test = array_combine($catid, $categories);
			                
			                foreach ($test as $key => $category) {
			                $updatesql .= sprintf("WHEN %d THEN %d ", $key, $category);
			            	}
			            	
			            	$sql = 'UPDATE '.$jaktable4.' SET msporder = CASE id
			        		'.$updatesql.'
			        		END
							WHERE id IN ('.$realid.')';
			                $result = $jakdb->query($sql);
			                
			                if (!$result) {
								jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
							} else {
								jak_redirect(BASE_URL.'index.php?p=success');
			    }
			       
			    }
			    
			    // Call the template
			    $template = 'payment.php';
			    
		    break;
		    }
		
	break;
	case 'orders':
		
		switch ($page2) {
		
			case 'edit':
			
				if (is_numeric($page3) && jak_row_exist($page3, $jaktable1)) {
				
					if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				    $defaults = $_POST;
				
				    if (empty($defaults['jak_ordernr'])) {
				        $errors['e1'] = $tl['error']['e2'];
				    }
				    
				    if ($defaults['jak_price'] == '') {
				        $errors['e2'] = $tl['shop']['e'];
				    }
				    
				    if (count($errors) == 0) {
				    
				
					$sql = 'UPDATE '.$jaktable1.' SET 
					paid_method = '.$defaults['jak_payment'].',
					total_price = "'.smartsql($defaults['jak_price']).'",
					tax = "'.smartsql($defaults['jak_tax']).'",
					shipping = "'.smartsql($defaults['jak_shipping']).'",
					freeshipping = '.$defaults['jak_freeshipping'].',
					currency = "'.smartsql($defaults['jak_currency']).'",
					company = "'.smartsql($defaults['jak_company']).'",
					name = "'.smartsql($defaults['jak_name']).'",
					address = "'.smartsql($defaults['jak_address']).'",
					zip_code = "'.smartsql($defaults['jak_zip']).'",
					city = "'.smartsql($defaults['jak_city']).'",
					country = "'.smartsql($defaults['jak_country']).'",
					phone = "'.smartsql($defaults['jak_phone']).'",
					email = "'.smartsql($defaults['jak_email']).'",
					sh_company = "'.smartsql($defaults['jak_sh_company']).'",
					sh_name = "'.smartsql($defaults['jak_sh_name']).'",
					sh_address = "'.smartsql($defaults['jak_sh_address']).'",
					sh_zip_code = "'.smartsql($defaults['jak_sh_zip']).'",
					sh_city = "'.smartsql($defaults['jak_sh_city']).'",
					sh_country = "'.smartsql($defaults['jak_sh_country']).'",
					sh_phone = "'.smartsql($defaults['jak_sh_phone']).'",
					ordernumber = "'.smartsql($defaults['jak_ordernr']).'"
					WHERE id = "'.smartsql($page3).'"';
					$result = $jakdb->query($sql);
				
				if (!$result) {
				
				    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				        
					} else {
				
				        jak_redirect(BASE_URL.'index.php?p=success');
				    }
					    
				 } else {
				    
				   	$errors['e'] = $tl['error']['e'];
				    $errors = $errors;
				    }
				}
				
				$JAK_FORM_DATA = jak_get_data($page3, $jaktable1);
				
				$result_option = $jakdb->query('SELECT COUNT(id) AS total_item, title, product_option, price, coupon_price FROM '.$jaktable8.' WHERE orderid = '.$JAK_FORM_DATA['id'].' GROUP BY shopid, product_option ORDER BY price ASC');
				
				while ($row_option = $result_option->fetch_assoc()) {
				
					$row_option['price'] = $row_option['total_item'] * $row_option['price'];
					
					$row_option['price'] = number_format($row_option['price'], 2, '.', '');
					
				    $jak_ordered[] = array('title' => $row_option['title'], 'product_option' => $row_option['product_option'], 'price' => $row_option['price'], 'coupon_price' => number_format($row_option['coupon_price'], 2, '.', ''), 'total_item' => $row_option['total_item']);
				}
				
				// Get the right Country
				$JAK_COUNTRY = getCountry($JAK_FORM_DATA['country'], '');
				$JAK_SHCOUNTRY = getCountry($JAK_FORM_DATA['sh_country'], '');
				
				// Get the payment modules
				$JAK_PAYMENT_ALL = jak_get_payment($jaktable4, '', '');
								
				$template = 'editorder.php';
				
				} else {
				    
				   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
				}
			
			break;
		 	case 'paid':
		 		
		 		if (is_numeric($page3) && jak_row_exist($page3, $jaktable1)) {
		 		
		 			if ($page4) {
		 				
		 				$sql = 'UPDATE '.$jaktable1.' SET paid = 0, paidtime = NULL WHERE id = "'.smartsql($page3).'"';
		 			
		 			} else {
		 				
		 				$sql = 'UPDATE '.$jaktable1.' SET paid = 1, paidtime = NOW() WHERE id = "'.smartsql($page3).'"';
		 				
		 			}
		 			
		 		$result = $jakdb->query($sql);
		 	        	
		 		if (!$result) {
		 	    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
		 		} else {
		 	        jak_redirect(BASE_URL.'index.php?p=success');
		 	    }
		 	    
		 		} else {
		 	    
		 	   		jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
		 		}
		 	
		 break;
		 case 'isbooked':
		 		
		 		if (is_numeric($page3) && jak_row_exist($page3, $jaktable1)) {
		 		
		 		if ($page4) {
		 				
		 			$sql = 'UPDATE '.$jaktable1.' SET order_booked = 0 WHERE id = "'.smartsql($page3).'"';
		 			
		 		} else {
		 			
		 			$sql = 'UPDATE '.$jaktable1.' SET order_booked = 1 WHERE id = "'.smartsql($page3).'"';
		 		
		 		}
		 		
		 		$result = $jakdb->query($sql);
		 	        	
		 		if (!$result) {
		 	    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
		 		} else {
		 	        jak_redirect(BASE_URL.'index.php?p=success');
		 	    }
		 	    
		 		} else {
		 	    
		 	   		jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
		 		}
		 	
		 break;
		 case 'email':
		 	
		 		if (jak_row_exist($page3, $jaktable1)) {
		 			
		 			$result = $jakdb->query('SELECT email, name FROM '.$jaktable1.' WHERE id = '.smartsql($page3));
		 			$row = $result->fetch_assoc();
		 			
		 			$mail = new PHPMailer(); // defaults to using php "mail()"
		 			$body = file_get_contents('../payment.html');
		 			$body = str_ireplace("[\]",'',$body);
		 			$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
		 			$address = $row['email'];
		 			$mail->AddAddress($address, $row['name']);
		 			$mail->Subject = JAK_TITLE.' - '.$tl['shop']['m38'];
		 			$mail->AltBody = $tl['shop']['m39'];
		 			$mail->MsgHTML($body);
		 			
		 			if ($mail->Send()) {
		 				jak_redirect(BASE_URL.'index.php?p=success');
		 			}
		 		} else {
		 		    
		 		   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
		 		}
		 		
		break;
		case 'digital':
		
			if (jak_row_exist($page3, $jaktable1)) {
			
				$send_email = 0;
			
				$result = $jakdb->query('SELECT email, name, ordernumber FROM '.$jaktable1.' WHERE id = '.smartsql($page3));
				$row = $result->fetch_assoc();
			
				$result_option = $jakdb->query('SELECT t2.title, t2.digital_file, t2.id FROM '.$jaktable8.' AS t1 LEFT JOIN '.$jaktable.' AS t2 ON (t1.shopid = t2.id) WHERE t1.orderid = "'.smartsql($page3).'" AND t2.digital_file != "" GROUP BY t1.shopid ');
				
				while ($row_option = $result_option->fetch_assoc()) {
				
					$getfile = str_replace("//", "/", "../".$row_option['digital_file']);
					$download_link = '';
					$getAttach = '';
					
					// if the filesize is smaller then 2mb send attach it
					if (round(filesize($getfile) / 1024, 0) <= 2048) {
						
						$getAttachBase = basename($getfile);
						$getAttach = str_replace("//", "/", "../".$row_option['digital_file']);
					
					// if file size is bigger then 2mb create download link
					} else {
					
						$downloadid = time();
					
						$jakdb->query('UPDATE '.$jaktable1.' SET 
						downloadid = "'.$downloadid.'",
						downloadtime = ADDDATE(NOW(), INTERVAL 7 DAY)
						WHERE id = "'.smartsql($page3).'"');
						
						// Create download link
						if (JAK_USE_APACHE) {
							$dflink = str_replace('/admin/', '', JAK_rewrite::jakParseurl('dl', $row['ordernumber'], $row_option['id'], $downloadid, ''));
						} else {
							$dflink = JAK_rewrite::jakParseurl('dl', $row['ordernumber'], $row_option['id'], $downloadid, '');
						}
						
						$download_link = '<p>'.$tl["shop"]["m75"].'<a href="'.BASE_URL_ORIG.$dflink.'">'.$tl["shop"]["m76"].'</a></p>';
						
					}
					
					$body = '<body style="margin:10px;">
					<div style="width:750px; font-family: \'Droid Serif\', Helvetica, Arial, sans-serif; font-size: 14px;">
					<div align="center"><img src="'.BASE_URL_ORIG.'img/header.jpg" style="height: 90px; width: 750px"></div>
					<p>
					'.$tl["shop"]["m73"].'
					</p>
					'.$download_link.'
					<p>
					'.$tl["shop"]["m74"].'
					</p>
					<p>'.JAK_TITLE.'</p>
					</div>
					</body>';
					
				    $mail = new PHPMailer(); // defaults to using php "mail()"
				    $body = str_ireplace("[\]",'',$body);
				  	$mail->SetFrom(JAK_EMAIL, JAK_TITLE);
				    $mail->AddAddress($row['email'], $row['name']);
				    $mail->Subject = JAK_TITLE.' - '.$tl['shop']['m9'].' - '.$row_option['title'];
				    $mail->AltBody = $tl['shop']['m39'];
				    if ($getAttach) $mail->AddAttachment($getAttach, $getAttachBase);
				    $mail->MsgHTML($body);
				    $mail->Send(); // Send email without any warnings
				    
				    $send_email = 1;
				    
				}
				
				if ($send_email) {
					jak_redirect(BASE_URL.'index.php?p=success');
				} else {
					jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
				}
			
			} else {
			    
			   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
			}
		
		break;
		case 'delete':
			
			if (jak_row_exist($page3, $jaktable1)) {
			
		    	$sql = 'DELETE FROM '.$jaktable1.' WHERE id = '.smartsql($page3).'';
				$result = $jakdb->query($sql);
				
				$jakdb->query('DELETE FROM '.$jaktable8.' WHERE orderid = '.smartsql($page3));
		        	
				if (!$result) {
		    		jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
				
		        	jak_redirect(BASE_URL.'index.php?p=success');
		    	}
		    
			} else {
		    
		   		jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
			}
		break;
		case 'invoice':
		
			if (is_numeric($page3)) {
			
				$result = $jakdb->query('SELECT * FROM '.$jaktable1.' WHERE id = "'.smartsql($page3).'"');
				$row = $result->fetch_assoc();
				
				$result_option = $jakdb->query('SELECT COUNT(id) AS total_item, title, product_option, price, coupon_price FROM '.$jaktable8.' WHERE orderid = '.$row['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 = getCountry('', $row['country']);
				$JAK_SHCOUNTRY = getCountry('', $row['sh_country']);
		
				// Call the template
				$template = 'invoice.php';
			
			} else {
			
				jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
			}
		
		break;
		case 'booked':
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			    $defaults = $_POST;
			    
			    if (isset($defaults['delete'])) {
			    
			    $lockuser = $defaults['jak_delete_order'];
			
			        for ($i = 0; $i < count($lockuser); $i++) {
			            $locked = $lockuser[$i];
			            
			            $sql = 'DELETE FROM '.$jaktable1.' WHERE id = '.$locked.'';
						$result = $jakdb->query($sql);
			        	
			        }
			  
			 	if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
					
			        jak_redirect(BASE_URL.'index.php?p=success');
			    }
			    
			    }
			    
			    if (isset($defaults['search'])) {
			    
			        if (strlen($defaults['jakSH']) < '1') {
			            $errors['e1'] = $tl['shop']['s1'];
			        }
			    
			        if (count($errors) > 0) {
			        
			        	$errors['e'] = $tl['shop']['s2'].'<br />';
			            
			        } else {
			        
			            $secureIn = smartsql($defaults['jakSH']);
			            $SEARCH_WORD = $secureIn;
			            $JAK_ORDERS = jak_get_shop_orders('', $secureIn, 'ordernumber', 0);
			            
			        }
			        }
			
			 } else {
			
			$getTotal = jak_get_total($jaktable1, 1, 'order_booked', 'paid');
			
			if ($getTotal != 0) {
				// Paginator
				$pages = new Paginator;
				$pages->items_total = $getTotal;
				$pages->mid_range = 5;
				$pages->items_per_page = 20;
				$pages->jak_get_page = $page3;
				$pages->jak_where = 'index.php?p=shop&sp=orders&ssp=booked';
				$pages->paginate();
				
				$JAK_PAGINATE = $pages->display_pages();
			}
			
			$JAK_ORDERS = jak_get_shop_orders($pages->limit, 1, 'order_booked', 1);
			
			}
			
			// Call the template
			$template = 'orders.php';
		
		break;
		case 'orders-paid':
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			    $defaults = $_POST;
			    
			    if (isset($defaults['delete'])) {
			    
			    $lockuser = $defaults['jak_delete_order'];
			
			        for ($i = 0; $i < count($lockuser); $i++) {
			            $locked = $lockuser[$i];
			            
			            $sql = 'DELETE FROM '.$jaktable1.' WHERE id = '.$locked.'';
						$result = $jakdb->query($sql);
			        	
			        }
			  
			 	if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
					
			        jak_redirect(BASE_URL.'index.php?p=success');
			    }
			    
			    }
			    
			    if (isset($defaults['search'])) {
			    
			        if (strlen($defaults['jakSH']) < '1') {
			            $errors['e1'] = $tl['shop']['s1'];
			        }
			    
			        if (count($errors) > 0) {
			        
			        	$errors['e'] = $tl['shop']['s2'].'<br />';
			            
			        } else {
			        
			            $secureIn = smartsql($defaults['jakSH']);
			            $SEARCH_WORD = $secureIn;
			            $JAK_ORDERS = jak_get_shop_orders('', $secureIn, 'ordernumber', 1);
			            
			        }
			        }
			
			 } else {
			
			$getTotal = jak_get_total($jaktable1, 0, 'order_booked', 'paid');
			
			if ($getTotal != 0) {
				// Paginator
				$pages = new Paginator;
				$pages->items_total = $getTotal;
				$pages->mid_range = 5;
				$pages->items_per_page = 20;
				$pages->jak_get_page = $page3;
				$pages->jak_where = 'index.php?p=shop&sp=orders&ssp=orders-paid';
				$pages->paginate();
				
				$JAK_PAGINATE = $pages->display_pages();
			}
			
			$JAK_ORDERS = jak_get_shop_orders($pages->limit, 0, 'order_booked', 1);
			
			}
			
			// Call the template
			$template = 'orders.php';
		
		break;
		default:
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			    $defaults = $_POST;
			    
			    if (isset($defaults['delete'])) {
			    
			    $lockuser = $defaults['jak_delete_order'];
			
			        for ($i = 0; $i < count($lockuser); $i++) {
			            $locked = $lockuser[$i];
			            
			            $sql = 'DELETE FROM '.$jaktable1.' WHERE id = '.$locked.'';
						$result = $jakdb->query($sql);
			        	
			        }
			  
			 	if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
					
			        jak_redirect(BASE_URL.'index.php?p=success');
			    }
			    
			    }
			    
			    if (isset($defaults['search'])) {
			    
			        if (strlen($defaults['jakSH']) < '1') {
			            $errors['e1'] = $tl['shop']['s1'];
			        }
			    
			        if (count($errors) > 0) {
			        
			        	$errors['e'] = $tl['shop']['s2'].'<br />';
			            
			        } else {
			        
			            $secureIn = smartsql($defaults['jakSH']);
			            $SEARCH_WORD = $secureIn;
			            $JAK_ORDERS = jak_get_shop_orders('', $secureIn, 'ordernumber', 0);
			            
			        }
			        }
			
			 } else {
			
			$result = $jakdb->query('SELECT COUNT(*) as totalAll FROM '.$jaktable1.' WHERE order_booked = 0 AND paid = 0');
			$row = $result->fetch_assoc();
			
			if ($row['totalAll'] != 0) {
				// Paginator
				$pages = new Paginator;
				$pages->items_total = $row['totalAll'];
				$pages->mid_range = 5;
				$pages->items_per_page = 20;
				$pages->jak_get_page = $page2;
				$pages->jak_where = 'index.php?p=shop&sp=orders';
				$pages->paginate();
				
				$JAK_PAGINATE = $pages->display_pages();
			}
			
			$JAK_ORDERS = jak_get_shop_orders($pages->limit, 0, 'order_booked', 0);
			
			}
			
			// Get the months statistic
			$resultst1 = $jakdb->query('SELECT MONTHNAME(paidtime) AS mtime, YEAR(paidtime) AS ytime, MONTH(paidtime) AS ptime FROM '.$jaktable1.' WHERE paid = 1 GROUP BY mtime ORDER BY MONTH(paidtime) ASC LIMIT 12');
			if ($jakdb->affected_rows > 0) {
			while ($rowst1 = $resultst1->fetch_assoc()) {
			        
			        // get the days in one table
			        $arraymonth[] = $rowst1['mtime'].' '.$rowst1['ytime'];
			        $arraymonthnumber[] = $rowst1['ptime'];
			    }
			    
			    $arraymonth = array_unique($arraymonth);
			    $arraymonthnumber = array_unique($arraymonthnumber);
			}
			
			// Get the months statistic
			$resultst12 = $jakdb->query('SELECT SUM(total_price) AS earning, MONTH(paidtime) AS ptime FROM '.$jaktable1.' WHERE paid = 1 AND currency = "'.JAK_CURRENCY.'" GROUP BY ptime ORDER BY MONTH(paidtime) ASC LIMIT 12');
			if ($jakdb->affected_rows > 0) {
			while ($rowst12 = $resultst12->fetch_assoc()) { 
			        
			        // get the days in one table
			        $fostat2p[] = $rowst12['ptime'];
			        $fostat2[] = $rowst12['earning'];
			    }
			    
			    $fostat2 = array_combine($fostat2p,$fostat2);
			}
			
			if (JAK_CURRENCY1) {
				
				// Currency Two
				$currency_two = explode('/', JAK_CURRENCY1);
				
				// Get the months statistic
				$resultst13 = $jakdb->query('SELECT SUM(total_price) AS earning, MONTH(paidtime) AS ptime FROM '.$jaktable1.' WHERE paid = 1 AND currency = "'.$currency_two[0].'" GROUP BY ptime ORDER BY MONTH(paidtime) ASC LIMIT 12');
				if ($jakdb->affected_rows > 0) {
				while ($rowst13 = $resultst13->fetch_assoc()) { 
				        
				        // get the days in one table
				        $fostat21p[] = $rowst13['ptime'];
				        $fostat21[] = $rowst13['earning'];
				    }
				    
				    $fostat21 = array_combine($fostat21p,$fostat21);
				}
			}
			
			// Create a array with all three currency
			if (JAK_CURRENCY2) {	
					
				// Currency Three
				$currency_three = explode('/', JAK_CURRENCY2);
				
				// Get the months statistic
				$resultst14 = $jakdb->query('SELECT SUM(total_price) AS earning, MONTH(paidtime) AS ptime FROM '.$jaktable1.' WHERE paid = 1 AND currency = "'.$currency_three[0].'" GROUP BY ptime ORDER BY MONTH(paidtime) ASC LIMIT 12');
				if ($jakdb->affected_rows > 0) {
				while ($rowst14 = $resultst14->fetch_assoc()) { 
				        
				        // get the days in one table
				        $fostat22p[] = $rowst14['ptime'];
				        $fostat22[] = $rowst14['earning'];
				    }
				    
				    $fostat22 = array_combine($fostat22p,$fostat22);
				}
				
			}
			
			// Sanitize the data
			if (!empty($arraymonth) && !empty($arraymonthnumber)) {
				
				foreach ($arraymonthnumber as $m) {	
					
					if (array_key_exists($m, $fostat2)) {
						
						$fostat2f[] = $fostat2[$m];
						
					} else {
					
						$fostat2f[] = '0';
					}
				
				}
			
				// Total
				$stat1total = join(", ", $fostat2f);
				// Month
				$stat1month = join("', '", $arraymonth);
				
				if (is_array($fostat21)) {
				
					foreach ($arraymonthnumber as $m) {	
						
						if (array_key_exists($m, $fostat21)) {
							
							$fostat21f[] = $fostat21[$m];
							
						} else {
						
							$fostat21f[] = '0';
						}
					
					}
				
					$stat2total = join(", ", $fostat21f);
					
				}
				
				if (is_array($fostat22)) {
				
					foreach ($arraymonthnumber as $m) {	
						
						if (array_key_exists($m, $fostat22)) {
							
							$fostat22f[] = $fostat22[$m];
							
						} else {
						
							$fostat22f[] = '0';
						}
					
					}
					
					$stat3total = join(", ", $fostat22f);
					
				}
			}
			
			// Call the template
			$template = 'orders.php';
		
		break;
		}
		
	break;
	case 'shipping':
		
		switch ($page2) {
		
			case 'new':
			
				if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				    $defaults = $_POST;
				
				    if (empty($defaults['jak_title'])) {
				        $errors['e1'] = $tl['error']['e2'];
				    }
				    
				    if ($defaults['jak_price'] == '') {
				        $errors['e2'] = $tl['shop']['e'].'<br />';
				    }
				    
				    if (empty($defaults['jak_country'])) {
				        $errors['e3'] = $tl['shop']['e1'];
				    }
				    
				    if (count($errors) == 0) {
				
					$sql = 'INSERT INTO '.$jaktable7.' SET 
					title = "'.smartsql($defaults['jak_title']).'",
					country = "'.smartsql($defaults['jak_country']).'",
					est_shipping = "'.smartsql($defaults['jak_estship']).'",
					price = "'.smartsql($defaults['jak_price']).'",
					handling = "'.smartsql($defaults['jak_handling']).'",
					weightfrom = "'.smartsql($defaults['jak_weight']).'",
					weightto = "'.smartsql($defaults['jak_weightto']).'",
					time = NOW()';
					$result = $jakdb->query($sql);
				
				if (!$result) {
				
				    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				        
					} else {
				
				        jak_redirect(BASE_URL.'index.php?p=success');
				    }
					    
				 } else {
				    
				   	$errors['e'] = $tl['error']['e'];
				    $errors = $errors;
				    }
				}
				
				// Get the country list
				$JAK_COUNTRY = getCountry(JAK_COUNTRY, '');
				
				$template = 'newshipment.php';
			
			break;
			case 'edit':
			
				if (is_numeric($page3) && jak_row_exist($page3, $jaktable7)) {
				
					if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				    $defaults = $_POST;
				
				    if (empty($defaults['jak_title'])) {
				        $errors['e1'] = $tl['error']['e2'];
				    }
				    
				    if ($defaults['jak_price'] == '') {
				        $errors['e2'] = $tl['shop']['e'];
				    }
				    
				    if (empty($defaults['jak_country'])) {
				        $errors['e3'] = $tl['shop']['e1'];
				    }
				    
				    if (count($errors) == 0) {
				
					$sql = 'UPDATE '.$jaktable7.' SET 
					title = "'.smartsql($defaults['jak_title']).'",
					country = "'.smartsql($defaults['jak_country']).'",
					est_shipping = "'.smartsql($defaults['jak_estship']).'",
					price = "'.smartsql($defaults['jak_price']).'",
					handling = "'.smartsql($defaults['jak_handling']).'",
					weightfrom = "'.smartsql($defaults['jak_weight']).'",
					weightto = "'.smartsql($defaults['jak_weightto']).'",
					time = NOW()
					WHERE id = "'.smartsql($page3).'"';
					$result = $jakdb->query($sql);
				
				if (!$result) {
				
				    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				        
					} else {
				
				        jak_redirect(BASE_URL.'index.php?p=success');
				    }
					    
				 } else {
				    
				   	$errors['e'] = $tl['error']['e'];
				    $errors = $errors;
				    }
				}
				
				$JAK_FORM_DATA = jak_get_data($page3, $jaktable7);
				
				// Get the country list
				$JAK_COUNTRY = getCountry($JAK_FORM_DATA['country'], '');
								
				$template = 'editshipment.php';
				
				} else {
				    
				   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
				}
			
		break;
		case 'lock';
		
			if (is_numeric($page3) && jak_row_exist($page3, $jaktable7)) {
		
			$result = $jakdb->query('UPDATE '.$jaktable7.' SET status = IF (status = 1, 0, 1) WHERE id = "'.smartsql($page3).'"');
			    	
			if (!$result) {
				jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
			} else {
			    jak_redirect(BASE_URL.'index.php?p=success');
			}
			
			} else {
			   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
			}
		
		break;
		case 'delete';
		
			if (is_numeric($page3) && jak_row_exist($page3, $jaktable7)) {
		
			$result = $jakdb->query('DELETE FROM '.$jaktable7.' WHERE id = "'.smartsql($page3).'"');
			    	
			if (!$result) {
				jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
			} else {
			    jak_redirect(BASE_URL.'index.php?p=success');
			}
			
			} else {
			   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
			}
		
		break;
		default:
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			    $defaults = $_POST;
			    
			    if (isset($defaults['delete'])) {
			    
			    $lockuser = $defaults['jak_delete_order'];
			
			        for ($i = 0; $i < count($lockuser); $i++) {
			            $locked = $lockuser[$i];
			            
			            $sql = 'DELETE FROM '.$jaktable7.' WHERE id = '.$locked.'';
						$result = $jakdb->query($sql);
			        	
			        }
			  
			 	if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
			        jak_redirect(BASE_URL.'index.php?p=success');
			    }
			    
			    }
			
			} else {
			
				$JAK_SHIPPING = jak_get_shipping($jaktable7, '', '');
			
			}
			
			// Call the template
			$template = 'shipment.php';
		}
		
	break;
	default:
	
		switch ($page1) {
		
			case 'edit':
			
				if (is_numeric($page2) && jak_row_exist($page2,$jaktable)) {
				
					if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				    $defaults = $_POST;
				
				    if (empty($defaults['jak_title'])) {
				        $errors['e1'] = $tl['error']['e2'];
				    }
				    
				    if ($defaults['jak_price'] == '') {
				        $errors['e2'] = $tl['shop']['e'];
				    }
				    
				    if (count($errors) == 0) {
				    
				    if (!empty($defaults['jak_update_time'])) {
				    	$insert .= 'time = NOW(),';
				    }
				    
				    // Delete the hits
				    if (!empty($defaults['jak_delete_hits'])) {
				    	$jakdb->query('UPDATE '.$jaktable.' SET hits = 1 WHERE id = '.$page2);
				    }
				    
				    if (!empty($defaults['jak_img'])) {
				    	$insert .= 'previmg = "'.$defaults['jak_img'].'",';
				    } else {
				    	$insert .= 'previmg = NULL,';
				    }
				    
				    if (!empty($defaults['jak_mimg'])) {
				    	$insert .= 'img = "'.$defaults['jak_mimg'].'",';
				    } else {
				    	$insert .= 'img = NULL,';
				    }
				    
				    if (!empty($defaults['jak_file'])) {
				    	$insert .= 'digital_file = "'.$defaults['jak_file'].'",';
				    } else {
				    	$insert .= 'digital_file = NULL,';
				    }
				
				$sql = 'UPDATE '.$jaktable.' SET 
				catid = "'.$defaults['jak_catid'].'",
				title = "'.smartsql($defaults['jak_title']).'",
				content = "'.smartsql($defaults['jak_content']).'",
				product_home = '.$defaults['jak_showhome'].',
				showdate = '.$defaults['jak_showdate'].',
				price = "'.smartsql($defaults['jak_price']).'",
				sale = "'.smartsql($defaults['jak_sale']).'",
				product_weight = "'.smartsql($defaults['jak_weight']).'",
				stock = "'.smartsql($defaults['jak_stock']).'",
				'.$insert.'
				product_options = "'.smartsql($defaults['jak_poption']).'",
				product_options1 = "'.smartsql($defaults['jak_poption1']).'",
				product_options2 = "'.smartsql($defaults['jak_poption2']).'"
				WHERE id = "'.smartsql($page2).'"';
				$result = $jakdb->query($sql);
				
				// Category
				if ($defaults['jak_catid'] != 0 || $defaults['jak_catid'] != $defaults['jak_oldcatid']) {
					$jakdb->query('UPDATE '.$jaktable9.' SET count = count - 1 WHERE id = "'.$defaults['jak_oldcatid'].'"');
					$jakdb->query('UPDATE '.$jaktable9.' SET count = count + 1 WHERE id = "'.$defaults['jak_catid'].'"');
				}
				
				if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
					jak_redirect(BASE_URL.'index.php?p=success');
				}
					    
				} else {
				    
				   $errors['e'] = $tl['error']['e'];
				   $errors = $errors;
				}
				}
				
				$JAK_FORM_DATA = jak_get_data($page2, $jaktable);
				$JAK_CAT = jak_get_cat_info($jaktable9, 0);
				
				$template = 'edititem.php';
				
				} else {
				   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
				}
				
			break;
			case 'delete':
				
				if (is_numeric($page2) && jak_row_exist($page2,$jaktable)) {
				
					$result2 = $jakdb->query('SELECT catid FROM '.$jaktable.' WHERE id = "'.smartsql($page2).'"');
					$row2 = $result2->fetch_assoc();
					
					if (is_numeric($row2['catid'])) {
								
						$jakdb->query('UPDATE '.$jaktable9.' SET count = count - 1 WHERE id = "'.$row2['catid'].'"');
									
					}
							
					$result = $jakdb->query('DELETE FROM '.$jaktable.' WHERE id = "'.smartsql($page2).'"');    	
				
				if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
					jak_redirect(BASE_URL.'index.php?p=success');
				}
				    
				} else {
				   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
				}
				
			break;
			case 'lock':
			
					$result2 = $jakdb->query('SELECT catid, active FROM '.$jaktable.' WHERE id = "'.smartsql($page2).'"');
					$row2 = $result2->fetch_assoc();
					
					if (is_numeric($row2['catid'])) {
					
						if ($row2['active'] == 1) {
							$jakdb->query('UPDATE '.$jaktable9.' SET count = count - 1 WHERE id = "'.$row2['catid'].'"');
						} else {
							$jakdb->query('UPDATE '.$jaktable9.' SET count = count + 1 WHERE id = "'.$row2['catid'].'"');
						}
						
					}
					
					$result = $jakdb->query('UPDATE '.$jaktable.' SET active = IF (active = 1, 0, 1) WHERE id = "'.smartsql($page2).'"');
				    	
				if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
					
				    jak_redirect(BASE_URL.'index.php?p=success');
				}
				
			break;
			case 'sort':
				
				if (is_numeric($page2) && jak_row_exist($page2,$jaktable9)) {
				
					$sql = 'SELECT * FROM '.$jaktable.' WHERE catid = "'.smartsql($page2).'" ORDER BY ecorder ASC';
					$result = $jakdb->query($sql);
					while ($row = $result->fetch_assoc()) {
					        // collect each record into $_data
					        $jakdata[] = $row;
					}
					
					$JAK_ECOMMERCE_ALL = $jakdata;
					$JAK_CAT = jak_get_cat_info($jaktable9, 1);
					
					// Call the template
					$template = 'shop.php';
				    
				} else {
				    
				   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
				}
			
			break;
			default:
				 
				 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				         $defaults = $_POST;
				         
				                 $categories = $defaults['corder'];
				                 $catid = $defaults['real_ms_id'];
				                 $realid = implode(',', $defaults['real_ms_id']);
				                 $test = array_combine($catid, $categories);
				                 
				                 foreach ($test as $key => $category) {
				                 $updatesql .= sprintf("WHEN %d THEN %d ", $key, $category);
				             	}
				             	
				             	$sql = 'UPDATE '.$jaktable.' SET ecorder = CASE id
				         		'.$updatesql.'
				         		END
				 				WHERE id IN ('.$realid.')';
				                 $result = $jakdb->query($sql);
				                 
				                if (!$result) {
				 					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				 				} else {
				 		
				         		jak_redirect(BASE_URL.'index.php?p=success');
				     }
				        
				     }
				
				$JAK_ECOMMERCE_ALL = jak_get_shop($jaktable, '');
				
				$JAK_CAT = jak_get_cat_info($jaktable9, 1);
				
				// Call the template
				$template = 'shop.php';
		}
}
?>