<?php
if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){
	include_once("../connect.php");
	//include_once("../session.php");
}else{
	include_once("./connect.php");
	include_once("./functions.php");
	
	include_once("./session.php");
}



include_once("pos.class.php");
//var_dump($_SESSION);
mysqli_query($con, "SET time_zone = '-04:00'");
$function = $_REQUEST['f'];
if($function == "getCart"){
	getCart($_SESSION['SalesmanID']);
}elseif($function == "addToCart"){
	addToPOSCart($_SESSION['SalesmanID'], $_REQUEST['line'], $_REQUEST['sku'], $_REQUEST['qty']);
}elseif($function == "deleteCartItem"){
	deletePOSCartItem($_REQUEST['id']);
}elseif($function == "getInventoryItem"){
	getInventoryItem($_REQUEST['upc']);
}elseif($function == "saveCartItem"){
	$pos = new POS($_SESSION['SalesmanID']);
	if($pos->editCartItem($_REQUEST['id'], $_REQUEST['desc'], $_REQUEST['qty'], $_REQUEST['price'], $_REQUEST['discount'], $_REQUEST['taxable1'], $_REQUEST['taxable2'])){
		echo "true";
	}else{
		echo "false";
	}
	
}elseif($function == "customerLookup"){
	customerLookup($_REQUEST['term']);
}elseif($function == "clearCart"){
	
	$pos = new POS($_SESSION['SalesmanID']);
	//var_dump($pos);
	if($pos->clearCart()){
		echo "true";
	}else{
		echo "false";
	}
	
}elseif($function == "productLookup"){
	productLookup($_REQUEST['term'], $_REQUEST['an']);
}elseif($function == "setCustomer"){
	ob_start();
	setCustomer($_REQUEST['an']);
	$resultData = ob_get_contents();
	ob_end_clean();
	$result = json_decode($resultData);
	//var_dump($result);
	if($result->result){
		$pos = new POS($_SESSION['SalesmanID']);
		$pos->recalculatePrices();
		//var_dump($pos);
		$customer = new Customer($_REQUEST['an']);
		unlink($customer->Password);
		unlink($customer->CookieHash);
		echo safe_json_encode($customer);
	}else{
		echo $resultData;
	}
}

