<?php
//die('test');
include_once("session.php");
include_once("connect.php");

global $con;
$pricePlanMode = false;
$isCustomer = false;

if (isset($_SESSION['isCustomer'])) {
	$isCustomer = $_SESSION['isCustomer'];
}else {
	header("Location: login.php");
	return;
}
$language = "ES";

if ($isCustomer) {
	$customer = new Customer($_SESSION['AccountNumber']);
	$language = $customer->Language;
} else {
	if (isset($_SESSION['SalesmanID'])) {
		$salesman = new Salesman($_SESSION['SalesmanID']);
		$language = $salesman->Language;
		$pricePlanMode = $_SESSION['pricePlanMode'];
		if(isset($_SESSION['TruckMode']) && $_SESSION['TruckMode'] == true){
			header("Location: truckinventory.php");
		}
	}else {
		header("Location: login.php");
		return;
	}


}
if(isset($_REQUEST['sku'])){
	if($_REQUEST['sku'] == "" && $_REQUEST['line'] == "" && $_REQUEST['group'] == ""){
		header("Location: index.php");
		return;
	}
}
$_SESSION['LastSearch'] = array(
			"SKU" => "",
			"Line" => "",
			"Group" => "",
			"WC" => "",
			"Page" => ""
);


//var_dump($_SESSION);
?>

 <!DOCTYPE html>
<?php
if($_REQUEST['cachedl'] == "1"){
	?>
	<html lang="en" manifest="cache.manifest">
	<?php
	
}else{


 ?>
 <html lang="en">
 <?php
} ?>
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <!--<meta name="viewport" content="width=device-width, initial-scale=1">-->
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	 <meta http-equiv="cache-control" content="max-age=0" />
	 <meta http-equiv="cache-control" content="no-cache" />
	 <meta http-equiv="expires" content="0" />
	 <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
	 <meta http-equiv="pragma" content="no-cache" />

     <title><?= $config['CompanyName'] ?></title>

     <!-- Bootstrap -->
     <link href="css/bootstrap.min.css" rel="stylesheet">

     <!-- Icons -->
		<link rel="apple-touch-icon" sizes="57x57" href="img/apple-icon-57x57.png">
		<link rel="apple-touch-icon" sizes="60x60" href="img/apple-icon-60x60.png">
		<link rel="apple-touch-icon" sizes="72x72" href="img/apple-icon-72x72.png">
		<link rel="apple-touch-icon" sizes="76x76" href="img/apple-icon-76x76.png">
		<link rel="apple-touch-icon" sizes="114x114" href="img/apple-icon-114x114.png">
		<link rel="apple-touch-icon" sizes="120x120" href="img/apple-icon-120x120.png">
		<link rel="apple-touch-icon" sizes="144x144" href="img/apple-icon-144x144.png">
		<link rel="apple-touch-icon" sizes="152x152" href="img/apple-icon-152x152.png">
		<link rel="apple-touch-icon" sizes="180x180" href="img/apple-icon-180x180.png">
		<link rel="icon" type="image/png" sizes="192x192"  href="img/android-icon-192x192.png">
		<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
		<link rel="icon" type="image/png" sizes="96x96" href="img/favicon-96x96.png">
		<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png">
	
		<meta name="msapplication-TileColor" content="#ffffff">
		<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
		<meta name="theme-color" content="#ffffff">


     <link rel="stylesheet" href="css/bootstrap-combobox.css?date=2342" />

     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <script src="js/functions.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->

           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="js/bootstrap.min.js?date=13"></script>
       	 <script src="js/bootstrap-combobox.js?date=13"></script>
           <script src="js/select2.full.min.js"></script>
     <![endif]-->
	<link rel="stylesheet" href="css/styles.css"/>
	<link rel="stylesheet" href="css/select2.min.css"/>
   </head>
   <body>
<?php

	include("navbar.php");

