<?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>Monthly - Report</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">
					<div class="card card-outline ">
						<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: 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;">Date From: </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>
									<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="txtDatePicker2" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
												</div>
											</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;">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;">Account Head:</label>
											<div class="col-md-8">
                                                <select type="text" class="form-control" id="cboExpenseReason">
												</select>
											</div>
										</div>	
                                    </div> -->
									<!-- <div class="col-md-6"></div> -->
					                <div class="col-md-6">
					                	<div class="form-group row">
                                        <div class="col-md-6"></div>
					                		<div class="col-md-3">
					                			<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 ">
				<div class="card-header">
					<h3 class="card-title"><span id="total_records" style="font-weight:bold;"> Detail</span></h3>
				</div>
				<div class="card-body p-0 table-responsive ">
					<table class="table table-head-fixed table-bordered" id="myTable" style="max-height: 500px;">
						<thead>                  
							<tr>
								<!-- <th style="width: 3%">#</th> -->
								<th style="width: 30%">Description</th>
								<th style="width: 20%">Cash In</th>
                                <th style="width: 30%">Description</th>
                                <th style="width: 20%">Cash Out</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
						<tfoot>
							<tr>
								<td colspan='4'>
									<div class="form-group row">
										<label class="col-md-4 col-form-label" style="text-align: right;"><span id="note"></span>Note:</label>
										<div class="col-md-8">
											<textarea type="text" rows="10" class="form-control" id="txtNote" disabled></textarea>										
											<span type="text"  class="form-control" id="txtNoteSpan" style='display:none;'></span>
											<br><button type='button' class='btn btn-success' onclick="Save();" style='display:none;' id='btnSave'><i class='fas fa-plus'></i></button>
										</div>
									</div>
								</td>
							</tr>
							
						</tfoot>
					</table>

				</div>
			</div>

			<div class="modal fade modal-primary" id="myModalIncome">
				<div class="modal-dialog" style="max-width: 100% !important;">
					<div class="modal-content" style="width: 60%;margin-left: 20%;">
						<!-- <div class="modal-content" style="width: 46%; top: 29px; margin-left: 28%;"> -->
						<div class="modal-header">
							<h4 class="modal-title" id="mdtitle"></h4>&nbsp;-&nbsp;<h4 class="modal-title" id="mdtitle1"></h4>
						</div>
						<div class="modal-body">							
							<div class="col-md-12">
								<div class="card card-outline ">
									<div class="card-body p-0">
										<table class="table table-striped table-responsive table-bordered" id="myTable1" style="max-height: 500px;">
											<thead>                  
												<tr>
													<th style="width: 3%">#</th>
													<th style="width: 10%;">Date</th>
													<th style="width: 10%;">Description</th>
													<th style="width: 10%;">Particular</th>
													<th style="width: 10%;">Amount</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");
		$('#txtDatePicker1, #txtDatePicker2').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>");	

		}

	});

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

	$("#txtNote").on("input",function(){
		$("#txtNoteSpan").text($(this).val());
	});
	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>");			
			});		
		});
	}
	var BAL = 0 ;
	var COL = "" ;
    function search(){
		$("#loading").css("display","block");
		var df =$("#txtDatePicker1").val();
		var dt =$("#txtDatePicker2").val();
		var city = $("#cboCity").val();
		$("#note").text("("+df.substring(0,7)+") ");
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			type: "POST",
			url: APP_URL + "api/sales/search_cash_book_main.php",
			data: JSON.stringify({ df: df,dt: dt,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_in, function(i, v) {
				var s="In";
				$("#myTable").find("tbody")
				.append($('<tr>')
					// .append("<td style='width: 10px'>" + (i+1) + "</td>")
					.append("<td onclick='getDetail(\"" + s + "\",\"" + v.description + "\",\"" + v.cash_in + "\");' style='color:blue;cursor:pointer;'>" + v.description + "</td>")
					.append("<td style='text-align:right;' >" + v.cash_in + "</td>")
					.append("<td></td>")
                    .append("<td></td>")
					)
			});	

            // $("#myTable").find("tbody")
			// 	.append($('<tr>')
			// 		// .append("<td style='width: 10px'>" + (i+1) + "</td>")
            //         .append("<td></td>")
            //         .append("<td></td>")
			// 		.append("<td>Opening Balance</td>")
			// 		.append("<td style='text-align:right;'>" + data.opening_balance + "</td>")
			// 		)

              $.each(data.records_out, function(i, v) {
				var s="Out";

				$("#myTable").find("tbody")
				.append($('<tr>')
					// .append("<td style='width: 10px'>" + (i+1) + "</td>")
                    .append("<td></td>")
                    .append("<td></td>")
					.append("<td onclick='getDetail(\"" + s + "\",\"" + v.description + "\",\"" + v.cash_out + "\",\"" + v.t + "\");' style='color:blue;cursor:pointer;'>" + v.description + "</td>")
					.append("<td style='text-align:right;'>" + v.cash_out + "</td>")
					)

				if(v.ascd==48){
					$("#myTable").find("tbody")
					.append($('<tr>')
					// .append("<td style='width: 10px'>" + (i+1) + "</td>")
                    .append("<td></td>")
                    .append("<td></td>")
					.append("<td></td>")
					.append("<td></td>")
					)
				}
			});	
			$("#myTable").find("tbody")
					.append($('<tr>')
					// .append("<td style='width: 10px'>" + (i+1) + "</td>")
                    .append("<td></td>")
                    .append("<td></td>")
					.append("<td></td>")
					.append("<td></td>")
					)


			$("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;">')
            .append("<td colspan='1' style='text-align:left;'>Total</td>")
            .append("<td style='text-align:right;'>" + ((data.cash_in_total)?data.cash_in_total:0) + "</td>")
			.append("<td style='text-align:left;'>Total</td>")
			.append("<td style='text-align:right;'>" + ((data.cash_out_total)?data.cash_out_total:0) + "</td>")
  			); 

			  var $bc=$bc5=$bc3=$bc1="";
			if(parseInt(data.cash_balance)<0){
				 $bc="color:red;";
				 COL ="color:red;";
			}else{
				$bc="";
				COL ="";
			}
			BAL = data.cash_balance;

            $("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;background-color:yellow;">')
            .append("<td colspan='3' style='text-align:right;'><button type='button' style='margin-left: 5px;' class='btn btn-success float-left' onclick='addNote()'><i class='fas fa-edit'></i> </button>Balance Amount</td>")
			.append("<td style='text-align:right;"+$bc+"'>" + ((data.cash_balance)?data.cash_balance:0) + "</td>")
  			); 


       });

	   getNote();
	}	

	function addItem(){
		$("#myTable").find("tbody")
		.append($('<tr style="font-weight:bold;">')
		// .append("<td colspan='3' style='text-align:center;'><input onkeypress='return isNumber(event)' onkeyup='abc(this);btozero(this);' onchange='abc(this);' type='text' style='text-align:right;width: 100px;margin-left: 85%;'  class='form-control input-group-prepend' value='0' ><span class='input-group-append'>%</span></td>")
		.append("<td colspan='3' style='text-align:center;'><div class='row'><input onkeypress='return isNumber(event)' onkeyup='abc(this);btozero(this);' onchange='abc(this);' type='text' style='text-align:right;width: 100px;margin-left: 87%;margin-right:10px;' class='col-md-1 form-control input-group-prepend' value='0'><span style='display:none;'></span><label class='col-form-label' style='text-align: right;'> %</label></div></td>")
		.append("<td style='text-align:right;"+COL+"'>" + 0 + "</td>")
		); 
	}

	function addNote(){
		$("#txtNote").attr("disabled",false);
		$("#btnSave").css("display","");
	}

	function abc(obj){
		var par = parseInt($(obj).val().replace(/,/g, '')) * parseInt(BAL.replace(/,/g, '')) / 100;
		$(obj).parent().parent().parent().find("td").eq(1).text(parseInt(par).toLocaleString());
		$(obj).parent().find("span").eq(0).text(parseInt($(obj).val().replace(/,/g, '')));

	}

	function getDetail(r,st,amt,t){

		$("#myModalIncome").modal('show');
		$("#mdtitle").text(st);

		$("#myTable1").find("tbody tr").remove();
		var df =$("#txtDatePicker1").val();
		var dt =$("#txtDatePicker2").val();
		var city = $("#cboCity").val();
		$.ajax({
			url: APP_URL + "api/sales/get_monthly_detail.php",
			type: "POST",
			data: JSON.stringify({ r:r, df: df, dt: dt, city: city, st:st, t:t })
		}).done(function(data){
			console.log(data.records)
				$.each(data.records, function(i, v) {
					$("#myTable1").find("tbody")
						.append($('<tr>')
							.append("<td style='width: 10px'>" + (i+1) + "</td>")
							.append("<td>" + v.date + "</td>")
							.append("<td>" + v.description + "</td>")
							.append("<td>" + v.particular + "</td>")
							.append("<td  style='text-align:right;'>" + v.amount + "</td>")
						)
				});
				$("#mdtitle1").text(data.total_amountF);
				// $("#txtTotalAmountP").val(data.t);
		});		
	}

	function View(){
		window.open(APP_URL + "index_share.php?city=" + $("#cboCity").val(),'_blank');
		// document.location = APP_URL + "index_share.php?city=" + $("#cboCity").val(), '_blank';
	}

	function Save(){
		$("#loading").css("display","block");
		var df = $("#txtDatePicker1").val().substring(0,7);
		var city = $("#cboCity").val();
		var note = $("#txtNote").val();

		$.ajax({
			url: APP_URL + "api/note/create.php",
			type: "POST",
			data: JSON.stringify({ city: city, df: df, note: note })
		}).done(function(data){	
			$("#loading").css("display","none");
			if(data.message=="created"){
				$("#txtNoteSpan").text(note);
				$("#txtNote").attr("disabled",true);
				$("#btnSave").css("display","none");
			}
		});
	}

	function getNote(){

		var city = $("#cboCity").val();
		var df = $("#txtDatePicker1").val().substring(0,7);

		$.ajax({
			url: APP_URL + "api/note/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ city: city, df: df })
		}).done(function(data) {	

			$.each(data.records, function(i, v) {	
				$("#txtNote").val(v.note);
				$("#txtNoteSpan").text(v.note);
			});
		});
	}

	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);
			$(obj).parent().parent().parent().find("td").eq(1).text(0)
		}
	}

</script>	
