<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<style>
	#myTable1 td:nth-child(6), #myTable1 td:nth-child(7){
		text-align: right;
		padding-right: 30px;
	}	
	div.dataTables_wrapper div.dataTables_info {
	    display: none;
	}
	.tdr{
		text-align: right;
	}
</style>

<style>
	.autocomplete-items {
		position: absolute;
		border: 1px solid #d4d4d4;
		border-bottom: none;
		border-top: none;
		z-index: 99;
		/*position the autocomplete items to be the same width as the container:*/
		top: 100%;
		left: 8px;
		right: 8px;
		max-height: 300px;
		overflow-y: auto;
	}
	.autocomplete-items div {
		padding: 10px;
		cursor: pointer;
		background-color: #fff;
		border-bottom: 1px solid #d4d4d4;
	}
	.autocomplete-items div:hover {
		/*when hovering an item:*/
		background-color: #e9e9e9;
	}
	.autocomplete-active {
		/*when navigating through the items using the arrow keys:*/
		background-color: DodgerBlue !important;
		color: #ffffff;
	}
	.switch {
	  position: relative;
	  display: inline-block;
	  width: 60px;
	  height: 25px;
	  margin-top: 6px;
	}

	/* Hide default HTML checkbox */
	.switch input {
	  display:none;
	}

	/* The slider */
	.slider {
	  position: absolute;
	  cursor: pointer;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  background-color: #ccc;
	  -webkit-transition: .4s;
	  transition: .4s;
	}

	.slider:before {
	  position: absolute;
	  content: "";
	  height: 22px;
	  width: 22px;
	  left: 5px;
	  bottom: 1px;
	  background-color: white;
	  -webkit-transition: .4s;
	  transition: .4s;
	}

	input:checked + .slider {
	  background-color: #dc3545;
	}

	input:focus + .slider {
	  box-shadow: 0 0 1px #dc3545;
	}

	input:checked + .slider:before {
	  -webkit-transform: translateX(26px);
	  -ms-transform: translateX(26px);
	  transform: translateX(26px);
	}

	/* Rounded sliders */
	.slider.round {
	  border-radius: 34px;
	}

	.slider.round:before {
	  border-radius: 50%;
	}