?>
  <br />
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
     <div class="container " style="">

     <center>
		<h3>
			<?php
					//if is a salesman
					if (!$_SESSION['isCustomer']) {
					   if ($pricePlanMode) {
						   $customer = new Customer($_SESSION['AccountNumber']);
						   echo("Price Plan Mode - <i>" . $customer->AccountNumber . " - " . $customer->Name . "</i>");
						   //echo ($customer->SupplierID)?("Supplier ID: " . $customer->SupplierID):"";
					   }elseif(isset($_SESSION['setCustomerMode']) && $_SESSION['setCustomerMode']) {
						   $customer = new Customer($_SESSION['setCustomer']);
						   echo("<i>" . $customer->AccountNumber . " - " . $customer->Name . "</i>");
						   //echo ($customer->SupplierID)?("Supplier ID: " . $customer->SupplierID):"";


					   }
					}else{
						$customer = new Customer($_SESSION['AccountNumber']);
					}
					 ?>
		</h3>
		<h5 style="color: red;">
			<?php
			if($customer->TaxIDExpiration2 != "0000-00-00"){
				$Tax2ExpirationDate = strtotime($customer->TaxIDExpiration2);

				$difference = $Tax2ExpirationDate - time();
				$difference = $difference/(60*60*24);
				if($difference < 0){
					echo "Expired Municipal Tax Exemption Certificate!";
				}elseif($difference <= 30){
					echo "The Municipal Tax Exemption Certificate is about to expire!";
				}
			}

			?>
		</h5>
		<h5>
			<?=  ($customer->SupplierID)?("Supplier ID: <b>" . $customer->SupplierID . "</b>"):""; ?>
		</h5>
	 </center>
     <div class="well well-sm">
       <form name="inventorySearch" role="form" novalidate="novalidate" class="form-inline">


       	 <div class="row">
			<div class="col-md-3 centered">
				<h3 class="centered">Product Finder<br>

				</h3>
				
				
			</div>
			<div class="col-md-9">
				

				<div class="form-group">
					<div class="row">
						<div class="col-xs-12 col-md-3">
							<label class="comboboxLabel">Category</label>
							<select name="line"  id="lineSelect" style="width: 100%;" class="form-control">

								<option></option>
								<?php
									global $con;
									$name = "Name";
									if ($language == "EN") {
										$name = "NameEN";
									}
									$group = (isset($_GET['group']))?$_GET['group']:"";
									if($group == ""){
										$group = "%";
									}
									$where = " WHERE `Code` IN (SELECT `Line` FROM INVENTORY WHERE `Group` LIKE '$group' GROUP BY `Line`)";

									$query = "SELECT * FROM `LINE` ORDER BY `$name` ASC";
									$result = mysqli_query($con, $query);
									while ($row = mysqli_fetch_array($result)) {
								?>
										<option <?= (isset($_REQUEST['line']) && $_REQUEST['line'] == $row['Code'])?"selected":"" ?> value="<?=$row['Code']?>"><?=$row[$name]?></option>
								<?php
									}

								?>
							</select>
						</div>
						<div class="col-xs-12 col-md-6">
							<label class="comboboxLabel">Stock #</label><br>
							<div class="input-group">
								<span class="input-group-addon">
									<?php
										$wc = isset($_REQUEST['wc'])?$_REQUEST['wc']:"0";
									?>
									<input type="checkbox" <?= ($wc == "1")?"checked":"" ?>  name="wc" aria-label="..."> Wild
								</span>
								<input autocomplete="off" class="form-control" style="" type="text" name="sku" value="<?= (isset($_REQUEST['sku'])?$_REQUEST['sku']:"") ?>" />
								<div class="input-group-btn">
									<button class="btn btn-primary">Search</button>
								</div>
							</div>
						</div>
						<div class="col-xs-12 col-md-3">
							<label class="comboboxLabel"> </label><br>
							<a class="btn btn-primary form-control" onclick="showCatalog();">Browse Catalog</a>
						</div>
					</div>
				</div>


				<div class="form-group">
					


				</div>

			   <div class="form-group hidden">

				 

			   </div>
			   <?php

			   if(!$isCustomer && ($detect->isMobile() || $detect->isTablet())){
					if($detect->isTablet()){
						$shortcutMargin = 0;
					}else{
						$shortcutMargin = -10;
					}
			   ?>
			   <div class="pull-right" style="margin-top: <?= $shortcutMargin ?>px; width: 70%;">
				<div class="row">
					<div class="col-xs-6"><a style="font-size: 40px;" href="cart.php">🛒</a></div>
					<div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#reorderModal').modal('toggle');return false;" href="#"><img src="./img/icon_reorder2.png" style="width: 50px;"/></a></div>
					<div class="col-xs-6"><a style="font-size: 40px;" href="mod.php?p=payment&a=new">💰</a></div>
					<div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#navbarClearCustomer').click();">👥</a></div>
					<div class="col-xs-6"><a style="font-size: 40px;" onclick="showCatalog();"><img src="img/catalog-icon.png" style="width: 50px;" /></a></div>
					<div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#deliveryModal').modal();"><img  style="height: 40px;" src="img/delivery_logo.png" /></a></div>
					<div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#specialsModal').modal('toggle');"><img src="img/special_icon.png" style="width: 50px;" /></a></div>

					<?php
						if($salesman->AllowTruckMode){
					?>
					<div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#truckModeWarehouseModal').modal();"><img  style="height: 40px;" src="img/truck.png" /></a></div>
					<?php
						}
						$query = "SELECT COUNT(PurchaseOrderID) `Count` FROM PURCHASE_ORDER_HEADER JOIN VENDOR USING(VendorID) WHERE Confirmed = 1 AND Received = 0";
						$result = mysqli_query($con, $query);
						$row = mysqli_fetch_array($result);
						if($row['Count'] > 0){

						?>
						<div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#altasModal').modal();"><img src="img/ontheway.png" style="width: 50px;" /></a></div>

						<?php
						}
						?>
				</div>

				<br>
				<br>
				<img style="display: none; width: 50px;" class="pull-right" src="img/pr_flag.png" id="updateIndicator" />
			   </div>
			   <?php

			 }elseif($isCustomer && $detect->isMobile()){
				 ?>
				 <div class="pull-right" style="margin-top: <?= $shortcutMargin ?>px; width: 70%;">
			 	 	<div class="row">
						 <div class="col-xs-6"><a style="font-size: 40px;" href="cart.php">🛒</a></div>
						 <div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#reorderModal').modal('toggle');return false;" href="#"><img src="./img/icon_reorder2.png" style="width: 50px;"/></a></div>
						 <div class="col-xs-6"><a style="font-size: 40px;" onclick="showCatalog();"><img src="img/catalog-icon.png" style="width: 50px;" /></a></div>
						 <div class="col-xs-6"><a style="font-size: 40px;" onclick="$('#specialsModal').modal('toggle');"><img src="img/special_icon.png" style="width: 50px;" /></a></div>
					 </div>
					 </div>
				 <?php
			 }
			   ?>

			</div>
		 </div>
       </form>
     </div>


 </div>


 <?php


 if(isset($_REQUEST['sku'])){


	$part = strtoupper(mysqli_real_escape_string($con, trim($_REQUEST['sku'])));
	$isSalesman = (!$isCustomer) ? 'true' : 'false';
	$account = ($isCustomer)?$_SESSION['AccountNumber']:$_SESSION['SalesmanID'];
	$query = "INSERT INTO SEARCH_QUERY (`Group`, `Line`, `SKU`, `AccountNumber`, `Salesman`, `QueryDate`) VALUES ('" . $_REQUEST['group'] . "', '" . $_REQUEST['line'] . "', '" . $part . "', '" . $account . "', " . $isSalesman . ", NOW())";
	mysqli_query($con, $query);

 $line = ($_REQUEST['line'] != '')?" AND INVENTORY.`Line`  LIKE '" . mysqli_real_escape_string($con, $_REQUEST['line']) . "'":'';
 $group = ($_REQUEST['group'] != '')?" AND INVENTORY.`Group`  LIKE '" . mysqli_real_escape_string($con, $_REQUEST['group']) . "'":'';

 $_SESSION['LastSearch'] = array(
 			"SKU" => $part,
 			"Line" => mysqli_real_escape_string($con, $_REQUEST['line']),
 			"Group" => mysqli_real_escape_string($con, $_REQUEST['group']),
 			"WC" => (isset($_REQUEST['wc']))?$_REQUEST['wc']:"0",
 			"Page" => (isset($_REQUEST['p']))?$_REQUEST['p']:"1"
 );

 /*
 if(isset($_REQUEST['wc'])){
	$parts = explode(" ", $part);
	$query = "";
	foreach ($parts as $term) {
		$query1 = "SELECT * FROM `INVENTORY` WHERE `SKU` LIKE '%$term%'" . $line . $group;
		$query2 = "SELECT * FROM `INVENTORY` WHERE REPLACE(`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $term) . "'" . $line . $group;
		$query3 = "SELECT * FROM `INVENTORY` WHERE `Interchange` LIKE '%$term%'" . $line . $group;
		$query4 = "SELECT * FROM `INVENTORY` WHERE `Description` LIKE '%$term%'" . $line . $group;
		$query5 = "SELECT * FROM `INVENTORY` WHERE `Notes` LIKE '%$term%'" . $line . $group;
		$query = $query . $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " UNION ";
	}
		$query = $query . "SELECT * FROM `INVENTORY` WHERE `SKU` LIKE '$term'" . $line . $group . " ORDER BY `sku`";

 }else{
 	$query1 = "SELECT * FROM `INVENTORY` WHERE `SKU` LIKE '$part'" . $line . $group;
 	$query2 = "SELECT * FROM `INVENTORY` WHERE REPLACE(`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $part) . "'" . $line . $group;
 	$query3 = "SELECT * FROM `INVENTORY` WHERE `Interchange` LIKE '%$part%'" . $line . $group;
 	$query4 = "SELECT * FROM `INVENTORY` WHERE `Description` LIKE '%$part%'" . $line . $group;
 	$query5 = "SELECT * FROM `INVENTORY` WHERE `Notes` LIKE '%$part%'" . $line . $group;
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY `sku`";
 }

 */

 /**/
 	$AccountNumber = ($_SESSION['isCustomer'])?$_SESSION['AccountNumber']:$_SESSION['SalesmanID'];
 	if(isset($_REQUEST['wc'])){
 		if ($_REQUEST['wc'] == "1") {
 			$part = "%" . str_ireplace(" ", "%", $part) . "%";
 		}

 	}
 	$query1 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 1 SortOrder, 0 as Reference, \"\" AS Supplier 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 Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND INVENTORY.`SKU` LIKE '$part'" . $line . $group;
 	$query2 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier 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 Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND REPLACE(INVENTORY.`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $part) . "'" . $line . $group;
 	$query3 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier 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 Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND `Interchange` LIKE '%$part%'" . $line . $group;
	$query3 .= "UNION SELECT
			INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 1.5 SortOrder, `Reference`, Supplier
		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'
			LEFT JOIN
			`INTERCHANGE` ON `INVENTORY`.SKU = INTERCHANGE.SKU

		WHERE

			REPLACE(INTERCHANGE.Reference, \"-\", \"\") LIKE '" . str_ireplace("-", "", $part) . "'" . $line . $group;

 	$where = "";
 	$index = 0;
 	if (isset($_REQUEST['wc'])) {
 		$partGroup = explode("%", $part);
 	}else{
 		$partGroup = explode(" ", $part);
 	}

 	$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 '%$part%'" . $line . $group;
 	*/
 	$query4 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier 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  Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND " . $where . $line . $group;

 	$query5 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier 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 Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND `Notes` LIKE '%$part%'" . $line . $group;
 	$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);


 if (isset($_REQUEST['debug'])) {
	//echo($query);
	echo("<BR />");
	echo($queryPLS);
 }

 $result = mysqli_query($con, $query);
 if (!(isset($_REQUEST['p']))) {
 	$pagenum = 1;
 } else {
 	$pagenum = $_REQUEST['p'];
 }

$rows = mysqli_num_rows($result);

 if ($rows < 2) {
 	$query1 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 1 SortOrder, 0 as Reference, \"\" AS Supplier 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 Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND INVENTORY.`SKU` LIKE '$part%'" . $line . $group;
 	$query2 = "SELECT INVENTORY.*, SHOPPING_CART.Qty AS OnOrder, 2 SortOrder, 0 as Reference, \"\" AS Supplier 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 Active = 1 AND ((Discontinued = 1 AND INVENTORY.Qty > 0) OR (Discontinued = 0)) AND REPLACE(INVENTORY.`SKU`,\"-\",\"\") LIKE '" . str_ireplace("-", "", $part) . "%'" . $line . $group;
 	$query = $query1 . " UNION " . $query2 . " UNION " . $query3 . " UNION " . $query4 . " UNION " . $query5 . " ORDER BY `sku`";
	$result = mysqli_query($con, $query);
	$rows = mysqli_num_rows($result);
 }


 $page_rows = 50;
 if($rows > 0){
 	$last = ceil($rows/$page_rows);
 	if ($pagenum < 1) {
 		$pagenum = 1;
 	} elseif ($pagenum > $last) {
 		$pagenum = $last;
 	}
 	$max = ' LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
 	$query .= $max;
 	$result = mysqli_query($con, $query);


	include_once('./modules/lostsale/lostsale.addon.php');
?>

		<div class="container">
			<div class="row">
   			<script type="text/javascript">
				var cursor = 0;

				function nextItem() {
					cursor += 1;
					console.log(cursor);
					length = $('table tr').length;
					cursor = cursor % length;
					if (cursor == 0) {
						$($('table tr')[length-1]).removeClass("active");
						if (hymen) {
							alert("end of page")
							hymen = false;
						}
					}else{
						console.log("length: " + $('table tr').length);
						console.log("cursor:" + cursor);
						$($('table tr')[cursor-1]).removeClass("active");
						$($('table tr')[cursor]).addClass("active");
					}
				}
				function previousItem() {
					if (cursor == 0) {
						alert("go back");
					} else if (cursor < 0) {
						return;
					}else{
						cursor -= 1;
						if (cursor == 0) {
							alert("go back");
						}else{
							$($('table tr')[cursor+1]).removeClass("active");
							$($('table tr')[cursor]).addClass("active");
						}
					}
				}
				/*
				$(document).keydown(function(e) {

					//alert(e.which);
					switch (e.which) {
						case 13:
							//enter pressed
							if (typeof($("#qtyBox").data('bs.modal')) == "undefined") {
								askQty(cursor-1);
								break;
							}
							if ($("#qtyBox").data('bs.modal').isShown) {
								break;
							}else {
								askQty(cursor-1);
							}

							break;
						case 38:
							//up arrow
							previousItem();
							break;
						case 40:
							//down arrow
							$('[name=sku]').blur();
							nextItem();
							break;
					}
				});
				*/
   			</script>
<?php
   $index = 0;
   $listingArray = array();
 	while($row = mysqli_fetch_array($result)){
		$product = new Item($row['Group'], $row['Line'], $row['SKU']);
		//$row['Qty'] -= $product->getCommittedQty();
 		if (in_array($row['Line'] . $row['SKU'], $listingArray)) {
 			continue;
 		}
 		array_push($listingArray, $row['Line'] . $row['SKU']);
 		echo "<script type=\"text/javascript\">\n";
 		echo "Line.push('" . $row['Line'] . "');\n";
 		echo "Group.push('" . $row['Group'] . "');\n";
 		echo "SKU.push('" . $row['SKU'] . "');\n";
 		echo "OnOrder.push('" . $row['OnOrder'] . "');\n";
 		echo "</script>";

		if($customer->AccountNumber == "10033" || $isSalesman != "false"){
			$qty = ($row['Qty']);
		}else{
			$qty = ($row['Qty'] > 50)?"50+":$row['Qty'];
		}

		$qty = ($qty < 0)?"0":$qty;
		if($index%4 == 0){
			echo "<div class=\"row\">";
		}
?>

				<div class="col-md-3">
					<div style="height: 450px;" class="thumbnail">
						<a href="" onclick="getProductDetails('<?= $row['Line'] ?>', '<?= $row['SKU'] ?>'); return false;"><img style="max-height: 252px;" src="<?= $product->getImage() ?>" alt=""></a>

						<div class="caption">
						  <h4 class="pull-right"><?php
								$price = 0;
								if(isQtyBreakSpecial($row['Line'], $row['SKU'])){
								  echo "<del>";
								}
								
								$price = getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * (getPricePlanCalculatedRate($_SESSION['setCustomer']));
							
								echo moneyFormat($price);
								
								if(isQtyBreakSpecial($row['Line'], $row['SKU'])){
								  echo "</del>";
								}
								?></span>
								<?php
									 if(floatval($row['Core'])>0){
										 echo "<br><i><b>Core:</b> ".$row['Core'] . "</i>";
									 }
								?></h4>
						  <h4><a href="#" onclick="getProductDetails('<?= $row['Line'] ?>', '<?= $row['SKU'] ?>'); return false;"><?= $product->SKU ?></a></h4>
							<?php
							if($row['Reference'] != "0"){
								echo "<small><b>(Interchange for: " . $row['Reference'] . " - <i>" . $row['Supplier'] . "</i>)</b></small>";
							}else{
								echo "";
							}
							 ?>

						  <p>
							<?= $product->Description . " " . $product->Notes ?>
							<br>
							<?php
								if($row['Discontinued']){
							?>
							<span style="color: red;">WHILE SUPPLIES LAST</span><br>
							<?php
								}
							?>


						  </p>
						</div>
						<p>
							<div class="row">
								<div class="col-xs-6">
									<?php
										if($price == 0){
									?>
									<button id="<?= $index; ?>AddButton" class="btn <?= $row['OnOrder'] > 0 ? "btn-warning":"btn-primary" ?>" id="item<?= $index; ?>" onclick="askQty(<?= $index; ?>)" type="button"><?= $row['OnOrder'] > 0 ? "Update":"Quote" ?></button>
									<?php
										}else{
									?>
									<button id="<?= $index; ?>AddButton" class="btn <?= $row['OnOrder'] > 0 ? "btn-warning":"btn-success" ?>" id="item<?= $index; ?>" onclick="askQty(<?= $index; ?>)" type="button"><?= $row['OnOrder'] > 0 ? "Update":"Add" ?></button>
									<?php
										}
									?>

								</div>
								<div class="col-xs-6">

								<?php
									if($product->getAttribute('Barcode')){
								?>
									<a onclick="openBarcode('<?= $row['Line'] . " " . $row['SKU'] . "<br><small>" . $row['Description'] . " " . $row['Notes'] ?>', '<?= $product->getAttribute('Barcode') ?>');"><img style="width: 28px;" src="img/barcode.png"></a>
								<?php
									}
								?>

								</div>

							</div>
							<div class="row">
								<div class="col-xs-4">

								</div>

								<div class="col-xs-8" style="text-align: right; padding-right: 30px;">

									On Hand: <?= $qty ?>
									<?php
									if($product->getCommittedQty()!=""){
									?>
									<br>Committed: <?= $product->getCommittedQty() ?>

									<?php
									}
									//var_dump($product->ConfrimedQuery);
										if($product->ConfirmedQty > 0){
									?>
									<br>
									<span style="color: blue;"><img src="img/ontheway.jpg" style="width: 40px;">: <?= $product->ConfirmedQty ?></span>
									<?php
										}
									?>
								</div>


							</div>
						</p>
					</div>
				</div>
     <?php
	 if($index%4 == 3){
			echo "</div>";
		}
     $index++;
     } ?>
		</div>
	</div>


 <div style="width: 100%; text-align: center;" class="pagination">
 <?php
 if($last > 1){
 	$wc = isset($_REQUEST['wc'])?$_REQUEST['wc']:"0";
 	$queryString = $_SERVER['PHP_SELF'] . "?group=" . $_REQUEST['group'] . "&line=" . $_REQUEST['line'] . "&sku=" . $_REQUEST['sku'] . "&wc=" . $wc;
 	if(!isset($_REQUEST['p'])){
 		$_REQUEST['p'] = "1";
 	}
  ?>
	<ul class="pagination">
	<?php
	//disable prev button in first page
	 ?>
	<li <?= ($_REQUEST['p'] == "1")?"class=\"disabled\"":"" ?>>
		<a href="<?= $queryString . "&p=". (intval(mysqli_real_escape_string($con, $_REQUEST['p']))-1)?>">Prev</a>
     </li>
     <?php
     //create each page button
     	for($i = 1; $i<=$last; $i++){
     		$p = (isset($_REQUEST['p']))?$_REQUEST['p']:"1";
     ?>
     <li <?= ($p == "$i")?"class=\"active\"":"" ?>>
       <a href="<?= $queryString . "&p=". $i ?>"><?= $i ?></a>
     </li>
             <?php } ?>
     <li <?= ($_REQUEST['p'] == $last)?"class=\"disabled\"":"" ?>>
 	<?php

 		$p = (isset($_REQUEST['p']))?(intval($_REQUEST['p'])+1):"2";
 		$link = $queryString . "&p=" . $p;
 	?>
       <a href="<?= $link; ?>">Next</a>
     </li>
   </ul>
   <?php } ?>
 </div>
 <?php

 	}else {
?>
		<div class="well well-sm"><?php
		//($language=="ES")?"Lo sentimos, no encontramos lo que est&aacute; buscando.":"We are sorry, we couldn't find the part you are looking for."
		?><br />
		<?php
			include_once('./modules/lostsale/lostsale.addon.php');
			if ($_SESSION['isCustomer']) {
		?>
				<?= ($language=="ES")?"":"" ?>

		<?php
			}

		 ?></div>

<?php
 	}
 }

?>

<script type="text/javascript">
      $(document).ready(function(){
        $('[name=sku]').select();
//        $('.grpline').css("width", "100px");

      });
      function setLanguage(Language) {
		$('#LanguageButton').text(Language);

      	$.get('functions.php?action=setLanguage&language=' + Language, function(data) {
      		if (data == "true") {
      			location.reload();
      		}else {
      			console.log("ERROR: " + data);
      		}
      	});

      }

      function showPromo() {
      	$('iframe').attr('src', '');
      	$('#promoModal').modal('show');

      }
      var promoModal = $("#promoModal");
      promoModal.on('hide.bs.modal', function (e) {
      	$('iframe').attr('src', '');
      });


      /************************** /
      *							  *
      *	  BUYER'S GUIDE ADDON	  *
      *							  *
      / **************************/
	  loadBGLinks();
	  function loadBGLinks(){
		var BGsku, BGtype, BGline;
		for (var i = 0; i < SKU.length; i++) {
		  BGsku = $($('.SKU')[i]).text();
		  switch (Line[SKU.lastIndexOf(BGsku)]) {
		  <?php

		  $query = "SELECT * FROM BUYERS_GUIDE_DEFINITIONS WHERE `Line` != ''";
		  $result = mysqli_query($con, $query);
		  while ($row = mysqli_fetch_array($result)) {
			  echo "\tcase \"" . $row['Line'] . "\":\n";
			  echo "\t\t\t\tBGtype = '" . $row['Type'] . "';\n";
			  echo "\t\t\t\tbreak;\n";
		  }
		   ?>
			  default: {
				  switch (Group[SKU.lastIndexOf(BGsku)]) {
			<?php

					  $query = "SELECT * FROM BUYERS_GUIDE_DEFINITIONS WHERE `Group` != ''";
					  $result = mysqli_query($con, $query);
					  while ($row = mysqli_fetch_array($result)) {
						  echo "\tcase \"" . $row['Group'] . "\":\n";
						  echo "\t\t\t\tBGtype = '" . $row['Type'] . "';\n";
						  echo "\t\t\t\tbreak;\n";
					  }
					?>
					   default:
						  BGtype = 'cross';
						  break;
				  }
			  }
		  }
		  if (Line[SKU.lastIndexOf(BGsku)] != "") {
			  $($('.SKU')[i]).html('<a href="javascript:getProductDetails(\'' + Line[SKU.lastIndexOf(BGsku)] + '\', \'' + BGsku + '\')">' + BGsku + '</a>');

		  }

		}
	  }


      function getBG(type, line, group, sku) {
            	var	sku2 = sku;
            	$('#applicationsTable').html('');
            	$('#images').html('');
            	$('#detailsTable').html('');
            	$('#detailsTab').css('display', '');
            	$('#imagesTab').css('display', '');

       		$.get('./smtpengine.php?type=' + type + '&line=' + line + '&group=' + group + '&action=applications&part=' + sku2, function(data) {
       			if (data != "false") {
       				var applications = JSON.parse(data);
       				for (var i = 0; i < applications.length; i++) {
       					$('#applicationsTable').append("<tr style=\"overflow: hidden;\"><td>" + applications[i].year + "</td><td>" + applications[i].make + "</td><td>" + applications[i].model + "</td><td>" + applications[i].engine + "</td><td style=\"overflow: hidden;\">" + applications[i].parttype + "</td></tr>");
       				}
       				$('#skuBG').text(sku);
       				$('#BGModal').modal('show')
       				$('#applicationsTab').click();
       			}else {
       				alert("Lo sentimos, no tenemos imagen disponible para esta pieza.\nWe are sorry, we don't have an image for this part.");
       			}

       		});

       		$.get('./smtpengine.php?type=' + type + '&line=' + line + '&group=' + group + '&action=images&part=' + sku2, function(data) {
       			var images = JSON.parse(data);
       			if (images.length > 0) {
           			for (var i = 0; i < images.length; i++) {
           				$('#images').append('<img src="' + images[i].id + '" alt="" />');
           			}
           		}else {
           			$('#imagesTab').css('display', 'none');
           		}
       		});
       		$.get('./smtpengine.php?type=' + type + '&line=' + line + '&group=' + group + '&action=details&part=' + sku2, function(data) {
       			var details = JSON.parse(data);
       			if (details.length > 0) {
       				for (var i = 0; i < details.length; i++) {
       					$('#detailsTable').append('<tr><td>' + details[i].attribute + '</td><td>' + details[i].value + '</td></tr>');
       				}
       			}else {
       				$('#detailsTab').css('display', 'none');
       			}

       		});


            }
			$('[name=line]').on('change', function(){
				$.get('functions.php?action=getGroupsByLine&line=' + $('[name=line]').val(), function (data){
					data = JSON.parse(data);
					$('[name=group]').html('');
					for(var i = 0; i < data.length; i++){
						$('[name=group]').append('<option value="' + data[i].Code + '">' + data[i].Name + '</option>');
					}
					//$('[name=group]').data('combobox').clearTarget();
					//$('[name=group]').data('combobox').clearElement();
					//$('[name=group]').data('combobox').refresh();

					$('[name=group]').each(function(){ //need to run in .each to refresh all the elements
						//$(this).data('combobox').refresh();
					});


				});
			});

    </script>





   </body>
 </html>
