<script src="assets/js/king-table.js"></script>
<div class="content">
	<div class="main-content">
		<div class="row">	
			<form id="frmmain" name="frmmain" data-parsley-validate novalidate>
			<div class="col-md-6">
				
				<div class="widget widget-scrolling">
					<div class="widget-header">
						<h3><i class="fa fa-pencil-square-o"></i> Demand</h3>
					</div>
					<div class="widget-content">
						<div class="row">	
							<div class="form-group col-md-12">
								<label for="text-input1">Search Customer.*</label>
								<input type="hidden" id="custid" name="custid" >
								<input type="text" name="searchcust" id="searchcust" class="form-control searchTypeahead" autocomplete="off" >
							</div>
							<div class="form-group col-md-6">
								<label for="text-input1">Sequence No.*</label>
								<input type="text" name="seqno" id="seqno" class="form-control" readonly>
								<small class="text-danger" id="errseqno"></small>
							</div>
							<div class="form-group col-md-6">
								<label for="text-input1">Operator*</label>
								<select name="cmboperator" id="cmboperator" class="form-control" required>
									<option value="">-- Select --</option>
								</select>
								<small class="text-danger" id="errcmboperator"></small>
							</div>
							
							<div class="form-group col-md-6">
								<label for="text-input1">Customer.</label>
								<input type="text" name="customername" id="customername" class="form-control" readonly >
								<small class="text-danger" id="errcustomername"></small>
							</div>
							
							<div class="form-group col-md-6">
								<label for="text-input1">Bill No.</label>
								<input type="text" name="billno" id="billno" class="form-control" readonly >
								<small class="text-danger" id="errbillno"></small>
							</div>
							
							<div class="form-group col-md-6">
							<label for="text-input1">Previous Receipt Date.*</label>
							<input type="date" name="prevbilldt" id="prevbilldt" class="form-control" readonly >
							<small class="text-danger" id="errprevbilldt"></small>
							</div>
							<div class="form-group col-md-6">
								<label for="text-input1">Current Receipt Date*</label>
								<input type="date" name="receiptdt" id="receiptdt" class="form-control" value="<?php echo date("Y-m-d"); ?>" >
								<small class="text-danger" id="errreceiptdt"></small>
							</div>
							<div class="form-group col-md-6">
								<label for="text-input1">Prev Reading.</label>
								<input type="text" name="prevreading" id="prevreading" class="form-control" readonly >
								<small class="text-danger" id="errprevreading"></small>
							</div>
							<div class="form-group col-md-6">
								<label for="text-input1">Current Reading.</label>
								<input type="text" name="currreading" id="currreading" class="form-control" autocomplete="off"   >
								<small class="text-danger" id="errcurrreading"></small>
							</div>
							<div class="form-group col-md-6">
								<label for="text-input1">Previous Balance.</label>
								<input type="text" name="prevbal" id="prevbal" class="form-control" readonly >
								<small class="text-danger" id="errprevbal"></small>
							</div>
							<div class="form-group col-md-6">
								<label for="text-input1">Current Bill.</label>
								<input type="text" name="currbill" id="currbill" class="form-control" readonly >
								<small class="text-danger" id="errcurrbill"></small>
							</div>
							
						</div>
					</div>
					<div class="widget-footer">
						<center><button type="submit" name="btnreceipt" id="btnreceipt" class="btn btn-primary center-block"><i class="fa fa-plus"></i> Add</button></center>
					</div>
				</div>
			</div>
			<div class="col-md-6">
				<div class="widget">
					<div class="widget-header">
						<h3><i class="fa fa-calculator"></i> Tariff charge</h3>
					</div>
					<div class="widget-content">
						<div class="project-section activity">
														
							<div class="form-group col-md-6">
								<label for="text-input1">Tariff type.</label>
								<input type="hidden" name="tarifftypeid" id="tarifftypeid" class="form-control" readonly >
								<input type="text" name="tarifftype" id="tarifftype" class="form-control" readonly >
								<small class="text-danger" id="errtarifftype"></small>
							</div>
							<div class="form-group col-md-3">
								<label for="text-input1">Total Unit.</label>
								<input type="text" name="tariffunit" id="tariffunit" class="form-control" readonly >
								<small class="text-danger" id="errtariffunit"></small>
							</div>
							<div class="form-group col-md-3">
								<label for="text-input1">No. of Month</label>
								<input type="text" name="nomonth" id="nomonth" class="form-control" readonly >
								<small class="text-danger" id="errtariffunit"></small>
							</div>
							
							<table  id="tariffcharttable" class="table table-striped table-hover table-bordered datatable">
									<thead>
										<tr>
											<th>Unit</th>
											<th>Range</th>
											<th>Charge</th>
											<th>Amount</th>
										</tr>
									</thead>
									<tbody>
									</tbody>
							</table>							
						</div>
					</div>					
					<div class="widget-footer">
						<b>Total amount -</b> Rs. <span id="divtotalcost">0</span>
					</div>
				</div>
			</div>
			
			
			<div class="col-md-6">
				<div class="widget">
					<div class="widget-header">
						<h3><i class="fa fa-file-text-o"></i> Info About Water Meter</h3>
					</div>
					<div class="widget-content">
						<div class="project-section activity">
								<div class="form-group col-md-12">
									<label for="text-input1">Meter status*</label>
									<select name="cmbmeterstatus" id="cmbmeterstatus" class="form-control" required>
										<?php
										$metrst=array("Working","Meter not working","Meter not visible","Others");
										foreach($metrst as $metrval)
										{
											echo "<option value='$metrval'>$metrval</opion>";
										}
										?>
									</select>
									<small class="text-danger" id="errcmbmeterstatus"></small>
								</div>
								<div class="form-group col-md-12">
									<label for="text-input1">Any note.</label>
									<textarea name="meterreason" id="meterreason" class="form-control"></textarea>
									<small class="text-danger" id="errmeterreason"></small>
								</div>
						</div>
					</div>
					
					<div class="widget-footer">
						&nbsp;
					</div>
				</div>
			</div>
			
			</form>
			
			<div class="col-md-12">
				<!-- BASIC VALIDATION -->
				<div class="widget widget-table">
					<div class="widget-header">
						<h3><i class="fa fa-table"></i> View Receipt records</h3> 
					</div>
					<div class="widget-content">				
						
						<table id="datatable-data-export" class="table table-sorting table-striped table-hover table-bordered datatable">
							<thead>
								<tr>
									<th>SL No.</th>
									<th>Bill No.</th>
									<th>Seq. No.</th>
									<th>Customer Name</th>
									<th>Receipt Date</th>
									<th>Previous Reading</th>
									<th>Current Reading</th>
									<th>Total Unit</th>
									<th>Previous Balance</th>
									<th>Current Bill</th>
									<th>Total Amount</th>
									<th>X</th>
								</tr>
							</thead>
							<tbody>
								<?php
									/*
										@foreach($data['UserType'] as $UserType)
										<tr>
										<td>{{$UserType->ut_type}}</td>
										<td>{{$UserType->ut_description}}</td>
										<td>{{$UserType->ut_status}}</td>
										
										<td> <span class="btn btn-default btn-xs">Edit</span>  <span class="btn btn-default btn-xs">Delete </span></td>
										</tr>
										@endforeach
									*/
								?>
							</tbody>
						</table>
						
					</div>
					
					<div class="widget-footer">
						<center><button type="button" name="btngeneratereceipt" id="btngeneratereceipt" class="btn btn-primary center-block"><i class="fa fa-floppy-o"></i> Generate Receipt</button></center>
					</div>
					
				</div>
				<!-- END BASIC VALIDATION -->
			</div>
			 
		</div>
	</div>
