<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<div class="content-wrapper" style="min-height: 1203.6px;">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<div class="container-fluid">
			<div class="row mb-2">
				<div class="col-md-6">
					<h1>Item - Entry</h1>
				</div>
				<div class="col-md-6">
				</div>
			</div>
		</div>
	</section>
	<section class="content">
		<div class="container-fluid">
			<div class="row">
				<div class="col-md-4">
					<div class="card card-outline card-primary">
						<div class="card-header">
							<h3 class="card-title">Input</h3>
						</div>
						<div class="overlay white" id="loading" style="display:none;position: absolute;width: 100%;height: 100%;z-index: 10000;">
							<i class="fas fa-3x fa-sync-alt rotate360"  style="margin: 70px 45%;"></i>
						</div>
						<form role="form">
							<div class="card-body">
								<div class="row">
									<div class="col-md-12">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
											<div class="col-md-8">
												<div class="input-group input-group">
													<select type="text" class="form-control" id="cboCity"></select>
												</div>
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Item Code: </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtItemCode">
												<input class="form-control" type="text" id="txtID" style="display:none;">
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Item Name: </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtItemName">
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Min. Stock Level:
											</label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtMinStockLevel" onfocus="this.select();" onkeypress="return isNumber(event)" onkeyup="btozero(this);" maxlength="9" style="text-align:right;" value="0">
											</div>
										</div>
										<div class="form-group row">
											<div class="col-md-4"></div>
											<div class="col-md-4 btnSave"></div>
											<div class="col-md-4 btnSave">
												<button type="button" class="btn btn-success btn-block"onclick="createItem();" id="btnSave">Save</button>
											</div>
											<div class="col-md-4 btnEdit" style="display: none;">
												<button type="button" class="btn btn-danger btn-block" onclick="clearForm()">Cancel</button>
											</div>
											<div class="col-md-4 btnEdit" style="display: none;">
												<button type="button" class="btn btn-primary btn-block" onclick="createItem()">Update</button>
											</div>
										</div>
									</div>
								</div>
							</div>
						</form>
					</div>
				</div>

				<div class="col-md-8">

					<div class="card card-outline card-primary">
						<div class="card-header">
							<h3 class="card-title">Item List<span id="total_records" style="font-weight:bold;"> </span></h3>
							<div class="card-tools">
								<button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
								<button type="button" class="btn btn-tool" data-card-widget="remove"><i class="fas fa-remove"></i></button>
							</div>
						</div>
						<div class="card-body p-0 table-responsive">
							<table class="table table-striped table-bordered" id="myTable">
								<thead>                  
									<tr>
										<th style="width: 3%">#</th>
										<th style="width: 15%">Item Code</th>
										<th>Item Name</th>
										<th style="width: 15%">Min. Stock Level</th>
										<th style="width: 3%;">Delete</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>
					</div>
				</div>

		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>
	var C = '<?php echo isset($_SESSION['city'])?$_SESSION['city']:""?>';
	var d = new Date();
  	var n = d.getTime();

	$(function() {
		$("body").addClass("sidebar-collapse");
		// getAll();
		if(C=='Main Office'){
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "'>" + C + "</option>");	
			getAll();
		}
	});

	$("#txtItemCode").on("keyup", function() {
		var value = $(this).val().toLowerCase();
		$("#myTable > tbody > tr ").filter(function() {$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
		});
	});

	function getAllCity(){
		$("#cboCity").find("option").remove();
		$("#cboCity").append("<option value= '-' data-id = ''></option>");
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				$("#cboCity").append("<option value= '" + v.name + "'>" + v.name + "</option>");			
			});	
			$("#cboCity").val('-');	
		});

	}

	$('#cboCity').change(function() { 
		getAll();
	});

	function createItem(){	
		$("#loading").css("display","block");
		var id = $("#txtID").val();
		var city = $("#cboCity").val();	
		var item_code = $("#txtItemCode").val();	
		var item_name = $("#txtItemName").val();	
		var min_stock_level = parseInt($("#txtMinStockLevel").val().replace(/,/g, ''));

		if(item_code=="" || item_name==""){
			bootbox.alert("Please fill the boxes.");
			$("#loading").css("display","none");
			return false;
		}else{
			$.ajax({
				url: APP_URL + "api/stock/item/create.php",
				type: "POST",
				data: JSON.stringify({ city: city, id: id, item_code: item_code, item_name: item_name, min_stock_level: min_stock_level }),
			}).done(function(data){
				$("#loading").css("display","none");
				if(data.message=="created"){
					bootbox.alert("Successfully Added.");
					getAll();
					clearForm();
				}else if(data.message=="duplicate"){
					bootbox.alert("Not allow duplicate rows.");
				}else if(data.message=="updated"){
					bootbox.alert("Successfully Updated");
					getAll();
					clearForm();
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}		
	}

	function btozero(obj){
		if($(obj).val() == "")$(obj).val(0);
	}

	function isNumber(evt) {
		evt = (evt) ? evt : window.event;
		var charCode = (evt.which) ? evt.which : evt.keyCode;
		if ( (charCode > 31 && charCode < 48) || charCode > 57) {
			return false;
		}
		return true;
	}


	function getAll(){
		var city = $("#cboCity").val();	
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/stock/item/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ city: city }),
		}).done(function(data) {
			console.log(data);
			$.each(data.records, function(i, v) {
				if(data.records){$("#total_records").text(" - " + data.records.length + " records");}else{$("#total_records").text(0 + " record(s) found.");}
				console.log(v);
				$("#myTable").find("tbody")
				.append($('<tr>')
					.append("<td style='width: 10px'>" + (i+1) + "</td>")
					.append("<td>" + v.item_code + "</td>")
					.append("<td>" + v.item_name + "</td>")
					.append("<td style='text-align:right;'>" + v.min_stock_level + "</td>")
.append("<td style='width: 70px;white-space: nowrap;'><span type='button' class='btn btn-primary btn-sm ' onclick='edit(\"" + v.id + "\", this)' style='padding: 0px 8px; min-width: 20px;' title='Edit'><i class='fas fa-edit'></i> </span> </td>")
					// <span class='btn btn-danger btn-sm' style='cursor:pointer; font-size: 12px; width: 40px;' onclick='delItem(\"" + v.id + "\", this)'><i class='fas fa-trash' title='Delete'></i></span>
					)
			});
		});
	}

	function clearForm(){
		$("#txtCustomer").attr("disabled", false);

		$(".btnSave").css("display", "block");
		$(".btnEdit").css("display", "none");
		$(".fa-edit").attr("disabled", false);

		$("#txtID").val("");
		$("#txtItemCode").val("");
		$("#txtItemName").val("");
		$("#txtMinStockLevel").val(0);

	}

	function delItem(id,obj){
		bootbox.confirm({
			message: "<h4>Are you sure that you want to delete?</h4>",
			buttons: {
				confirm: {
					label: '<span class="glyphicon glyphicon-ok"></span> Yes',
					className: 'btn-danger'
				},
				cancel: {
					label: '<span class="glyphicon glyphicon-remove"></span> No',
					className: 'btn-primary'
				}
			},
			callback: function (result) {
				if(result){
					$.ajax({
						type: "POST",
						url: APP_URL + "api/stock/item/delete.php",
						data: JSON.stringify({ id: id }),
						success: function(data){
							if(data=="deleted"){
								getAll();
								$(obj).parent().parent().remove();
							}else{
								bootbox.alert("Error on server side.");
							}
						}
					});
				}
			}
		});
	}

	function edit(id, obj){
		$("#txtItemName").focus();
		$("#txtItemCode").attr("disabled", true);

		$(".btnSave").css("display", "none");
		$(".btnEdit").css("display", "block");
		$(".fa-edit").attr("disabled", true);

		$(obj).attr("disabled", false);
		var tr = $(obj).parent().parent();


		$("#txtID").val(id);
		$("#txtItemCode").val($(tr).find("td").eq(1).text());
		$("#txtItemName").val($(tr).find("td").eq(2).text());
		$("#txtMinStockLevel").val($(tr).find("td").eq(3).text());
	}

</script>
