<?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>Expense - Entry</h1>
				</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 ">
						<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-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">
													<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;">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;">Voucher No.:  </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtVoucherNo">
											</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-6">
												<select type="text" class="form-control" id="cboExpenseReason">
												</select>
											</div>
											<div class="col-md-2">
												<button type="button" class="btn btn-info btn-block" onclick="ExpenseReason()">...</button>
											</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="txtParticular">
											</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="txtQuantity" 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="txtAmount" 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="txtExpenseBy">
											</div>
										</div>
										<!-- <div class="form-group row">
											<div class="col-md-8"></div>
											<div class="col-md-4 btnAdd">
												<button type="button" class="btn btn-success btn-block"onclick="create()" id="btnAdd">Add</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 class="form-group row">
											<div class="col-md-6"></div>
											<div class="col-md-3 btnSave"></div>
											<div class="col-md-3 btnSave">
												<button type="button" class="btn btn-success btn-block"onclick="create();" id="btnSave">Save</button>
											</div>
											<div class="col-md-3 btnEdit" style="display: none;">
												<button type="button" class="btn btn-danger btn-block" onclick="clearForm();">Cancel</button>
											</div>
											<div class="col-md-3 btnEdit" style="display: none;">
												<button type="button" class="btn btn-primary btn-block" onclick="create();">Update</button>
											</div>
										</div>
									</div>

								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
			<div class="card card-outline ">
				<div class="card-header">
					<h3 class="card-title">Expense 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 modal-primary" id="myModalExpenseReason">
				<div class="modal-dialog" style="max-width: 100% !important;">
					<div class="modal-content" style="width: 30%; top: 29px; margin-left: 35%;">
						<div class="modal-header">
							<h4 class="modal-title">ExpenseReason</h4>
							
						</div>
						<div class="modal-body">
							<div class="col-md-12">

								<div class="form-group row">
									<label class="col-md-4 col-form-label" style="text-align: right;">Expense Reason:</label>
									<div class="col-md-7">
										<!-- <input type="text" class="form-control" id="txtCity1" style="display:none;"> -->
										<input type="text" class="form-control" id="txtExpenseReason" >
									</div>
									<div class="col-md-1"></div>
								</div>
								<div class="form-group row">
									<label class="col-md-9 col-form-label"></label>
									<div class="col-md-2">
										<button class="btn btn-primary col-md-12" type="button" onclick="addER();">Add</button>
									</div>
									<div class="col-md-1"></div>
								</div>
							</div>
							<div class="col-md-12">
								<div class="card card-outline ">
									<div class="card-body p-0">
										<table class="table table-striped table-responsive table-head-fixed table-bordered " id="myTableER" style="max-height: 500px;">
											<thead>                  
												<tr >
													<th style="width: 1%;">#</th>
													<!-- <th style="width: 20%;">For</th> -->
													<th style="width: 10%;">Expense Reason</th>
													<th style="width: 1%;">Delete</th>
												</tr>
											</thead>
											<tbody>
											</tbody>
										</table>
									</div>
								</div>
							</div>
						</div>
					</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);
		if(C=='Main Office'){
			$("#cboCity").append("<option value= '" + C + "'>" + C + "</option>");	
			getExpenseReason();
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "'>" + C + "</option>");	
			$("#cboFor").append("<option value= '" + C + "'>" + C + "</option>");		
			getExpenseReason();
			getAll();
		}

	});

	// 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) {
	// 			if(v.name!='Main Office'){
	// 				$("#cboCity").append("<option value= '" + v.name + "' data-code= '" + v.code + "' >" + v.name + "</option>");			
	// 			}
				
	// 		});	
	// 		$("#cboCity").val(C);	
	// 	});
	// }
	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(C);	
		});
	}
	
	function ExpenseReason(){
		var city = $("#cboCity").val();
		$("#myModalExpenseReason").modal('show');
		$("#myTableER").find("tbody tr").remove();

		$.ajax({
			url: APP_URL + "api/expense_reason/get_expense_reason.php",
			type: "POST",
			data: JSON.stringify({ city: city}),
		}).done(function(data){
			console.log(data)
				$.each(data.records, function(i, v) {
					$("#myTableER").find("tbody")
						.append($('<tr>')
							.append("<td style='width: 10px'>" + (i +1) + "</td>")
							// .append("<td>" + v.city + "</td>")
							.append("<td>" + v.expense_reason + "</td>")
							.append("<td><button type='button' class='btn btn-block btn-danger btn-sm' onclick='delER(\"" + v.id + "\", this)' style='padding: 2px 13px;font-size: 13px; min-width: 20px'>&times;</button></td>")
						)
				});
				// $("#txtTotalAmountP").val(data.t);
		});
		
	}
	function getExpenseReason(){
		var city = $("#cboCity").val();
		$("#cboFor").append("<option value= '"+$("#cboCity").val()+"' >"+$("#cboCity").val()+"</option>");	
		$("#cboExpenseReason").find("option").remove();
		
		$.ajax({
			url: APP_URL + "api/expense_reason/get_expense_reason.php",
			type: "POST",
				data: JSON.stringify({ city: city}),
		}).done(function(data) {	
			$("#cboExpenseReason").append("<option value = '' ></option>");
			$.each(data.records, function(i, v) {	
				$("#cboExpenseReason").append("<option value= '" + v.expense_reason + "' >" + v.expense_reason + "</option>");							
			});
		});
		
	}


	$('#cboCity').change(function() { 
		getExpenseReason();
		var city = $("#cboCity").val();
		var c_t = $("#cboCity option:selected").attr("data-ctype");
		getAll();
		$("#cboFor").find("option").remove();
		if(c_t=="Head Office"){
			$("#cboFor").append("<option value= '' ></option>");	
			$.ajax({
				url: APP_URL + "api/city/get_all_rows.php"
			}).done(function(data) {
				$.each(data.records, function(i, v) {
					$("#cboFor").append("<option value= '" + v.name + "'>" + v.name + "</option>");			
				});		
				$("#cboFor").val(city);	
			});	
		}else{
			$("#cboFor").append("<option value= '" + city + "'>" + city + "</option>");			
			$("#cboFor").val(city);	
		}

	});

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

	function create(){ 
		var id = $("#txtID").val();
		var date = $("#txtDatePicker").val();
		var voucher_no = $("#txtVoucherNo").val();
		var expense_reason = $("#cboExpenseReason").val();
		var particular = $("#txtParticular").val();
		var quantity = parseInt($("#txtQuantity").val().replace(/,/g, ''));
		var amount = parseInt($("#txtAmount").val().replace(/,/g, ''));
		var expense_by = $("#txtExpenseBy").val();
		var city = $("#cboCity").val();

		if(particular.trim()==""){
			bootbox.alert("Please fill the boxes.");
		}else{
			$.ajax({
				url: APP_URL + "api/expense/create_update.php",
				type: "POST",
				data: JSON.stringify({ id: id, date: date, city: city, voucher_no: voucher_no, expense_reason: expense_reason, particular:particular, quantity:quantity, amount:amount, expense_by:expense_by}),
			}).done(function(data){
				console.log(data);
				if(data.message=="created"){
					bootbox.alert("Created.");
					$("#txtID").val("");
					$("#txtVoucherNo").val("");
					$("#cboExpenseReason").val("");
					$("#txtParticular").val("");
					$("#txtQuantity").val(0);
					$("#txtAmount").val(0);
					$("#txtExpenseBy").val("");
					getAll();
				}else if(data.message=="updated"){
					bootbox.alert("Successfully Updated.");
					$(".btnSave").css("display", "block");
					$(".btnEdit").css("display", "none");
					$("#txtID").val("");
					$("#txtVoucherNo").val("");
					$("#cboExpenseReason").val("");
					$("#txtParticular").val("");
					$("#txtQuantity").val(0);
					$("#txtAmount").val(0);
					$("#txtExpenseBy").val("");
					getAll();
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}   
	}

	function edit(id, obj){
		// $("#txtCustomer").focus();

		// $("#txtCustomer").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);
		$("#txtDatePicker").val($(tr).find("td").eq(1).text());
		$("#txtVoucherNo").val($(tr).find("td").eq(2).text());
		$("#cboExpenseReason").val($(tr).find("td").eq(3).text());
		$("#txtParticular").val($(tr).find("td").eq(4).text());
		$("#txtQuantity").val($(tr).find("td").eq(5).text());
		$("#txtAmount").val($(tr).find("td").eq(6).text());
		// $("#cboFor").val($(tr).find("td").eq(8).text());
		$("#txtExpenseBy").val($(tr).find("td").eq(8).text());
	}

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

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

		$("#txtID").val("");
		$("#txtVoucherNo").val("");
		$("#cboExpenseReason").val("");
		$("#txtParticular").val("");
		$("#txtQuantity").val(0);
		$("#txtAmount").val(0);
		$("#txtExpenseBy").val("");

	}

	function getAll(){
		$("#myTable").find("tbody").find("tr").remove();
		var date = $("#txtDatePicker").val();
		var city = $("#cboCity").val();
		$.ajax({
			url: APP_URL + "api/expense/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ date: date, 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.date + "</td>")
					.append("<td>" + v.voucher_no + "</td>")
					.append("<td>" + v.expense_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.exp_for + "</td>")
					.append("<td>" + v.expense_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/expense/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 addER(){

		var expense_reason = $("#txtExpenseReason").val();
		var city = $("#cboCity").val();

		if(expense_reason == "" ){
		bootbox.alert("Please fill expense reason.");
		}else{
		$.ajax({
			url: APP_URL + "api/expense_reason/create.php",
			type: "POST",
			data: JSON.stringify({expense_reason: expense_reason, city:city})
		}).done(function(data) {
			if(data.message=="created"){
				$("#txtExpenseReason").val("");
				ExpenseReason();
				getExpenseReason();
			}else{
				bootbox.alert("Error on server side.");
			}
		});
		}
	}

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

	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 btozero(obj){
		if($(obj).val() == "")$(obj).val(0);
	}

</script>