</div>
<!-- /main -->
<script src="js/bootstrap-typeahead.js"></script>
<script type="application/javascript">	
	$('#btngeneratereceipt').click(function(e)
	{
		if(confirm("Are you sure want to save all these records...?") == true)
		{
			$.ajax({
			url: "SaveReceiptRecord",
			type:'get',
			success: function(data) 
			{
				if(data != 0)
				{
					alert("Receipt Record deleted successfully...");
					viewtariffreceiptrecords();
				}
				else
				{
					alert("Failed to delete record..");
				}
			}
			});
		}
	})
	$('#btnreceipt').click(function(e)
	{
		e.preventDefault();	
		var _token = $("input[name='_token']").val();
		var seqno = $("input[name='seqno']").val();
		var cmboperator = $('#cmboperator').val();
		var customername = $("input[name='customername']").val();
		var billno = $("input[name='billno']").val();
		var prevbilldt = $("input[name='prevbilldt']").val();
		var receiptdt = $("input[name='receiptdt']").val();
		var prevreading = $("input[name='prevreading']").val();
		var currreading = $("input[name='currreading']").val();
		var tarifftype = $("input[name='tarifftypeid']").val();
		var tariffunit = $("input[name='tariffunit']").val();
		var prevbal = $("input[name='prevbal']").val();
		var currbill = $("input[name='currbill']").val();
		var cmbmeterstatus = $("[name='cmbmeterstatus']").val();
		var meterreason =$('#meterreason').val();
		if(custid == "")
		{
			document.getElementById("errcustid").innerHTML = "Sequence number should not be empty....";
			//$(".alert-info").find("ul").html('<li class="fa fa-cog fa-1x fa-fw"></li>Kindly check the error...');
		}
		else
		{
				$.ajax({
					url: "/insertreceipt",
					type:'POST',
					data: {_token:_token, custid:custid, seqno:seqno, cmboperator:cmboperator, customername:customername, billno:billno, prevbilldt:prevbilldt, receiptdt:receiptdt, prevreading:prevreading, currreading:currreading, tarifftype:tarifftype, tariffunit:tariffunit, prevbal:prevbal, currbill:currbill, cmbmeterstatus:cmbmeterstatus, meterreason:meterreason },
					success: function(data) {									
						if(data.status == 1)
						{
							alert("Record inserted successfully...");
		
		$("#tariffcharttable tbody").remove(); //This code will erase table record
		$("[name='searchcust']").val('');
		$("input[name='seqno']").val('');
		$('#cmboperator').val('-- Select --');
		$("input[name='customername']").val('');
		$("input[name='billno']").val('');
		$("input[name='prevbilldt']").val('');
		$("input[name='prevreading']").val('');
		$("input[name='currreading']").val('');
		$("input[name='tarifftypeid']").val('');
		$("input[name='tariffunit']").val('');
		$("input[name='prevbal']").val('');
		$("input[name='currbill']").val('');
		$("[name='cmbmeterstatus']").val('');
		$('#meterreason').val('');
		$("[name='tarifftype']").val('');
		$("[name='nomonth']").val('');		
		document.getElementById("divtotalcost").innerHTML = 0;							
		viewtariffreceiptrecords();
							//printSuccessMsg(data.message);
							//$('#sideMenu').load('WBAllReport');
						}
						else
						{
							//printErrorMsg(data.message)
						}
					}
				});					
		}
	});
	viewtariffreceiptrecords();
	function viewtariffreceiptrecords()
	{
			$.ajax({
			url: "ViewPendingReceipt",
			type:'get',
			success: function(data)
				{
					var totreading = 0;
					var totamt = 0;
					var grandtotalunit = 0;
					var grandprevbalance = 0;
					var grandcurrentbill = 0;
					var grandtotalamt = 0;
					//###Loop code starts here..
					var slno=1;
					$("#datatable-data-export tbody").remove(); //This code will erase table record
					$.each(data.WBAllReport, function(i, item) 
					{
						totreading = parseInt(data['WBAllReport'][i]['wtrb_currreading']) - parseInt(data['WBAllReport'][i]['wtrb_prevreading']);
						totamt = parseFloat(data['WBAllReport'][i]['wtrb_prevbal']) + parseFloat(data['WBAllReport'][i]['wtrb_currpayable']);
						
					 grandtotalunit = grandtotalunit + totreading;
					 grandprevbalance = grandprevbalance + parseFloat(data['WBAllReport'][i]['wtrb_prevbal']);
					 grandcurrentbill = grandcurrentbill + parseFloat(data['WBAllReport'][i]['wtrb_currpayable']);
					 grandtotalamt = grandtotalamt + totamt;
						
						$("#datatable-data-export").append("<tr><td>" + slno + "</td><td>" + data['WBAllReport'][i]['wtrb_billno'] + "</td><td>" + data['WBAllReport'][i]['cst_code'] + "</td><td>" + data['WBAllReport'][i]['cst_name'] + "</td><td>" + data['WBAllReport'][i]['wtrb_billdate'] + "</td><td>" + data['WBAllReport'][i]['wtrb_prevreading'] + "</td><td>" + data['WBAllReport'][i]['wtrb_currreading'] + "</td><td>" + totreading + "</td><td>" + data['WBAllReport'][i]['wtrb_prevbal'] + "</td><td>" + data['WBAllReport'][i]['wtrb_currpayable'] + "</td><td>" + totamt + "</td><td><button onclick='delreceiptrecord(" + data['WBAllReport'][i]['wtrb_id'] +")'>X</button></td></tr>");	
						slno = slno + 1;						
					});
					//###Loop code ends here..
					$("#datatable-data-export").append("<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>" + grandtotalunit +"</th><th>" + grandprevbalance + "</th><th>" + grandcurrentbill + "</th><th>" + grandtotalamt + "</th><th></th></tr>");
					//document.getElementById("divtotalcost").innerHTML = totamt;
					//$('#currbill').val(totamt);
					//$('#divtotalcost').innerHTML(totamt);
				}		
			});			
	}
	
	function delreceiptrecord(delid)
	{
		if(confirm("Are you sure want to delete this record?") == true)
		{
			$.ajax({
			url: "DeleteReceiptRecord",
			type:'get',
			data:'&delid='+delid,
			success: function(data) 
			{
				if(data != 0)
				{
					alert("Receipt Record deleted successfully...");
					viewtariffreceiptrecords();
				}
				else
				{
					alert("Failed to delete record..");
				}
			}
			});
		}
	}
	
	function printErrorMsg (msg) {
		$(".alert-info").css('display','none');
		$(".print-success-msg").css('display','none');
		$(".print-error-msg").find("ul").html('');
		$(".print-error-msg").css('display','block');
		$(".print-error-msg").find("ul").append('<li class="fa fa-times-circle fa-1x fa-fw"></li>'+msg);
	}
		
	function printSuccessMsg (msg) {
		$(".alert-info").css('display','none');
		$(".print-error-msg").css('display','none');
		$(".print-success-msg").find("ul").html('');
		$(".print-success-msg").css('display','block');
		$(".print-success-msg").find("ul").append('<li class="fa fa-check  fa-1x fa-fw"></li>'+msg);
		//Code to redirect page
		//var url = "/dashboard";
		//$(location).attr('href',url);
	}

	$('input.searchTypeahead').typeahead({
		ajax: '/searchrecord'
	});
	
	$('#searchcust').change(function(e)
	{
		custid=$('#custid').val($('ul.typeahead li.active').data('value'));	
		seach();
	});
	
	function seach()
	{
		$("#tariffcharttable tbody").remove(); //This code will erase tale record
		$('#seqno').val('');
		$('#customername').val('');				 
		$('#cmboperator').val('');
		$('#prevbilldt').val('');
		$('#prevreading').val('');
		$('#tarifftypeid').val('');
		$('#tarifftype').val('');
		$('#cmbmeterstatus').val('');
		$('#meterreason').val('');
		$('#billno').val('');
		$('#prevbal').val('');
		
		custid = $('#custid').val();
		$.ajax({
			url: "Displaycstrecord",
			type:'get',
			data:'&custid='+custid,
			success: function(data) 
			{
				$('#seqno').val(data['customer']['cst_code']);
			    $('#customername').val(data['customer']['cst_name']);				 
			    $('#cmboperator').val(data['customer']['usr_id']);
			    $('#prevbilldt').val(data['receiptrec']['wtrb_billdate']);
			    $('#prevreading').val(data['receiptrec']['wtrb_currreading']);
			    $('#tarifftypeid').val(data['customer']['tarf_id']);
			    $('#tarifftype').val(data['customer']['tarf_tarifftype']);
			    $('#cmbmeterstatus').val(data['receiptrec']['wtrb_mtrstatus']);
			    $('#meterreason').val(data['receiptrec']['wtrb_mtrreason']);
			    $('#billno').val(data['nextreceiptnumber']['wtrb_billno']);
			    $('#prevbal').val(data['balamt']);
			}		
		});
	}
	
	$('#currreading').keyup(function(e)
	{
		calculatetariffcharge();
	});	
	$('#receiptdt').change(function(e)
	{
		calculatetariffcharge();
	});
	
	function calculatetariffcharge()
	{
		var totreading = 0;
		var prevreading = 0;
		var currreading=0;
		var jumpreading =99999;
		var jumpreadingbal = 0;
		var lblpermonth=0;
		calcualteMonthYr();
		
		prevreading = $("input[name='prevreading']").val();
		currreading = $("input[name='currreading']").val();		
		
		if(parseInt(currreading) > parseInt(prevreading))
		{
			totreading = currreading - prevreading;
		}
		if(parseInt(prevreading) > parseInt(currreading))
		{
			jumpreadingbal = parseInt(jumpreading)-parseInt(prevreading);
			totreading = parseInt(jumpreadingbal) + parseInt(currreading);
		}
		
		var nomonth = $("input[name='nomonth']").val();
		lblpermonth = parseInt(totreading) / parseInt(nomonth);
				
		var tarfid = $("input[name='tarifftypeid']").val();
		var prevunit  = 0;
        var calcunit  = 0;
        var totamt   = 0;
		var slabamt = 0;
		$('#tariffunit').val(totreading);	
			$.ajax({
				url: "calculatetariffchart",
				type:'get',
				data:'&tarfid='+tarfid,
				success: function(data) 
				{
					//###Loop code starts here..
					$("#tariffcharttable tbody").remove(); //This code will erase table record
					$.each(data.tariffcharge, function(i, item) 
					{
						calcunit = 0;
				
						//###Tariffwise Slab calculation starts here...
						if(parseInt(lblpermonth) >= parseInt(data['tariffcharge'][i]['tarc_unitfrom']))
						{
							if(parseInt(i)==0 && parseInt(lblpermonth) <= parseInt(data['tariffcharge'][i]['tarc_unitto']))
							{
								calcunit = parseInt(data['tariffcharge'][i]['tarc_tariffrange']) / parseInt(data['tariffcharge'][i]['tarc_tariffrange']);                    
								slabamt = parseFloat(data['tariffcharge'][i]['tarc_tariffcharge']) * parseInt(nomonth);
							}
							else
							{
								if(parseInt(lblpermonth) >= parseInt(data['tariffcharge'][i]['tarc_unitto']))
								{
									calcunit = (parseInt(data['tariffcharge'][i]['tarc_unitto']) - parseInt(prevunit)) / (parseInt(data['tariffcharge'][i]['tarc_tariffrange']));
									slabamt = parseFloat(data['tariffcharge'][i]['tarc_tariffcharge']) * parseInt(calcunit) * parseInt(nomonth);
								}
								else
								{
									calcunit = (parseInt(lblpermonth) - parseInt(prevunit)) / (parseInt(data['tariffcharge'][i]['tarc_tariffrange']));
									slabamt = parseFloat(data['tariffcharge'][i]['tarc_tariffcharge']) * parseInt(calcunit) * parseInt(nomonth);
								}
							}
						}
						prevunit = data['tariffcharge'][i]['tarc_unitto'];
						totamt = totamt + slabamt;
						//###Tariffwise Slab calculation ends here...
						
						
						$("#tariffcharttable").append("<tr><td><input type='hidden' name='tarc_id[" + i + "]' value='" + data['tariffcharge'][i]['tarc_id'] + "'><input type='hidden' name='tarc_unitfrom[" + i + "]' value='" + data['tariffcharge'][i]['tarc_unitfrom'] + "'><input type='hidden' name='tarc_unitto[" + i + "]' value='" + data['tariffcharge'][i]['tarc_unitto'] + "'><input type='hidden' name='tarc_tariffrange[" + i + "]' value='" + data['tariffcharge'][i]['tarc_tariffrange'] + "'><input type='hidden' name='tarc_tariffcharge[" + i + "]' value='" + data['tariffcharge'][i]['tarc_tariffcharge'] + "'><input type='hidden' name='tarc_unitfrom[" + i + "]' value='" + data['tariffcharge'][i]['tarc_unitfrom'] + "'><input type='hidden' name='amt[" + i + "]' >" + data['tariffcharge'][i]['tarc_unitfrom'] + "-"+ data['tariffcharge'][i]['tarc_unitto'] +"</td><td>" + data['tariffcharge'][i]['tarc_tariffrange'] + "</td><td>" + data['tariffcharge'][i]['tarc_tariffcharge'] + "</td><td><span id='div["+ i + "]'>" + slabamt +"</span></td></tr>");
						slabamt=0;						
					});
					//###Loop code ends here..
					document.getElementById("divtotalcost").innerHTML = totamt;
					$('#currbill').val(totamt);
					//$('#divtotalcost').innerHTML(totamt);
				}
			});
	}
	
	function calcualteMonthYr()
	{
		var fromDate =new Date($('#prevbilldt').val()); //date picker (text fields)
		var toDate = new Date($('#receiptdt').val());
		var months=0;
		months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
		months -= fromDate.getMonth();
		months += toDate.getMonth();
		if (toDate.getDate() < fromDate.getDate())
		{
			months--;
		}
		if(parseInt(months) == 0)
		{
			$('#nomonth').val("1");
		}
		else
		{
			$('#nomonth').val(months);
		}
	}
</script>
<script>
	//Load Agent records
	$(document).ready(function(){
	 $.ajax({
            type: "GET",
            url:"/getagent",
            dataType: "json",
            success: function (data) {
                $.each(data,function(i,obj)
                {
				var div_data="<option value="+obj.usr_id+">"+obj.usr_name+ "("+ obj.usr_loginid +")</option>";	
                $(div_data).appendTo('#cmboperator'); 
                });
                }
          });
        });	
</script>