</style>
<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>Stock Transfer</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-12">
					<form role="form" id="frmEntry">	
						<div class="card card-outline card-primary">
							<div class="card-header">
								<h3 class="card-title">Entry</h3>
							</div>
							
							<div class="card-body">		
								<div class="row">
									<div class="col-md-4">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Date: </label>
											<div class="col-md-8">  
												<div class="input-group">
													<div class="input-group-prepend">
														<span class="input-group-text" style="width: 40px;">
															<i class="far fa-calendar-alt"></i>
														</span>
													</div>
													<input type="text" class="form-control" id="txtDatePicker" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
												</div>
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Store From: </label>
											<div class="col-md-8">
												<select type="text" class="form-control" id="cboCityFrom"></select>
											</div>
										</div>
                                        <div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Store To: </label>
											<div class="col-md-8">
												<select type="text" class="form-control" id="cboCityTo"></select>
											</div>
										</div>


									</div>
									<div class="col-md-4">
										<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" disabled>
											</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;">Qty: </label>
											<div class="col-md-8">
												<input type="number" class="form-control" onfocus="this.select();" onkeyup="btozero(this);" id="txtQuantity" value="1" min="1" style="text-align:right;">
											</div>
										</div>
									</div>
									<div class="col-md-4" style="padding-right: 27px;">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Remark:
											</label>
											<div class="col-md-8">
												<textarea type="text" class="form-control" rows="2" id="txtRemark" ></textarea>
											</div>
										</div>
										<div class="form-group row" style="margin-top: 22px;">
											<div class="col-md-7"></div>
											<div class="col-md-5">
												<button type="button" class="btn btn-primary btn-block" onclick="create()">Save</button>
											</div>
										</div>
									</div>

								</div>
							</div>
						</div>
						<div class="card card-outline">
							<div class="card-header">
								<h3 class="card-title">Transfer 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: 10%;">Date</th>
											<th style="width: 10%;">Store From</th>
											<th style="width: 10%;">Store To</th>
											<th style="width: 10%;">Item Code</th>
											<th>Item Name</th>
											<th style="width: 7%;">Qty</th>
											<th style="width: 25%;">Remark</th>
											<th style="width: 3%;">Delete</th>
										</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>
						</div>
					</form>
				</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 mm = (d.getMonth("MM")+1);
	var dd = d.getDate();
	var customDate = d.getFullYear() + "-" + ((mm<10)?"0" + mm:mm) + "-" +  ((dd<10)?"0" + dd:dd);

	$(function() {
		$("body").addClass("sidebar-collapse");
		$('#txtDatePicker').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',
			showButtonPanel: true,
            showAnim: 'clip',
            autoclose: true
        }).val(customDate);
		autocomplete(document.getElementById("txtItemName"));
		if(C=='Main Office'){
			getAllCity();
		}else{
			$("#cboCityFrom").append("<option value= '" + C + "'>" + C + "</option>");	
			getAllCityBranch();
		}
	});

	function getAllCity(){
		$("#cboCityFrom").find("option").remove();
		$("#cboCityTo").find("option").remove();
		$("#cboCityTo").append("<option value= '' data-id = '' class=''></option>");
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				$("#cboCityTo").append("<option value= '" + v.name + "' id= '" + v.id + "' class='T'>" + v.name + "</option>");	
				$("#cboCityFrom").append("<option value= '" + v.name + "' data-id= '" + v.id + "' >" + v.name + "</option>");
			});	
			$("#cboCityFrom").val(C);	
			$('#'+ $("#cboCityFrom option:selected").attr("data-id")).attr("style", "display:none;");
		});
	}

		function getAllCityBranch(){
		$("#cboCityTo").find("option").remove();
		$("#cboCityTo").append("<option value= '' data-id = '' class=''></option>");
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				if(v.name!=C){
					$("#cboCityTo").append("<option value= '" + v.name + "' id= '" + v.id + "' class='T'>" + v.name + "</option>");	
				}
				
			});	
			// $("#cboCity").val(C);	
			// $('#'+ $("#cboCity option:selected").attr("data-id")).attr("style", "display:none;");	
		});
	}

	$('#txtDatePicker').on('change',function(){
        getStockList();
	});
	$('#cboCityFrom').on('change',function(){
		$('#cboCityTo').val("");
		$(".T").attr("style", "display:block;");
		$('#'+ $("#cboCityFrom option:selected").attr("data-id")).attr("style", "display:none;");
        getStockList();
	});
	$('#cboCityTo').on('change',function(){
        getStockList();
	});

	function getStockList(){
		var stock_transfer_date = $("#txtDatePicker").val();
		var store_from = $("#cboCityFrom").val();
		var store_to = $("#cboCityTo").val();
		$.ajax({
			url: APP_URL + "api/stock/transfer/search.php",
			type: "POST",
			data: JSON.stringify({ stock_transfer_date: stock_transfer_date, store_from: store_from, store_to: store_to })
		}).done(function(data){
			$("#loading").css("display","none");
			$("#myTable").find("tbody").find("tr").remove();
			if(data.records){$("#total_records").text(" - " + data.records.length + " record(s) found.");}else{$("#total_records").text(0 + " record(s) found.");}
			$.each(data.records, function(i, v) {	
				$("#myTable").find("tbody")
				.append($('<tr>')
					.append("<td style='width: 10px' class='order'>" + (i+1) + "</td>")
					.append("<td>" + v.stock_transfer_date + "</td>")
					.append("<td>" + v.store_from + "</td>")
					.append("<td>" + v.store_to + "</td>")
					// .append("<td>" + v.stock_transfer_by + "</td>")
					.append("<td>" + v.item_code + "</td>")
					.append("<td>" + v.item_name + "</td>")
					.append("<td style='text-align:right;'>" + v.quantity + "</td>")
					.append("<td>" + v.remark + "</td>")
					.append("<td style='width: 70px;white-space: nowrap;'> <span type='button' class='btn btn-danger btn-sm' onclick='del(\"" + v.id + "\",this)' style='padding: 0px 8px; min-width: 20px;' title='Delete'><i class='fas fa-trash'></i></span></td>")
				);
			});
			
			$("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;">')
			.append("<td colspan='6' style='text-align:right;'>Total:</td>")
			.append("<td style='text-align:right;'>" + ((data.total)?data.total:0).toLocaleString() + "</td>")
  			);  
        });
	}

	function del(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/transfer/delete.php",
					data: JSON.stringify({ id: id }),
					success: function(data){
						if(data=="deleted"){
							$(obj).parent().parent().remove();
							getStockList();
						}else{
							bootbox.alert("Error on server side.");
						}
					}
					});
				}
			}
		});
	}

	function create(){
		var stock_transfer_date = $("#txtDatePicker").val();
		var store_from = $("#cboCityFrom").val();
		var store_to = $("#cboCityTo").val();
		var transfer_by = "";
		var item_code = $("#txtItemCode").val();
		var item_name = $("#txtItemName").val();
		var quantity = parseInt($("#txtQuantity").val().replace(/,/g, ''));
		var remark = $("#txtRemark").val();
		if(quantity==0){
			bootbox.alert("Qty can't be 0.");
		}else{
			$.ajax({
				type: "POST",
				url: APP_URL + "api/stock/transfer/create.php",
				data: JSON.stringify({ stock_transfer_date: stock_transfer_date, store_from: store_from, store_to: store_to, transfer_by: transfer_by, item_code: item_code, item_name: item_name, quantity: quantity, remark: remark }),
				success: function(data){	
					if(data=="created"){
						bootbox.alert("Created.");
						$("#frmEntry")[0].reset();
						$("#txtDatePicker").val(customDate);
						getStockList();
					}else if(data=="updated"){
						bootbox.alert("Stockin success.");
						$("#frmEntry")[0].reset();
						$("#txtDatePicker").val(customDate);
						// getAllStore();
						$("#txtQuantity").val(1);
						$("#txtPrice").val(0);
						getStockList();
					}else{
						bootbox.alert("Error on server side.");
					}
				}
			}); 
		}		
	}	