function getCart($SalesmanID){
	$pos = new POS($SalesmanID);
	echo safe_json_encode($pos->Items);
}
function addToPOSCart($SalesmanID, $Line, $SKU, $Qty){
	$pos = new POS($SalesmanID);
	//var_dump($pos);
	$result = $pos->addToCart($Line, $SKU, $Qty);
	if($result === true){
		echo "true";
	}else{
		echo print_r($result);
	}
}
function deletePOSCartItem($id){
	$pos = new POS($SalesmanID);
	$result = $pos->deleteCartItem($id);
	if($result === true){
		echo "true";
	}else{
		echo $result;
	}
}
function customerLookup($term, $accountNumber){
	global $con;
	$term = mysqli_real_escape_string($con, $term);
	if(true){
 		if (true) {
 			$term = "%" . str_ireplace(" ", "%", $term) . "%";
 		}
 		
 	}
 	$query = "SELECT AccountNumber FROM CUSTOMER WHERE Name LIKE '%$term%' OR CompanyName LIKE '%$term%' OR Contact LIKE '%$term%' OR AccountNumber LIKE '$term' OR Phone LIKE '%$term'";
	$query = "SELECT * FROM ($query) T LIMIT 12";
	$result = mysqli_query($con, $query);
	if(mysqli_num_rows($result)){
	?>
		<table class="table table-condensed">
			<thead>
				<tr>
					<th>Name</th>
					<th>Company</th>
					<th>City</th>
					<th>Phone</th>
					<th>Price Level</th>
					<th></th>
				</tr>
			</thead>
		
			<tbody>
		<?php
		while($row = mysqli_fetch_array($result)){
			$customer = new Customer($row['AccountNumber']);
		?>
			<tr>
				<td><?= $customer->Name ?></td>
				<td><?= $customer->CompanyName ?></td>
				<td><?= $customer->City ?></td>
				<td><?= $customer->Phone ?></td>
				<td><?= $customer->PriceLevel ?></td>
				
				<td><button onclick="selectCustomer('<?= $row['AccountNumber'] ?>')" class="btn btn-sm btn-success">Select</button></td>
			</tr>
		<?php
		}
		?>
			</tbody>
		</table>
	<?php
	}else{
	?>
		<div class="" style="margin-top: 20px;"><center><h3>No results found.</h3></center></div>
	<?php
	}
	
}
function productLookup($term, $accountNumber){
	global $con;
	$term = mysqli_real_escape_string($con, $term);
	if(true){
 		if (true) {
 			$term = "%" . str_ireplace(" ", "%", $term) . "%";
 		}
 		
 	}
 	$query1 = "SELECT INVENTORY.*, 1 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE INVENTORY.`SKU` LIKE '$term'";
 	$query2 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE REPLACE(INVENTORY.`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $term) . "'" . $line . $group;
 	$query3 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE `Interchange` LIKE '%$term%'";
	$query3 .= "UNION SELECT 
			INVENTORY.*, 1.5 SortOrder, `Reference`, Supplier
		FROM `INVENTORY` 
			LEFT JOIN 
			`INTERCHANGE` ON `INVENTORY`.SKU = INTERCHANGE.SKU
				
		WHERE 
			
			REPLACE(INTERCHANGE.Reference, \"-\", \"\") LIKE '" . str_ireplace("-", "", $term) . "'";
	
 	$where = "";
 	$index = 0;
 	if ((true)) { //if wc=1
 		$partGroup = explode("%", $term);
 	}else{
 		$partGroup = explode(" ", $term);
 	}
 	
 	$partCount = count($partGroup);
 	foreach ($partGroup as $key => $value) {
 		$index++;
 		$where .= "CONCAT_WS(' ', `Description`, `Notes`) LIKE '%$value%'";
 		if ($index < $partCount) {
 			$where .= " AND ";
 		}
 	}
 	/*
 	$query4 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder FROM `INVENTORY` LEFT JOIN SHOPPING_CART  
 			ON `INVENTORY`.SKU = SHOPPING_CART.SKU 
 				AND INVENTORY.`Group` = SHOPPING_CART.`Group` 
 				AND `INVENTORY`.Line = SHOPPING_CART.Line 
 				AND SHOPPING_CART.`AccountNumber` = '$AccountNumber' WHERE `Description` LIKE '%$term%'" . $line . $group;
 	*/
 	$query4 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE " . $where;
	
 	$query5 = "SELECT INVENTORY.*, 2 SortOrder, 0 as Reference, \"\" AS Supplier FROM `INVENTORY` WHERE `Notes` LIKE '%$term%'";
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY SortOrder, `sku`";
 /**/
	$queryPLS = $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY SortOrder, `sku`";
	$queryPLS = str_ireplace(" UNION ", " AND INVENTORY.Qty <= 0 GROUP BY `Group`, SKU UNION ",$queryPLS);
	$queryPLS = str_ireplace(" ORDER BY ", " AND INVENTORY.Qty <= 0 GROUP BY `Group`, SKU ORDER BY ",$queryPLS);
	$query = "SELECT * FROM ($query) T LIMIT 12";
	$result = mysqli_query($con, $query);
	if(mysqli_num_rows($result)){
	?>
		<table class="table table-condensed">
			<thead>
				<tr>
					<th>Line</th>
					<th>SKU</th>
					<th>Description</th>
					<th>Qty</th>
					<th>Committed</th>
					<th>Price</th>
					<th>Add</th>
				</tr>
			</thead>
		
			<tbody>
		<?php
		while($row = mysqli_fetch_array($result)){
			$product = new Item($row['Group'], $row['Line'], $row['SKU']);
		?>
			<tr>
				<td><?= $product->Line ?></td>
				<td><?= $product->SKU ?></td>
				<td><?= $product->Description . " " , $product->Notes ?></td>
				<td><?= $product->Qty ?></td>
				<td><?= $product->getCommittedQty(); ?></td>
				<td><?= moneyFormat(getCustomerPrice($row['Group'], $row['Line'], $row['SKU'], $accountNumber)) ?></td>
				<td><button onclick="addLookupItem('<?= $row['Line'] ?>','<?= $row['SKU'] ?>')" class="btn btn-sm btn-success">Add</button></td>
			</tr>
		<?php
		}
		?>
			</tbody>
		</table>
	<?php
	}else{
	?>
		<div class="" style="margin-top: 20px;"><center><h3>No results found.</h3></center></div>
	<?php
	}
	
}
function getInventoryItem($upc){
	global $con;
	$query = "SELECT * FROM INVENTORY WHERE SKU LIKE '$upc' OR INTERCHANGE LIKE '$upc' OR VendorSKU LIKE '$upc'";
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	$item = new Item($row['Group'], $row['Line'], $row['SKU']);
	echo safe_json_encode($item);
}
?>