<?php 
$categoryID = $_REQUEST['id'];

 ?>
 <link href="../css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
 <script src="../js/fileinput.js" type="text/javascript"></script>
<div class="panel panel-default">
  <div class="panel-heading form-inline">
  	<a class="btn btn-success" role="button" style="float: right;" href="#" download="Catalog<?= "(" . date("m.d.Y") . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'catalog', 'Catalog');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
  	<div style="margin-right: 10px; float: right;">
  		<div class="input-group">
  			<div id="clearButton" style="display: none;" class="input-group-addon" onclick="clearFilter()">
  				<span class="glyphicon glyphicon-remove" aria-hidden="true"></span></div>
  		 	<input type="text"   class="form-control" name="filter" placeholder="Filter" value="" />
  			<div class="input-group-addon" onclick="filter()">
  		      	<span class="glyphicon glyphicon-search" aria-hidden="true"></span></div>
  		</div>
  			<button class="btn btn-primary" onclick="addCatalogItem()" >Add New Item</button>
  	</div>
  	
    <h3 class="panel-title">Catalog</h3>
    <small>Click on a row to edit the Item</small>
  </div>
  <div class="panel-body">
  <table class="table table-hover" id="catalog">
    <thead>
    	<tr>
    		<th>Group</th>
    		<th>Line</th>
    		<th>SKU</th>
    		<th>Description</th>
    		<th>Has Image</th>
    	</tr>
    </thead>
   <?php 
   	$query = "SELECT CATALOG_DETAIL.*, INVENTORY.Group, INVENTORY.Description FROM `CATALOG_DETAIL`, INVENTORY WHERE CategoryID = $categoryID AND CATALOG_DETAIL.SKU = INVENTORY.SKU AND CATALOG_DETAIL.LINE = INVENTORY.LINE ORDER BY INVENTORY.`Line`, INVENTORY.`SKU` ASC";
   	$result = mysqli_query($con, $query);
   	while ($row = mysqli_fetch_array($result)) {
   ?>
   		<tr onclick="editCatalogItem('<?= $row['id'] ?>')">
   			<td><?= $row['Group'] ?></td>
   			<td><?= $row['Line'] ?></td>
   			<td><?= $row['SKU'] ?></td>
   			<td><?= $row['Description'] ?></td>
   			<!--  -->
   			<td id="hasImage-<?= $row['id'] ?>"><?= hasImage($row['Line'], $row['SKU'], true)?"Yes":"No" ?></td>
   		</tr>
   <?php		
   	}
    ?>
    </table>
  </div>
</div>


<div class="modal fade" id="AddEditCatalogItem">
  <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 Catalog Item</h4>
      </div>
      <div class="modal-body">
      	<form class="catalogItem">
      		<input type="hidden" id="isNew" name="isNew" value="" />
      		<input type="hidden" id="CatalogItemID" name="CatalogItemID" value="" />
      		<input type="hidden" id="CategoryID" name="CategoryID" value="" />
      		<div class="form-group">
      		    <label for="CatalogItemLine">Line</label>
      		    <select class="form-control combobox" id="CatalogItemLine" name="CatalogItemLine">
      		    <option></option>
      		    <?php
      		    	$query = "SELECT * FROM `LINE` ORDER BY Name";
      		    	$result = mysqli_query($con, $query);
      		    	while ($row = mysqli_fetch_array($result)) {
      		    ?>
      		    	<option value="<?= $row['Code'] ?>"><?= $row['Code'] . " - " . $row['Name'] ?></option>
      		    <?php
      		    	}
      		    ?>
      		    </select>
      		</div>
      		<div class="form-group">
      		    <label for="CatalogItemSKU">SKU</label>
      		    <input type="text" class="form-control small" name="CatalogItemSKU" autocomplete="off" id="CatalogItemSKU" placeholder="SKU">
      		</div>
      		
      		<div class="form-group">
      			<div id="imagePreviewDiv" style="height: 150px; text-align: center; vertical-align: middle;" id="">
      				
      				<img id="imagePreview" style="max-height: 100%; max-width: 100%;"src="" alt="" />
      			</div>
      			<div class="alert alert-info" style="display: none;" id="uploadSuccess" role="alert">
      			  	File has been uploaded successfully!</div>

      		    <label for="CatalogItemImage">Image</label>
      		    <input type="file" class="file form-control" name="CatalogItemImage" autocomplete="off" id="CatalogItemImage">
      		</div>
      	</form>
      </div>
      <div class="modal-footer">
      	<button type="button" class="btn btn-danger" id="deleteButton" onclick="deleteCatalogItem()" data-dismiss="modal">Delete</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="saveButton" onclick="saveCatalogItemInfo()">Save</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
	$('[name=filter]').on('keypress', function(e) {
		if (e.which == 13) {
			filter();
		}
	
	});
	$($('input[type=text]')[$('input[type=text]').length-1]).keydown(function(e){
			if(e.which == 13)
				$('#saveButton').click();
		
		});
	function clearFilter() {
		$('[name=filter]').val("");
		$('#clearButton').css('display', 'none');
		$('tr').css('display', '');
		
	}
	function filter() {
		var	name = $('[name=filter]').val();
		filterByName(name);
	}
	function filterByName(name) {
		$('#clearButton').css('display', '');
		for (var i = 0; i < $('tr').length; i++) {
			if (i != 0) {
				var result = $('tr')[i].innerText.toUpperCase().indexOf(name.toUpperCase());
				if (result < 0) {
					$($('tr')[i]).css('display', 'none');
				}else {
					$($('tr')[i]).css('display', '');
				}
			}
		}
	}
	function clearModal() {
		$('#isNew').val("0");
		$('#CatalogItemID').val("-1");
		$('#CategoryID').val("-1");
		$('#CatalogItemGroup').val("");
		$('#CatalogItemLine').val("");
		$('#CatalogItemSKU').val("");
		$('#CatalogItemPrice').val("");
		$('#CatalogItemUPC').val("");
		$('#saveButton').css('display', '');
		$('#CatalogItemLine').data('combobox').clearTarget()
		$('#CatalogItemLine').data('combobox').clearElement()
		$('#CatalogItemLine').data('combobox').refresh();
		$("#uploadSuccess").css('display', 'none');
		
	}
	function addCatalogItem() {
		clearModal();
		$('#isNew').val("1");
		$('#AddEditTitle').text("Add Price List Item");
		$('#CategoryID').val("<?= $categoryID ?>");
		$('#deleteButton').css('display', 'none');
		$('#imagePreviewDiv').css('display', 'none');
		$('#AddEditCatalogItem').modal('toggle');
	}
	function editCatalogItem(ID) {
		clearModal();
		$.get("functions.php?action=getCatalogItemInfo&id=" + ID, function(data){
		 	var catalogItem = JSON.parse(data);
		 	$('#isNew').val("0");
			$('#AddEditTitle').text("Edit Catalog Item");
			$('#CatalogItemID').val(ID);
			$('#CategoryID').val(catalogItem.CategoryID);
			$('#CatalogItemLine').val(catalogItem.Line);
			$('#CatalogItemSKU').val(catalogItem.SKU);
			$('#deleteButton').css('display', '');
			$('#saveButton').css('display', 'none');
			$('#imagePreviewDiv').css('display', '');
			$('#imagePreview').attr('src', catalogItem.Image);
			$('#CatalogItemLine').data('combobox').refresh();
			$('#AddEditCatalogItem').modal('toggle');
		});
	}
	function saveCatalogItemInfo() {
		var catalogItem = '{ "CategoryID" : "' + $('#CategoryID').val() + '", "Line" : "' + $('#CatalogItemLine').val() + '", "SKU" : "' + $('#CatalogItemSKU').val() + '", "ID" : "' + $('#CatalogItemID').val() + '", "IsNew" : "' + $('#isNew').val() + '"}';
		catalogItem = JSON.parse(catalogItem);
		$.get("functions.php?action=catalogItemExists&line=" + $('#CatalogItemLine').val() + "&sku=" + $('#CatalogItemSKU').val(), function(data) {
			data = JSON.parse(data);
			if (data.rowCount > 0) {
				var categories = "";
				for (var i = 0; i < data.rows.length; i++) {
					categories = categories + data.rows[i].Name + "\n";
				}
				
				if (confirm("This item is already in the following category(ies):\n" + categories + "\n\nAre you sure you want to continue?")) {
					$.post( "functions.php?action=saveCatalogItemInfo", catalogItem)
					  .done(function( data ) {
					  	data = JSON.parse(data);
					    if (data.result === true) {
					      	clearModal();
					      	$('#AddEditCatalogItem').modal('toggle');
					      	location.reload();
					      }else {
					      	alert("There has been an error saving the price list data.\r\n\r\nMySQL Error: " + data.error);
					      }
					    });
				}
			}else {
				$.post( "functions.php?action=saveCatalogItemInfo", catalogItem)
				  .done(function( data ) {
				  	data = JSON.parse(data);
				    if (data.result === true) {
				      	clearModal();
				      	$('#AddEditCatalogItem').modal('toggle');
				      	location.reload();
				      }else {
				      	alert("There has been an error saving the price list data.\r\n\r\nMySQL Error: " + data.error);
				      }
				    });
			}
		
		
		});
		
	}
	function deleteCatalogItem() {
		if (confirm("Are you sure you want to delete this item from the Price List? This cannot be undone.")) {
			var itemID = $('#CatalogItemID').val();
			$.post( "functions.php?action=deleteCatalogItem&ID=" + itemID, null)
			  .done(function( data ) {
			  data = $.parseJSON(data);
			    if (data.result == true) {
			    	clearModal();
			    	//$('#AddEditCatalogItem').modal('toggle')
			    	location.reload(true);
			    }else {
			    	alert("There has been an error deleting the item.");
			    }
			  });
		  }
		
	}
	$('#CatalogItemGroup').combobox();
	$('#CatalogItemLine').combobox();
	$("#CatalogItemImage").fileinput({
		'showUpload':true, 
		'showPreview': false,
		'uploadUrl':"upload_image.php",
		'uploadExtraData': function (previewId, index) {
		    var obj = {};
		    $('.catalogItem').find('input').each(function() {
		        var id = $(this).attr('id'), val = $(this).val();
		        obj[id] = val;
		    });
		    $('.catalogItem').find('select').each(function() {
		        var id = $(this).attr('id'), val = $(this).val();
		        obj[id] = val;
		    });
		    return obj;
		},
		'fileTypeSettings':'image',
		'elErrorContainer':'#uploadError',
	});
	$('#CatalogItemImage').on('filebatchselected', function(event, files) {
	console.log('heee');
	    
	});
	
	
	$('#CatalogItemImage').on('filebatchuploadsuccess', function(event, data, previewId, index) {
	    response = data.response;
	    if(response.fileuploaded == true){
	    console.log(response);
	    	$("#uploadSuccess").text(response.message);
			$("#uploadSuccess").css('display', "");
			$('#imagePreviewDiv').css('display', '');
			$('#imagePreview').attr('src', response.url);
			
						
	    }
	    
	});
	$('#CatalogItemImage').on('fileuploaded', function(event, data, previewId, index) {
	    response = data.response;
	    if(response.fileuploaded == true){
	    	$("#uploadSuccess").text(response);
	    	$("#uploadSuccess").css('display', "");
	    				
	    }
	    
	});
	</script>
