<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<?php
	$sid = "";
	if(isset($_GET['sid'])){
		if(!empty($_GET['sid'])){
			$sid = $_GET['sid'];
		}
	}
?>
<style>
	#myTable1 td:nth-child(6){
		text-align: right;
	}	
	div.dataTables_wrapper div.dataTables_info {
	    display: none;
	}
</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%;
	}

		.hId{
		display: none;
	}

		#myCustomer{
		padding-right: 30% !important;
	}
</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>Item Sales</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">Customer Info</h3>
							</div>

							<div class="card-body">	
								<div class="row">
									<div class="col-md-3">
										<div class="form-group row">
											<label for="txtDatePicker" class="col-md-4 col-form-label text-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>
									<div class="col-md-3">

										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Store:
											</label>
											<div class="col-md-8">
												<select type="text" class="form-control" id="cboCity" >
												</select>
											</div>
										</div>
										
									</div>
									<div class="col-md-3">

										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Voucher No.:
											</label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtVoucherNo" disabled>
											</div>
										</div>
										
									</div>
									<div class="col-md-3">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Name:
											</label>
											<div class="col-md-8 input-group">
												<input type="text" class="form-control" id="txtInvoiceNo" style='display:none;'>
												<input type="text" class="form-control" id="txtName" disabled>
												<span class="input-group-append">
													<button type="button" class="btn btn-info btn-flat" onclick="getList()">...</button>
												</span>
											</div>
										</div>


										
									</div>
									
								</div>
							</div>
						</div>
						<div class="card  card-outline card-primary">
							<div class="card-header">
								<h3 class="card-title">Item Info</h3>
							</div>
							
							<div class="card-body">	
								<div class="row">
									<div class="col-md-1"></div>
									<div class="col-md-3">
										<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>
                                    <div class="col-md-3" >
                                        <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>

                                    <div class="col-md-3">
                                        <div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Qty/Price: </label>
											<div class="col-md-4">
												<input type="number" class="form-control" onkeyup="btozero(this);" onfocus="this.select();" id="txtQuantity" value="1" min="1" style="text-align:right;">
											</div>
											<div class="col-md-4">
												<input type="text" class="form-control" onkeyup="btozero(this);" onfocus="this.select();" onkeypress="return isNumber(event)" id="txtPrice" value="0" style="text-align:right;">
											</div>
										</div>
										
									</div>
                                    <div class="col-md-1" style="padding-right: 27px;">
                                        <div class="form-group row" style="margin-bottom: 0px;">
											<!-- <div class="col-md-4"></div> -->
											<div class="col-md-12">
												<button type="button" class="btn btn-primary btn-block" onclick="add()">Add</button>
											</div>
										</div>
                                    </div>
								</div>
								<div class="card-body p-0" style="height:250px; overflow-y: auto;background-color: #e6e7e8 !important;width: 91.5%;margin-left: 5%;">
									<table class="table table-striped " id="myTable" >
										<thead>                  
											<tr>
												<th style="width: 3%;">#</th>
												<th style="width: 15%;">Item Code</th>
												<th>Item Name</th>
												<th style="width: 8%;text-align:centre;">Qty</th>
												<th style="width: 10%;">Price</th>
												<th style="width: 10%;">Amount</th>
												<th style="width: 3%;">Remove</th>
											</tr>
										</thead>
										<tbody>
										</tbody>
								</table>	
							</div>
							</div>
								<div class="card-body ">	
									<div class="row">
										<div class="col-md-7">

										</div>
										<!-- <div class="col-md-5"></div> -->
										<div class="col-md-5" style="padding-right: 4%;">
											<div class="form-group row">
												<label class="col-md-6 col-form-label" style="text-align: right;">Total Amount:
												</label>
												<div class="col-md-6">
													<input type="text" class="form-control" id="txtTotalAmount" name="txtTotalAmount" value="0" style="text-align:right;" disabled>
												</div>
											</div>		
											<div class="form-group row">
												<label class="col-md-6 col-form-label" style="text-align: right;">Discount:
												</label>
												<div class="col-md-6">
													<input type="text" class="form-control" id="txtDiscount" onfocus="this.select();" onkeypress="return isNumber(event)" value="0" style="text-align:right;">
												</div>
											</div>									
											<div class="form-group row">
												<label class="col-md-6 col-form-label" style="text-align: right;">Payment:
												</label>
												<div class="col-md-6">
													<input type="text" class="form-control" id="txtPayment" onkeypress="return isNumber(event)" value="0" style="text-align:right;" disabled>
												</div>
											</div>
											<div class="form-group row" id="create">
												<label class="col-md-9 col-form-label" style="text-align: right;">
												</label>
												<div class="col-md-3">
													<button type="button" class="btn btn-primary btn-block" id="btnSubmit" onclick="validateAndSave()">Sales</button>
												</div>
											</div>
											<div class="form-group row" id="update" style="margin-bottom: 7px; display: none;">
												<label class="col-md-6 col-form-label" style="text-align: right;"></label>
												<div class="col-md-3">

												</div>
												<div class="col-md-3">
													<button type="button" class="btn btn-success btn-block" id="btnSubmit" onclick="validateAndSave()">Update</button>
												</div>
											</div>

										</div>
									</div>
								</div>

								<div class="modal fade" id="myCustomer" style="padding-right: 30% !important;">
									<div class="modal-dialog">
										<div class="modal-content" style="width: 200%;">
											<div class="modal-header">
												<h4 class="modal-title">Customer</h4>
							
											</div>
											<section class="content">
												<div class="container-fluid">
													<div class="row">
														<div class="col-md-12">
															<div class="card card-outline card-primary">
																<!-- <div class="card-header">
																	<h3 class="card-title">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">
																	<table id="myTable1" class="table table-bordered table-hover" style="border-collapse: collapse !important;">
																		<thead>
																			<tr>
																				<!-- <th style="width: 3%">#</th> -->
																				<th>#</th>
																				<!-- <th>ID No.</th> -->
																				<th>Name</th>
																				<th>Phone No.</th>
																				<!-- <th class="hId">Invoice No.</th> -->
																			</tr>
																		</thead>
																		<tbody></tbody>
																	</table>
																</div>
															</div>
														</div>
													</div>
												</div>
											</section>	
										</div>
									</div>
								</div>

							</div>
						</div>
					</form>
				</div>

				

			</div>
			
		</div>
		
	</div>

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

	var sid = '<?=$sid;?>';
	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{
			$("#cboCity").append("<option value= '" + C + "'>" + C + "</option>");	


		}

		<?php if($sid!=""){ ?>
			$("#create").css('display', 'none');
			$("#update").css('display', '');
			getSales();
		<?php }else{ ?>
			getVoucherNo();
		<?php } ?>

	});

    $("#cboCity").change(function(){
    	$("#txtItemCode").val("");
    	$("#txtItemName").val("");
    	$("#txtQuantity").val(1);
    	$("#txtPrice").val(0);
		getVoucherNo();
		
	});

	function getAllCity(){
		$("#cboCity").find("option").remove();
		// $("#cboCity").append("<option value= '' data-id = ''>[All]</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(C);	
			// getStockList();
		});

	}

    function getVoucherNo(){
		$("#txtVoucherNo").val("");
		$.ajax({
			url: APP_URL + "api/stock/item_sales/get_generate_voucher_no.php"
		}).done(function(data) {
            $("#txtVoucherNo").val(data.voucher_no);
		});
	}

	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);
					$("#txtPrice").val(this.getElementsByTagName("input")[3].value);
					closeAllLists();
				});
				a.appendChild(b);
			}
		}

		document.addEventListener("click", function (e) {
			closeAllLists(e.target);
		});
	}

	function add(){

		var item_code = $("#txtItemCode").val();
		var item_name = $("#txtItemName").val();
		var quantity = parseInt($("#txtQuantity").val().replace(/,/g, ''));
		var price = parseInt($("#txtPrice").val().replace(/,/g, ''));
		if( item_name.trim() == ""){
			bootbox.alert("Please fill the boxes.");
		}else{

			$.ajax({
				url: APP_URL + "api/stock/item/update_price.php",
				type: "POST",
				data: JSON.stringify({ item_code: item_code, price: price })
			})

			$("#myTable").find("tbody")
			.append($('<tr>')
				.append("<td style='width: 10px'>" + ($("#myTable tbody tr").length +1) + "</td>")
				.append("<td>" + item_code + "</td>")
				.append("<td>" + item_name + "</td>")
				.append("<td style='text-align:right; padding-right:33px;'>" + quantity + "</td>")
				.append("<td style='text-align:right; padding-right:40px;'>" + parseInt(price).toLocaleString() + "</td>")
				.append("<td style='text-align:right; padding-right:40px;'>" + parseInt(quantity*price).toLocaleString() + "</td>")
				.append("<td style='width: 70px'><button type='button' class='btn btn-danger btn-sm'  style='padding: 0px 19px;font-size: 14px;' onclick='$(this).parent().parent().remove();calculate();'>×</button></td>")
			);
			// $("#txtMaterialName").removeAttr("disabled", "disabled");
			calculate();
			$("#txtItemCode").val("");
			$("#txtItemName").val("");
			$("#txtQuantity").val(1);
			$("#txtPrice").val(0);
		}	
	}

	function validateAndSave(){
		var sales_details = [];
		$("#myTable tbody tr").each(function (){
			var sales_detail = {
				"item_code" : ($(this).find("td").eq(1).text()),
				"item_name" : ($(this).find("td").eq(2).text()),
				"quantity": ($(this).find("td").eq(3).text().replace(/,/g, '')),
				"price" : $(this).find("td").eq(4).text().replace(/,/g, '')
			}
			sales_details.push(sales_detail);
		});

		var sales = {
			"vno":sid,
			"sales_date":$("#txtDatePicker").val(),
			"store":$("#cboCity").val(),
			"voucher_no":$("#txtVoucherNo").val(),
			"name": $("#txtName").val(),
			"invoice_no": "",
			"total_amount":$("#txtTotalAmount").val().replace(/,/g, ''),
			"discount":$("#txtDiscount").val().replace(/,/g, ''),
			"payment":$("#txtPayment").val().replace(/,/g, ''),
			"sales_details":sales_details
		};
		if($("#txtVoucherNo").val() == ""){
			bootbox.alert("Please fill the boxes.");
		}else if(parseInt($("#txtPayment").val())>parseInt($("#txtTotalAmount").val().replace(/,/g, ''))){
			bootbox.alert("Payment amount is over.");
		}else if( $("#myTable tbody tr").length==0){
			bootbox.alert("Please fill purchase_details.");
		}else{
			$.ajax({
				url: APP_URL + "api/item_sales/create.php",
				type: "POST",
				data: JSON.stringify(sales)
			}).done(function(data) {	
				if(data.message=="created"){
					print(data.vno);
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}
	}

	function calculate(){
		var total_amount = 0;
		$("#myTable tbody tr").each(function (i,v){
			var amount = $(this).find("td").eq(5).text().replace(/,/g, '');
			if(amount){
				total_amount +=  parseInt((amount).replace(/,/g, ''));
			}	
		});

		$("#txtTotalAmount").val((total_amount).toLocaleString());
		// $("#txtPayment").val((total_amount).toLocaleString());

		// $("#txtBalance").val((total_amount).toLocaleString());

		if($("#myTable tbody tr").length==0){
			$("#txtTotalAmount").val(0);
			$("#txtPayment").val(0);
		}

		calculateB();
	}

    $("#txtDiscount").keyup(function(){
    	calculateB();
    });


	function calculateB(){
		var balance = 0;
		var total_amount = parseInt($("#txtTotalAmount").val().replace(/,/g, ''));
		var discount = parseInt($("#txtDiscount").val().replace(/,/g, ''));
		payment = total_amount - (isNaN(discount)?0:discount);
		$("#txtPayment").val(payment.toLocaleString());

	}

	function getSales(){
		$.ajax({
			url: APP_URL + "api/sales/get_one_sales.php",
			type: "POST",
			data: JSON.stringify({ voucher_no: sid  })
		}).done(function(data) {
			$("#txtDatePicker").val(data.sales_date);
			$("#txtVoucherNo").val(data.voucher_no);
			$("#cboCity").val(data.city);
			$("#txtName").val(data.name);

			// $("#txtPayment").val(data.payment);
			// $("#txtBalance").val(data.balance);
			$.each(data.s_details, function(i, v) {
				$("#myTable").find("tbody")
		        .append($('<tr>')
					.append("<td style='width: 10px'>" + ($("#myTable tbody tr").length +1) + "</td>")
					.append("<td>" + v.item_code + "</td>")
					.append("<td>" + v.item_name + "</td>")
					.append("<td>" + v.store + "</td>")
					.append("<td style='text-align:right; padding-right:33px;'>" + v.quantity + "</td>")
					.append("<td style='text-align:right; padding-right:40px;'>" + parseInt(v.price).toLocaleString() + "</td>")
					.append("<td style='text-align:right; padding-right:40px;'>" + parseInt(v.quantity*v.price).toLocaleString() + "</td>")
					.append("<td style='width: 70px'><button type='button' class='btn btn-danger btn-sm'  style='padding: 0px 19px;font-size: 14px;' onclick='$(this).parent().parent().remove();calculate();'>×</button></td>")
				)
	        });
	        calculate();
	        // calculateB();
	
		});
	}

	function clearForm(){
		// window.open(APP_URL + "entry/sales.php");
		$("#txtDatePicker").val(customDate);
		$("#txtVoucherNo").val("");
		$("#txtName").val("");
		$("#txtTotalAmount").val(0);
		$("#txtDiscount").val(0);
		$("#txtPayment").val(0);
		$("#myTable tbody tr").remove();
	}

	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 print(vid,obj){
        bootbox.confirm({
        	message: "<h4>Successfully saved. Your Voucher No. is " + vid + ". Do you want to print?</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){
        			window.open(APP_URL + "print/item_sales_print.php?vid=" + vid  , "_blank");
					clearForm();
        		}
				window.location.href = APP_URL +"entry/item_sales.php";
				// else{
        		// 	clearForm();
        		// }
        	}
        });
    }

    function getList(){

			$("#myCustomer").modal('show');
			fillGrid();

	}

    function fillGrid(){
		var city = $("#cboCity").val();

		table = $('#myTable1').DataTable({
			"destroy": true,
			"paging": true,
			"lengthChange": true,
			"searching": true,
			"ordering": true,
			"info": true,
			"autoWidth": false,
			"responsive": true,
			"lengthMenu": [5, 10, 50, 100],
			"pageLength": 5,
			"ajax": APP_URL + "api/customer/get_item_sales_customer.php?city=" + city,
			// "columnDefs": [
			// {
			// 		className: "hId", targets: [4],
	        //     },
	        //     ]
	        });

		$('#myTable1').on('click', 'tbody td', function(e){	


			
			$("#txtName").val($(this).parent().find("td").eq(1).text());
			// $("#txtInvoiceNo").val($(this).parent().find("td").eq(4).text());

			$("#myCustomer").modal('hide');
		});


	}

	// function print(vid,obj){
	// 	window.open(APP_URL + "print/sales_print.php?vid=" + vid  , "_blank");
	// 	// document.location = APP_URL + "expense/purchase.php?pid=" + id  , "_blank";
	// }

</script>