function autocomplete(inp) {
		var currentFocus;
		inp.addEventListener("input", function(e) {
			var a, i, val = this.value;
			var obj = this;
			closeAllLists();
			if (!val) { return false;}
			currentFocus = -1;
			$.ajax({
				url: APP_URL + "api/stock/item/autocomplete.php",
				type: "POST",
				data: JSON.stringify({ city: $("#cboCity").val(), item_name: this.value })
			}).done(function( data ) {
				bindData(a, i, obj, data, val);
			});
		});

		inp.addEventListener("keydown", function(e) {
			var x = document.getElementById(this.id + "autocomplete-list");
			if (x) x = x.getElementsByTagName("div");
			if (e.keyCode == 40) {
				currentFocus++;
				addActive(x);
			} else if (e.keyCode == 38) { 
				currentFocus--;
				addActive(x);
			} else if (e.keyCode == 13) {
				e.preventDefault();
				if (currentFocus > -1) {
					if (x) x[currentFocus].click();
				}
			}
		});
		function addActive(x) {
			if (!x) return false;
			removeActive(x);
			if (currentFocus >= x.length) currentFocus = 0;
			if (currentFocus < 0) currentFocus = (x.length - 1);
			x[currentFocus].classList.add("autocomplete-active");
		}

		function removeActive(x) {
			for (var i = 0; i < x.length; i++) {
				x[i].classList.remove("autocomplete-active");
			}
		}

		function closeAllLists(elmnt) {
			var x = document.getElementsByClassName("autocomplete-items");
			for (var i = 0; i < x.length; i++) {
				if (elmnt != x[i] && elmnt != inp) {
					x[i].parentNode.removeChild(x[i]);
				}
			}
		}
		
		function bindData(a, i, obj, arr, val){
			a = document.createElement("DIV");
			a.setAttribute("id", obj.id + "autocomplete-list");
			a.setAttribute("class", "autocomplete-items");
			obj.parentNode.appendChild(a);
			for (i = 0; i < arr.length; i++) {
				var strRegExp = new RegExp(val, "gi" ); //i makes it case insensitive	
				var po = arr[i]['item_code'] +" - "+ arr[i]['item_name'];
				b = document.createElement("DIV");
				b.innerHTML = po.replace(strRegExp, '<b>'+val+'</b>');
				b.innerHTML += "<input type='hidden' value='" + arr[i]['item_code'].replace(/\'/g, '&apos;') + "'>";
				b.innerHTML += "<input type='hidden' value='" + arr[i]['item_name'] + "'>";
				b.innerHTML += "<input type='hidden' value='" + arr[i]['price'] + "'>";
				b.innerHTML += "<input type='hidden' value='" + arr[i]['sales_price'] + "'>";
				b.addEventListener("click", function(e) {
					inp.value = this.getElementsByTagName("input")[1].value;
					$("#txtItemCode").val(this.getElementsByTagName("input")[0].value);
					closeAllLists();
				});
				a.appendChild(b);
			}
		}

		document.addEventListener("click", function (e) {
			closeAllLists(e.target);
		});
	}
	
	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 < 44) || charCode > 57 )  {
			return false;
		}else if(charCode == 45){
			return true;
		}
		return true;
	}
</script>
