<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<style>
	
	.hId{
		display: none;
	}
	@media (max-width:480px){
	    .pagination{
	        display: inline-block;
	    }
	    div.dataTables_wrapper div.dataTables_filter input {
	        display: block;
	        padding-left: 0px !important;
	    }
	    .installID{
	        width: 112% !important;
	        margin-left: 14.5% !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>Bank In Out </h3>
				</div>
				<div class="col-md-6">
				</div>
			</div>
		</div>
	</section>
	<section class="content">
		<div class="container-fluid">
			<div class="row" id="entry">
				<div class="col-md-12">
					<div class="card card-outline card-primary">
						<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-4">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
											<div class="col-md-8">
												<input class="form-control" type="text" id="txtID" style="display:none;">
                                                <select type="text" class="form-control" id="cboCity"></select>
											</div>
										</div>
										<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-4">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Description:</label>
											<div class="col-md-8">
												<select type="text" class="form-control" id="cboDescription">
													<option value="Cash Deposit">Cash Deposit</option>
													<option value="Cash Withdrawal">Cash Withdrawal</option>
													<option value="Interest Post Credit Customer">Interest Post Credit Customer</option>
												</select>
											</div>
										</div>	
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Amount: </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtAmount" onfocus="this.select();" onkeypress="return isNumber(event)" onkeyup="btozero(this);" value=0 style='text-align: right;'>
											</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;">Remark: </label>
											<div class="col-md-8">
												<textarea type="text" id="txtRemark" class="form-control" rows="2" ></textarea>
											</div>
										</div>	
										<div class="form-group row" id="btnentry">
											<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>
						</form>
					</div>
				</div>
			</div>

			<div class="card card-outline card-primary">
				<div class="card-header">
					<h3 class="card-title">Bank In Out List<span  style="font-weight:bold;"> </span></h3>
					<!-- <button type="button" class="btn btn-primary float-right" onclick='getExcelImportForm(this);'><i class="fas fa-plus"></i> Excel Import</button> -->
					<button type="button" id="btnExport" value=" Export Table data into Excel " datafrom="myTable" class="btn btn-success  exportToExcel1 float-right">Export Data</button> 
				</div>
				<div class="card-body">
					<table id="myTable" class="table table-bordered table-hover" style="border-collapse: collapse !important;" >
						<thead style="background-color: #ecedee;">
							<tr>
								<th style='width:5%;'>No.</th>
								<th>Date</th>
                                <th>Description</th>
                                <th>Deposit</th>
                                <th>Withdrawal</th>
                                <th>Balance</th>
                                <th>Remark</th>
                                <th class="hId">CID</th>
 								<th style='width:5%;'>Edit</th>
 								
								<!-- <th>Delete</th> -->
							</tr>
						</thead>
						<tbody style="cursor: pointer;"></tbody>
					</table>
				</div>
			</div>

<!-- 			<div class="card card-outline card-primary">
				<div class="card-header">
					<h3 class="card-title">Customer List<span id="total_records" style="font-weight:bold;"> </span></h3>
					<div class="card-tools">
						<span><input type="text" class="form-control" id="txtSearch" style='padding-right:0px;' placeholder='Search Here'></span>
					</div>
				</div>
				<div class="card-body p-0">
					<table class="table table-striped table-responsive table-head-fixed table-bordered" id="myTable" style="max-height: 500px;">
						<thead>                  
							<tr>
								<th style="width: 3%">#</th>
								<th style="width: 20%">Name</th>
								<th style="width: 15%">Phone</th>
								<th style="width: 15%">Member Type</th>
								<th>Address</th>
								<th style="width: 3%;">Edit</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div> -->

		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>
	var C = '<?php echo isset($_SESSION['city'])?$_SESSION['city']:""?>';
	var userrole= '<?php echo $_SESSION['userrole']?>';
	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'){
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "'  >" + C + "</option>");	
			getAll();
		}

			if (userrole != "Admin") {
				$("#myTable th:eq(8), #myTable td:nth-child(9)").remove();
		        $("#btnentry").attr("style", "display:none;");
		    }
	});

		
	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").change(function(){
		getAll();
	});

	function create(){ 
		var id = $("#txtID").val();
		var city = $("#cboCity").val();
		var date = $("#txtDatePicker").val();
		var description = $("#cboDescription").val();
		var amount = parseFloat($("#txtAmount").val().replace(/,/g, ''));
		var remark = $("#txtRemark").val();
		
		if(city.trim()=="" || description.trim()==""){
			bootbox.alert("Please fill the boxes.");
		}else{
			$.ajax({
				url: APP_URL + "api/bank_in_out/create_update.php",
				type: "POST",
				data: JSON.stringify({ id: id, city: city, date: date, description:description, amount: amount, remark: remark }),
			}).done(function(data){
				console.log(data);
				if(data.message=="created"){
					bootbox.alert("Created.");
					clearForm();
					getAll();
				}else if(data.message=="updated"){
					bootbox.alert("Successfully Updated.");
					clearForm();
					getAll();
				}else if(data.message=="duplicate"){
					bootbox.alert("Duplicate data.");
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}   
	}

function getAll(){


		var city = $("#cboCity").val();
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			type: "POST",
			url: APP_URL + "api/bank_in_out/get_all_rows.php",
			data: JSON.stringify({ city: city })
		}).done(function(data) {	

			$.each(data.data, function(i, v) {

			  
				$("#myTable").find("tbody")
				.append($('<tr>')
					// .append("<td>" + (i+1) + "</td>")
                    .append("<td>" + v.i + "</td>")
                    .append("<td>" + v.date + "</td>")
					.append("<td>" + v.description + "</td>")
					.append("<td style='text-align:right'>" + v.in_amount + "</td>")
					.append("<td style='text-align:right'>" + v.out_amount +"</td>")
					.append("<td style='text-align:right'>" + v.balance +"</td>")
					.append("<td>" + v.remark +"</td>")
					.append("<td style='display:none;'>" + v.id +"</td>")
					.append("<td><button type='button' class='btn btn-block btn-primary btn-sm fas fa-edit' onclick='edit(\"" + v.id + "\",this)' style='padding: 0px 13px;font-size: 14px; min-width: 37px'></button></td>")
					// .append("<td>"+ ((userrole!="Admin")?"<button type='button' class='btn btn-block btn-success btn-sm fas fa-edit' onclick='edit(\"" + v.id + "\",this)' style='padding: 0px 13px;font-size: 14px; min-width: 37px'></button>":"") +"</td>")
				);
			});	

			if (userrole != "Admin") {
				$("#myTable th:eq(8), #myTable td:nth-child(9)").remove();
		        $("#btnentry").attr("style", "display:none;");
		    }

			$("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;">')
			.append("<td colspan='3' style='text-align:right;'>Total:</td>")
			.append("<td style='text-align:right;'>" + data.in_total + "</td>")
			.append("<td style='text-align:right;'>" + data.out_total + "</td>")
			.append("<td style='text-align:right;'>" + data.b_total + "</td>")

  			);  
			
       });
	}	

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

	// 	table = $('#myTable').DataTable({
	// 		"destroy": true,
	// 		"paging": true,
	// 		"lengthChange": true,
	// 		"searching": true,
	// 		"ordering": true,
	// 		"info": true,
	// 		"autoWidth": false,
	// 		"responsive": true,
	// 		"lengthMenu": [10, 50, 500, 1000, -1],
	// 		"pageLength": 10,
	// 		"ajax": APP_URL + "api/bank_in_out/get_all_rows.php?city=" + city,
	// 		"columnDefs": [
	// 			{
	// 				'targets': 8,
	// 				'searchable': false,
	// 				'orderable': false,	
	// 				'render': function (){	
	// 					return '<td><button type="button" class="btn btn-block btn-success btn-sm fas fa-edit" onclick="edit(this)" style="padding: 0px 13px;font-size: 14px; min-width: 37px"></button></td>';	
	// 				}
	// 			},
	// 			{
	// 				className: "hId", targets: [7],
	//             },
	//             {
	//                 targets: [3, 4, 5], // 4rd, 5th, and 6th columns
	//                 render: function (data, type, row) {
	//                     return '<div style="text-align: right;">' + data + '</div>';
	//                 }
	//             },
	// 			{ 
    //                 'searchable'    : false, 
    //                 'targets'       : [0,1,3,4,5,6,7] 
    //             },
	//             ]
			
	// 	});

	// }


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

		// $("#txtCustomer").attr("disabled", true);
		$("#cboCity").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();
		var opt = $(tr).find("td").eq(3).text();

		$("#txtID").val($(tr).find("td").eq(7).text());
		$("#txtDatePicker").val($(tr).find("td").eq(1).text());
		$("#cboDescription").val($(tr).find("td").eq(2).text());

		if($(tr).find("td").eq(3).text()==''){
			$("#txtAmount").val($(tr).find("td").eq(4).text());
		}else{
			$("#txtAmount").val($(tr).find("td").eq(3).text());
		}
		
		$("#txtRemark").val($(tr).find("td").eq(6).text());
	}

	function clearForm(){

		// $("#txtCustomer").attr("disabled", false);
		$("#cboCity").attr("disabled", false);

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

		$("#txtID").val("");
		$("#txtAmount").val(0);
		$("#txtRemark").val("");
		// $('#optNORMAL').attr('checked', 'checked');
	}

	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/bank_in_out/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 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 isNumber(evt) {
    // Ensure that the event object is defined
    evt = evt || window.event;

    // Reference to the input field
    var inputField = evt.target;

    // Current value of the input field
    var value = inputField.value;

    // Determine the character code of the pressed key
    var charCode = evt.which || evt.keyCode;

    // Check if the key pressed is a numeric character (0-9)
    // Allow special keys like Backspace, Tab, Enter, etc. (charCode 8, 9, 13, etc.)
    if ((charCode > 31 && charCode < 48) || charCode > 57) {
        // If the key is not numeric, check if it's a period (.) and if it has already been used
        if (charCode === 46 && value.indexOf('.') === -1) {
            // Allow the first period
            return true;
        }
        // If it's not a valid key, prevent the default action
        return false;
    }

    // If the key is numeric, check the current value and allow only two decimal places
    if (value.indexOf('.') !== -1) {
        var decimalPart = value.split('.')[1];
        if (decimalPart && decimalPart.length >= 2) {
            // If there are already two decimal places, prevent further input
            return false;
        }
    }

    // If the key is numeric and meets the conditions, allow the default action
    return true;
}



	function btozero(obj){
		// generatePackage();
		if($(obj).val() == ""){

			$(obj).val(0);

		}

	}	

$(".exportToExcel1").click(function(){
	exportExcel1("#myTable");
});

function exportExcel1(tableSelector) {
	var table = $(myTable);
		$(table).tableExport({
			type: 'xlsx',
			fileName: "sn" + new Date().toISOString().replace(/[\-\:\.]/g, ""),
			excel: {fileFormat: 'xlsx'},
			ignoreColumn: [7, 8] 
		});
    // var table = $(tableSelector).DataTable();

    // table.buttons.exportData({
    //     modifier: {
    //         columns: ':visible' 
    //     },
    //     format: {
    //         body: function (data, row, column, node) {
    //             // Customize the exported data if needed
    //             return column === 2 || column === 3 || column === 4 ? data : node.innerText.trim();
    //         }
    //     }
    // });
}


</script>
