<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<?php
	$D_ = "";
	if(isset($_GET['d'])){
		if(!empty($_GET['d'])){
			$D_ = $_GET['d'];
		}
	}
?>
<style>
		#myModel{
		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">
					<h3>Income - Report</h3>
				</div>
				<div class="col-md-6">
				</div>
			</div>
		</div>
	</section>
	<section class="content">
		<div class="container-fluid">
			<div class="row" id="SS">
				<div class="col-md-12">
					<div class="card card-outline card-primary">
						<div class="card-header">
							<h3 class="card-title">Search</h3>
						</div>
						<div class="overlay white" id="loading" style="display:none;position: absolute;width: 100%;height: 100%;z-index: 1000;">
							<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-6">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Date From&nbsp;<input id="chkDateFrom" type="checkbox" checked >:</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;">City:</label>
											<div class="col-md-8">
                                                <select type="text" class="form-control" id="cboCity"></select>
											</div>
										</div>

										
									</div>
									<div class="col-md-6">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;"> Date To: </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="txtDatePicker1" 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;">Account Head:</label>
											<div class="col-md-8">
												<select type="text" class="form-control" id="cboIncomeReason"></select>
											</div>
										</div>
										
										<div class="form-group row">
											<div class="col-md-6"></div>
											<div class="col-md-3" style="padding-bottom: 2px;">
												<button type="button" class="btn btn-primary btn-block" onclick="search()">Search</button>
											</div>
											<div class="col-md-3">
												<button type="button" id="btnExport" value=" Export Table data into Excel " datafrom="myTable" class="btn btn-success btn-block exportToExcel">Export Data</button> 
											</div>
										</div>
									</div>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
			<div class="card card-outline card-primary">
				<div class="card-header">
					<h3 class="card-title">Income 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-head-fixed table-bordered" id="myTable" style="max-height: 500px;">
						<thead>                  
							<tr>
								<th style="width: 3%">#</th>
								<th style="width: 10%">Date</th>
								<th style="width: 10%">Voucher No.</th>
								<th style="width: 15%">Account Head</th>
								<th>Particular</th>
								<th style="width: 5%">Quantity</th>
								<th style="width: 7%">Unit Price</th>
								<th style="width: 10%">Amount</th>
								<th style="width: 15%">Remark</th>
								<th style="text-align: center; width: 9%;">Action</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>
			<div class="modal fade" id="myModel" style="padding-right: 30% !important;">
				<div class="modal-dialog">
					<div class="modal-content" style="width: 200%;">
						<div class="modal-header">
							<h4 class="modal-title">Edit</h4>

						</div>
						<section class="content">
							<div class="container-fluid">
								<div class="row">
									<div class="col-md-12">
										<div class="card  card-primary">
											<div class="card-body">
												<div class="row">
													<div class="col-md-6">
														<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">
																	<input type="text" class="form-control" id="cboCityE" disabled>
																</div>
															</div>
														</div>
														<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="txtDatePickerE" 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;">Voucher No.:  </label>
															<div class="col-md-8">
																<input type="text" class="form-control" id="txtVoucherNoE">
															</div>
														</div>	
														<div class="form-group row">
															<label class="col-md-4 col-form-label" style="text-align: right;">Account Head: </label>
															<div class="col-md-8">
																<select type="text" class="form-control" id="cboIncomeReasonE">
																</select>
															</div>
														</div>
														
																																									
													</div>

													<div class="col-md-6">
														<div class="form-group row">

															<label class="col-md-4 col-form-label" style="text-align: right;">Particular:  </label>
															<div class="col-md-8">
																<input type="text" class="form-control" id="txtID" style="display:none;">
																<input type="text" class="form-control" id="txtParticularE">
															</div>
														</div>		
														<div class="form-group row">
															<label class="col-md-4 col-form-label" style="text-align: right;">Quantity: </label>
															<div class="col-md-3">
																<input type="text" name="txtPrice" id="txtQuantityE" class="form-control" onfocus="this.select();" style="text-align: right;" onkeypress="return isNumber(event)" onkeyup="btozero(this);" value="0" min="0" >
															</div>
															<label class="col-md-2 col-form-label" style="text-align: right;">Unit Price: </label>
															<div class="col-md-3">
																<input type="text" name="txtPrice" id="txtAmountE" class="form-control" onfocus="this.select();" style="text-align: right;" onkeypress="return isNumber(event)" onkeyup="btozero(this);" value="0" min="0" >
															</div>
														</div>
														<div class="form-group row">
															<label class="col-md-4 col-form-label" style="text-align: right;">Remark: </label>
															<div class="col-md-8">
																<input type="text" class="form-control" id="txtIncomeByE">
															</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="create();" 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="create()">Update</button>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</section>	
					</div>
				</div>
			</div>	
		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>
	var D_ = '<?=$D_;?>';
	var C = '<?php echo isset($_SESSION['city'])?$_SESSION['city']:"" ?>';
	var c_type = '<?php echo isset($_SESSION['c_type'])?$_SESSION['c_type']:"" ?>';
	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, #txtDatePicker1').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',
			showButtonPanel: true,
            showAnim: 'clip',
            autoclose: true
        }).val(customDate);
		if(C=='Main Office'){
			$("#cboCity").append("<option value= '" + C + "'>" + C + "</option>");	
			getIncomeReason();
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "' data-ctype= '" + c_type + "'>" + C + "</option>");	
			
		}

	});

	$(".exportToExcel").click(function(){
		exportExcel("#myTable");
	});

	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 + "'  data-ctype= '" + v.c_type + "'>" + v.name + "</option>");			
			});		
			$("#cboCity").val(C);
		});
	}
	
	$('#cboCity').change(function() { 
		getIncomeReason();
	});
	
	function getIncomeReason(){
		var city = $("#cboCity").val();
		$("#cboIncomeReason").find("option").remove();
		$("#cboIncomeReason").append("<option value = '' ></option>");
		$("#cboIncomeReasonE").find("option").remove();
		$("#cboIncomeReasonE").append("<option value = '' ></option>");

		$.ajax({
			url: APP_URL + "api/income_reason/get_income_reason.php",
            type: "POST",
            data: JSON.stringify({ city: city })
		}).done(function(data) {	
			$.each(data.records, function(i, v) {	

					$("#cboIncomeReason").append("<option value= '" + v.income_reason + "' >" + v.income_reason + "</option>");			
					$("#cboIncomeReasonE").append("<option value= '" + v.income_reason + "' >" + v.income_reason + "</option>");	
					
			});
		});
	}

	$("#chkDateFrom").change(function(){
		if($("#chkDateFrom").prop("checked")){
			$("#txtDatePicker").attr("disabled",false);
			$("#txtDatePicker1").attr("disabled",false);
		}else{
			$("#txtDatePicker").attr("disabled",true);
			$("#txtDatePicker1").attr("disabled",true);
		}
	})

	function search(){
		$("#loading").css("display","block");
		var df =($("#chkDateFrom").prop("checked"))?$("#txtDatePicker").val():"";
		var dt =($("#chkDateFrom").prop("checked"))?$("#txtDatePicker1").val():"";
		var income_reason = $("#cboIncomeReason").val();
		var city = $("#cboCity").val();

		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			type: "POST",
			url: APP_URL + "api/income/search.php",
			data: JSON.stringify({ df: df,dt: dt,income_reason: income_reason,city: city }),
			error: function(data) {
				$("#loading").css("display","none");
			}
		}).done(function(data) {	
			if(data.records.length>1){
				$("#total_records").text(" - " + data.records.length + " records found.");
			}else{
				$("#total_records").text(" - " + data.records.length + " record found.");
			}
			$("#loading").css("display","none");
			$.each(data.records, function(i, v) {
				$("#myTable").find("tbody")
				.append($('<tr>')
					.append("<td style='width: 10px'>" + (i+1) + "</td>")
					.append("<td>" + v.date + "</td>")
					.append("<td>" + v.voucher_no + "</td>")
					.append("<td>" + v.income_reason + "</td>")
					.append("<td>" + v.particular + "</td>")
					.append("<td style='text-align:right;'>" + v.quantity + "</td>")
					.append("<td style='text-align:right;'>" + v.amount + "</td>")
					.append("<td style='text-align:right;'>" + v.total_amount + "</td>")
					.append("<td>" + v.income_by + "</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> <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='7' style='text-align:right;'>Total Amount</td>")
			.append("<td style='text-align:right;'>" + ((data.net_amount)?data.net_amount:0) + "</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/income/delete.php",
						data: JSON.stringify({ id: id }),
						success: function(data){
							if(data=="deleted"){
								search();
								$(obj).parent().parent().remove();
							}else{
								bootbox.alert("Error on server side.");
							}
						}
					});
				}
			}
		});
	}

	function edit(id,obj){
		$("#myModel").modal('show');
		var tr = $(obj).parent().parent();
		$("#txtID").val(id);
		$("#cboCityE").val($("#cboCity").val());
		$("#txtDatePickerE").val($(tr).find("td").eq(1).text());
		$("#txtVoucherNoE").val($(tr).find("td").eq(2).text());
		$("#cboIncomeReasonE").val($(tr).find("td").eq(3).text());
		$("#txtParticularE").val($(tr).find("td").eq(4).text());
		$("#txtQuantityE").val($(tr).find("td").eq(5).text());
		$("#txtAmountE").val($(tr).find("td").eq(6).text());
		$("#txtIncomeByE").val($(tr).find("td").eq(8).text());
	}

	function create(){ 
		var id = $("#txtID").val();
		var date = $("#txtDatePickerE").val();
		var voucher_no = $("#txtVoucherNoE").val();
		var income_reason = $("#cboIncomeReasonE").val();
		var particular = $("#txtParticularE").val();
		var quantity = parseInt($("#txtQuantityE").val().replace(/,/g, ''));
		var amount = parseInt($("#txtAmountE").val().replace(/,/g, ''));
		var income_by = $("#txtIncomeByE").val();
        var city = $("#cboCityE").val();

		if(particular.trim()==""){
			bootbox.alert("Please fill the boxes.");
		}else{
			$.ajax({
				url: APP_URL + "api/income/create_update.php",
				type: "POST",
				data: JSON.stringify({ id: id, date: date, city: city, voucher_no: voucher_no, income_reason: income_reason, particular:particular, quantity:quantity, amount:amount, income_by:income_by}),
			}).done(function(data){
				console.log(data);
				if(data.message=="created"){
					bootbox.alert("Created.");
					$("#txtVoucherNoE").val("");
					$("#txtParticularE").val("");
					$("#quantityE").val(0);
					$("#txtAmountE").val(0);
					// search();
					getAllCity();
				}else if(data.message=="updated"){
					bootbox.alert("Successfully Updated.");
					$(".btnSave").css("display", "block");
					$(".btnEdit").css("display", "none");
					$("#txtIDE").val("");
					$("#txtVoucherNoE").val("");
					$("#txtParticularE").val("");
					$("#quantityE").val(0);
					$("#txtAmountE").val(0);
					$("#myModel").modal('hide');
				}else{
					bootbox.alert("Error on server side.");
				}
				search();
			});
		}   
	}

	function goToDetail(id){
		document.location = APP_URL + "entry/sales.php?id=" + id;
	}	

	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;
	}
	
</script>	
