<?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'] == false){
			header("Location: index.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" => ""
);

	

?>
 
 <!DOCTYPE html>
 
 <html lang="en">
   <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">
	 
     <title><?= $config['CompanyName'] ?> - Truck Inventory</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">
		<link rel="manifest" href="img/manifest.json">
		<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>");
					   }elseif(isset($_SESSION['setCustomerMode']) && $_SESSION['setCustomerMode']) {
						   $customer = new Customer($_SESSION['setCustomer']);
						   echo("<i>" . $customer->AccountNumber . " - " . $customer->Name . "</i>");
					   }
					}
					$truck = new Warehouse($_SESSION['WarehouseID']);
					 ?>
				</h3>
				<span>Truck Mode - <b><?= $truck->WarehouseName ?></b></span>
				<div class="well well-sm" style="height: 70px;">
					<div class="col-xs-3"><a style="font-size: 40px;" href="cart.php">🛒</a></div>
					
					<div class="col-xs-3"><a style="font-size: 40px;" href="mod.php?p=payment&a=new">💰</a></div>
					<div class="col-xs-3"><a style="font-size: 40px;" onclick="$('#navbarClearCustomer').click();">👥</a></div>
					<div class="col-xs-3"><a style="font-size: 40px;" onclick="$('#truckModeWarehouseModal').modal();"><img  style="height: 40px;" src="img/truck.png" /></a></div>
					
				</div>
			</center>
		</div>
<?php 
 
 
 
 	
	
	
	$isSalesman = (!$isCustomer) ? 'true' : 'false';
	
 
 
 /**/
 	$AccountNumber = ($_SESSION['isCustomer'])?$_SESSION['AccountNumber']:$_SESSION['SalesmanID'];
 	
 	$query = "SELECT INVENTORY.*, MULTIPLE_WH_INVENTORY.Qty TruckQty, SHOPPING_CART.Qty AS OnOrder, 1 SortOrder, 0 as Reference, \"\" AS Supplier FROM MULTIPLE_WH_INVENTORY JOIN `INVENTORY` USING(Line, SKU) 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 MULTIPLE_WH_INVENTORY.WarehouseID = " . $_SESSION['WarehouseID'];
 	
	
 	$where = "";
 	$index = 0;
 	
 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);
 
 $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['TruckQty']);
		}else{
			$qty = ($row['TruckQty'] > 50)?"50+":$row['TruckQty'];
		}
		
		$qty = ($qty < 0)?"0":$qty;
		if($index%4 == 0){
			echo "<div class=\"row\">";
		}
?>
	
				<div class="col-md-3 col-sm-2">
					<div 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>";
								}
								if ($isCustomer || $pricePlanMode) {
									$price = getCustomerPrice($row['Group'], $row['Line'], $row['SKU']) * (getPricePlanCalculatedRate($_SESSION['AccountNumber']));
								 echo moneyFormat($price);	
								} else {
									$price = getCustomerPrice($row['Group'], $row['Line'], $row['SKU']);
									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>
						  <p>
							<?= $product->Description . " " . $product->Notes ?>
							<br>
							 
							
							
						  </p>
						</div>
						<p>
							<div class="row">
								<div class="col-xs-6">
									
								</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">
									<?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-8" style="text-align: right; padding-right: 30px;">
									<?php
										if(!$row['Active']){
									?>
									<span style="color: red;">WHILE SUPPLIES LAST</span><br>
									<?php
										}
									?>
									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){
 	
 	$queryString = $_SERVER['PHP_SELF'] . "?";
 	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")?"Si tiene duda con respecto a la disponibilidad de una pieza no dude en contactar a su vendedor.":"If you have any questions regarding the availability of a part, don't hesitate to contact us." ?>
		
		<?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);
      		}
      	});
      
      }
      
      
      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>