<?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("session.php");
}
?>
 
 <!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">
     <title><?= $config['CompanyName'] ?></title>
 
     <!-- Bootstrap -->
     <link href="../css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="../css/bootstrap-combobox.css" />
 
     <!-- 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>
       <!-- 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"></script>
       	 <script src="../js/bootstrap-combobox.js"></script>
       	 <script src="../js/excellentexport.js"></script>
				 <script src="../js/functions.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
       //        $('.grpline').css("width", "100px");
             });
           </script>

     <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
	<link href="../css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
		<script src="../js/fileinput.js" type="text/javascript"></script>
   </head>
   <body>
   
       <?php
		include_once("./navbar.php");						
		?>     

   
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->
<div class="container" style="padding-top: 10px; width: 96%;">
	<div class="panel panel-default">
	  <div class="panel-heading form-inline">
		<a class="btn btn-success" role="button" style="float: right;" href="#" download="InventoryReport<?= "(" . date("m.d.Y") . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'inventoryTable', 'Inventory');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
		<h3 class="panel-title">Manage Inventory</h3>
		<span>This page is used to perform minor updates to inventory without the need to upload CSV files.</span>
		<br>
		<span>Please Click on a inventory item to edit it or type "%" in the SKu box to see all items.</span>
		<br><br>
		<button class="btn btn-success pull-right" onclick="addInventoryItem();">Add New Inventory Item</button>
		<form class="form pull-left">
			<?php
				foreach($_REQUEST as $key => $value){
					echo "<input type=\"hidden\" name=\"$key\" value=\"$value\" />\n";
				}
			
			?>
			<div class="form-group">
				<label for="sku">SKU:</label>
				<input class="form-control" type="text" name="sku" value="<?= isset($_REQUEST['sku'])?$_REQUEST['sku']:"" ?>" />
				
				<label for="desc">Description:</label>
				<input class="form-control" type="text" name="desc" value="<?= isset($_REQUEST['desc'])?$_REQUEST['desc']:"" ?>" />
				<input type="submit" class="btn" />
			</div>
		</form>
		<br><br>
	  </div>
	  <div class="panel-body">
	  	<table class="table table-hover table-condensed" id="inventoryTable">
	  		<thead>
	  			<tr>
	  				<th>Line</td>
					<td>Group</th>
	  				<th>SKU</th>
					<th>Description</th>
					<th>OnHand</th>
					<th>Cost</th>
					<th>Cost+15%</th>
					<th>Price A</th>
					<th>PM A</th>
					<th>Price B</th>
					<th>PM B</th>
					<th>Price C</th>
					<th>Price D</th>
					<th>Price E</th>
					<th>Location</th>
					
	  			</tr>
	  		</thead>
	    <?php
			$sku = $_REQUEST['sku'];
			$desc = $_REQUEST['desc'];
			if($sku != "" || $desc != ""){
				if($sku == ""){
					$sku = "%";
				}
				if($desc == ""){
					$desc = "%";
				}
			}
			$query = "SELECT * FROM INVENTORY WHERE REPLACE(SKU,'-','') LIKE REPLACE('" . $sku  . "','-','') AND Description LIKE '%$desc%' ORDER BY SKU";
			$result = mysqli_query($con, $query);
			while($row = mysqli_fetch_array($result)){
		?>
		<tr onclick="editInventoryItem('<?= $row['Group'] . "," . $row['Line'] . "," . $row['SKU']?>')" data-id="'<?= $row['Group'] . "," . $row['Line'] . "," . $row['SKU']?>'">
			<td><?= $row['Line'] ?></td><td><?= $row['Group'] ?></td>
			<td><b><?= $row['SKU'] ?></b><?= $row['Interchange']?" (" . $row['Interchange'] . ")":"" ?><?= (hasImage($row['Line'], $row['SKU'], true))?"<img style=\"width: 28px;\" src=\"../img/icon-camera-32.png\" /></a>":"" ?></td>
			<td><?= $row['Description'] . " " . $row['Notes'] ?></td>
			<td><?= $row['Qty'] ?></td>
			<td><?= moneyFormat($row['AvgCost']) ?></td>
			<td><?= moneyFormat($row['AvgCost']/.85) ?></td>
			<td><?= moneyFormat($row['PriceA']) ?></td>
			<td><?= round(($row['PriceA']-$row['AvgCost']/.85)/$row['PriceA']*100,2) . "%" ?></td>
			<td><?= moneyFormat($row['PriceB']) ?></td>
			<td><?= round(($row['PriceB']-$row['AvgCost']/.85)/$row['PriceB']*100,2) . "%" ?></td>
			<td><?= moneyFormat($row['PriceC']) ?></td>
			<td><?= moneyFormat($row['PriceD']) ?></td>
			<td><?= moneyFormat($row['PriceE']) ?></td>
			<td><?php
			
				echo $row['Location'];
				if($row['LocationB']){
					echo "<br>" . $$row['LocationB'];
				}
				if($row['LocationC']){
					echo "<br>" . $$row['LocationC'];
				}
				if($row['LocationD']){
					echo "<br>" . $$row['LocationD'];
				}
				if($row['LocationE']){
					echo "<br>" . $$row['LocationE'];
				}
				
			
			?></td>
			
		</tr>
		<?php
		}
		?>
	     </table>
	  </div>
	  <div class="panel-footer" style="height: 100px;" >
	  </div>
	</div>
</div>

<div class="modal fade" id="AddEditInventoryItem">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="AddEditTitle">Edit Inventory Item</h4>
            </div>
            <div class="modal-body">
                <form class="catalogItem">
                    <input type="hidden" id="isNew" name="isNew" value="" />
                    <input type="hidden" id="InventoryItemID" name="InventoryItemID" value="" />
                    <div class="form-group">
                        <label for="InventoryItemLine">Line</label>
                        <input class="form-control" disabled type="text" id="InventoryItemLine" name="InventoryItemLine" />
                    </div>
					<div class="form-group">
                        <label for="InventoryItemGroup">Group</label>
                        <input class="form-control" disabled type="text" id="InventoryItemGroup" name="InventoryItemGroup" />
                    </div>
					<div class="form-group">
                        <label for="InventoryItemSKU">SKU</label>
                        <input class="form-control" disabled type="text" id="InventoryItemSKU" name="InventoryItemSKU" />
                    </div>
					<div class="form-group">
                        <label for="InventoryItemInterchange">Interchange</label>
                        <input class="form-control" type="text" id="InventoryItemInterchange" name="InventoryItemInterchange" />
                    </div>
                    <div class="form-group">
                        <label for="InventoryItemDescription">Description</label>
                        <input class="form-control" type="text" id="InventoryItemDescription" name="InventoryItemDescription" />
                    </div>
                    <div class="form-group">
                        <label for="InventoryItemNotes">Notes</label>
                        <input class="form-control" type="text" id="InventoryItemNotes" name="InventoryItemNotes" />
                    </div>
					<div class="row">
						<div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemOnHand">On Hand</label>
								<input class="form-control" type="text" id="InventoryItemOnHand" name="InventoryItemOnHand" />
							</div>
						</div>
						<div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemAvgCost">Cost</label>
								<input class="form-control" type="text" id="InventoryItemAvgCost" name="InventoryItemAvgCost" />
							</div>
						</div>
						<div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemPriceA">Price A</label>
								<input class="form-control" type="text" id="InventoryItemPriceA" name="InventoryItemPriceA" />
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemPriceB">Price B</label>
								<input class="form-control" type="text" id="InventoryItemPriceB" name="InventoryItemPriceB" />
							</div>
						</div>	
						<div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemPriceC">Price C</label>
								<input class="form-control" type="text" id="InventoryItemPriceC" name="InventoryItemPriceC" />
							</div>
						</div>
						<div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemPriceD">Price D</label>
								<input class="form-control" type="text" id="InventoryItemPriceD" name="InventoryItemPriceD" />
							</div>
						</div><div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemPriceE">Price E</label>
								<input class="form-control" type="text" id="InventoryItemPriceE" name="InventoryItemPriceE" />
							</div>
						</div>
						<div class="col-md-4">
							<div class="form-group">
								<label for="InventoryItemCore">Core</label>
								<input class="form-control" type="text" id="InventoryItemCore" name="InventoryItemCore" />
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-md-12">
							<div class="form-group" id="InventoryItemImageDiv">
								<div id="InventoryItemImagePreviewDiv" style="height:
									150px; text-align: center; vertical-align: middle;" id="">
									<img id="InventoryItemImage" style="max-height:
										100%; max-width: 100%;" src="" alt="" />
								</div>
								<div class="alert alert-info" style="display:
									none;" id="uploadButtonSuccess" role="alert">
									File has been uploaded successfully!
								</div>
		
								<label for="InventoryItemImageInput">Item Image</label>
								<input type="file" class="file form-control" name="InventoryItemImageInput" autocomplete="off" id="InventoryItemImageInput">
							</div>
						</div>
					</div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="deleteButton" onclick="deleteInventoryItem()">Delete</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="saveButton" onclick="saveInventoryItemInfo();">Save</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<script type="text/javascript">
	
	function clearInventoryManageModal(){
		$('#isNew').val("0");
		$('#InventoryItemID').val("-1");
		$('#InventoryItemLine').val("");
		$('#InventoryItemLine').removeAttr("disabled");
		$('#InventoryItemGroup').removeAttr("disabled");
		$('#InventoryItemSKU').removeAttr("disabled");
		$('#InventoryItemGroup').val("");
		$('#InventoryItemSKU').val("");
		$('#InventoryItemDescription').val("");
		$('#InventoryItemNotes').val("");
		$('#InventoryItemOnHand').val("");
		$('#InventoryItemPrice').val("");
		$('#InventoryItemPriceF').val("");
		$('#InventoryItemPriceC').val("");
		$('#InventoryItemPriceG').val("");
		$('#InventoryItemCore ').val("");
		$('#InventoryItemImagePreviewDiv').css('display', 'none');
		$('#InventoryItemImage').attr('src', '');	
		$('#saveButton').css('display', '');
		$('#deleteButton').css('display', '');
		$("#uploadSuccess").css('display', 'none');
		
	}
	function addInventoryItem(){
		clearInventoryManageModal();
		$('#isNew').val("1");
		$('#AddEditTitle').text('Add New Inventory Item');
		$('#deleteButton').css('display', 'none');
		$('#InventoryItemLine').attr('disabled', false);
		$('#InventoryItemGroup').attr('disabled', false);
		$('#InventoryItemSKU').attr('disabled', false);
		$('#InventoryItemImagePreviewDiv').css('display', 'none');
		$('#AddEditInventoryItem').modal('toggle');
	}
	function editInventoryItem(id){
		clearInventoryManageModal();
		$('#isNew').val("0");
		$('#AddEditTitle').text('Edit Inventory Item');
		$('#SupplierCatalogID').val(id);
		$.get('mod.php?p=inventorymanage&a=functions&f=getInventoryItem&iid=' + id, function(data){
			data = JSON.parse(data);
			$('#InventoryItemID').val(id);
			$('#InventoryItemLine').val(data.Line);
			$('#InventoryItemGroup').val(data.Group);
			$('#InventoryItemSKU').val(data.SKU);
			$('#InventoryItemInterchange').val(data.Interchange);
			$('#InventoryItemDescription').val(data.Description);
			$('#InventoryItemNotes').val(data.Notes);
			$('#InventoryItemOnHand').val(data.Qty);
			$('#InventoryItemAvgCost').val(data.AvgCost);
			$('#InventoryItemPriceA').val(data.PriceA);
			$('#InventoryItemPriceB').val(data.PriceB);
			$('#InventoryItemPriceC').val(data.PriceC);
			$('#InventoryItemPriceD').val(data.PriceD);
			$('#InventoryItemPriceE').val(data.PriceE);
			$('#InventoryItemCore ').val(data.Core);
			if(data.Image){
				$('#InventoryItemImagePreviewDiv').css('display', '');
				$('#InventoryItemImage').attr('src', data.Image);	
			}
			$('#saveButton').css('display', '');
			$('#deleteButton').css('display', '');
			$('#AddEditInventoryItem').modal('toggle');
		});
		
		
	}
	function saveInventoryItemInfo(){
		var data = {};
		data.IsNew = $('#isNew').val();
		
		data.id = $('#InventoryItemID').val();
		data.Line = $('#InventoryItemLine').val();
		data.Group = $('#InventoryItemGroup').val();
		data.SKU = $('#InventoryItemSKU').val();
		data.Description = $('#InventoryItemDescription').val();
		data.Interchange = $('#InventoryItemInterchange').val();
		data.Notes = $('#InventoryItemNotes').val();
		data.Qty = $('#InventoryItemOnHand').val();
		data.AvgCost = $('#InventoryItemAvgCost').val();
		data.PriceA = $('#InventoryItemPriceA').val();
		data.PriceB = $('#InventoryItemPriceB').val();
		data.PriceC = $('#InventoryItemPriceC').val();
		data.PriceD = $('#InventoryItemPriceD').val();
		data.PriceE = $('#InventoryItemPriceE').val();
		data.Core = $('#InventoryItemCore').val();
		
	
		$.post('mod.php?p=inventorymanage&a=functions&f=saveInventoryItem', data)
			.success(function(response){
				if(response == "true"){
					$('#AddEditInventoryItem').modal('toggle');
					location.reload();
				}else{
					alert('An error has occurred inserting/updating the data into the table.');
				}
			})
			.fail(function(response){
				alert('An error has occurred either with the connection or the server has returned an unexpected http code.');
			});
	}
	function deleteInventoryItem(){
		$.get('mod.php?p=inventorymanage&a=functions&f=deleteInventoryItem&iid=' +  $('#InventoryItemID').val(), function(response){
			if(response == "true"){
				$('#AddEditInventoryItem').modal('toggle');
				location.reload();
			}else{
				alert("Error occurred, cant't delete.");
			}
		});
		
	}
	
	$("#InventoryItemImageInput").fileinput({
		'showUpload':true, 
		'showPreview': false,
		'uploadUrl':"mod.php?p=inventorymanage&a=upload_image",
		'uploadExtraData': function (previewId, index) {
		    var obj = {};
		    obj.Filename = $('#InventoryItemLine').val() + " " + $('#InventoryItemSKU').val();
		    return obj;
		},
		'fileTypeSettings':'image',
		'elErrorContainer':'#uploadError',
	});
	$('#InventoryItemImageInput').on('filebatchuploadsuccess', function(event, data, previewId, index) {
		response = data.response;
		if(response.fileuploaded === true){
		console.log(response);
			$("#uploadButtonSuccess").text(response.message);
			$("#uploadButtonSuccess").css('display', "");
			$('#InventoryItemImagePreviewDiv').css('display', '');
			$('#InventoryItemImage').attr('src', response.url);				   
		}
	});
</script>

   </body>
   
 </html>