<!DOCTYPE html>
<html lang="en">
<?php include "headerLink.php"?>

<body class="animsition">
    <div class="page-wrapper">
        <!-- HEADER MOBILE-->
        <?php include "menuSideBar_mobile.php" ;?>
        <!-- END HEADER MOBILE-->
		
        <!-- MENU SIDEBAR-->
        <?php include "menuSideBar.php" ;?>
        <!-- END MENU SIDEBAR-->

        <!-- PAGE CONTAINER-->
        <div class="page-container">
            <!-- HEADER DESKTOP-->
			<?php include "headerPage.php"?>
            <!-- END HEADER DESKTOP-->
			
			
			
			<!-- MAIN CONTENT-->
			<?php
			
			
			?>
			
            
            <div class="main-content"  >
                <div class="section__content section__content--p30" >
                    <div class="container-fluid" >
                        <!-- menu show on page after selected - start -->
                        <?php include "selectedMenuSubMenu.php"?>
						<!-- menu show on page after selected - end -->
						<div class="row" >
							
									<?php
									
									function dateDifference($start_date, $end_date)
									{
										// calulating the difference in timestamps 
										$diff = strtotime($start_date) - strtotime($end_date);
										 
										// 1 day = 24 hours 
										// 24 * 60 * 60 = 86400 seconds
										return ceil(abs($diff / 86400));
									}

									$selectedLocation = "";
									$selectedTenantInfo = "";
									$tenantInfo = "";
									$cutOffPayment = "";
									$tenant_status = "";
									$_SESSION["aged_date"] ="";
									//$_SESSION["projectLocation"] = "";
									$_SESSION["tenantInfo"] = "";
									$_SESSION["cutOffPayment"] = "";
									$_SESSION["tenant_status"] = "";
									//$tenant_id = $_GET["tenant_id"];
									$sqlDate = "";
									$selectedDate_cut = "";
									$selectedDate_cutFrom = "";
									$selectedDate_cutTo = "";
									//$_SESSION['projectLocation']=$_GET['projectLocation'];

									$_SESSION['statement_date']="";
									$_SESSION['statement_year']="";
									$_SESSION['statement_monthyear']="";
									$_SESSION['chooseDate']="";
									$_SESSION["statement_ChooseDate"] =  "";
									$_SESSION["statementby"] = "";
									$statementby = "";
									$statement_year = "";
									$statement_monthyear = "";
									$statement_date = "";
									$statement_ByChooseDate = "";
									$selected_cutOffPayment = "";
									$displayYear = "display:none";
									$displayMonthYear = "display:none";
									$displayDateFromTo = "display:none";
									$displayChooseDate = "display:none";
									$displayCheckBox = "display:none";
									$displayStatementOption = "display:none";

									$selectedLocation = $_GET["projectLocation"];
									if($selectedLocation != "" || $selectedLocation != null){
											$projectLocation = $_GET["projectLocation"];
											include "splitLocationName_project.php";
											$project_id = $project_id;
											$location_id = $location_id;
										}
										
										
										
									  $sqlYear = "select YEAR(bills.issue_date) AS year from bills 
												inner join tenants on bills.tenant_id =  tenants.id 
												inner join properties on tenants.property_id = properties.id
												inner join locations on properties.location_id = locations.id
												where locations.id = '$location_id'
												group by year having (year <= YEAR(CURDATE()) and year <> 0 ) order by year ASC";
									$runSqlYear = mysqli_query($link, $sqlYear);
									if($runSqlYear === FALSE){
										die(mysqli_error($link));
									}

									if(isset($_GET["reset"])){
										
										$_SESSION["dateFrom"] ="";
										$_SESSION["dateTo"] ="";
										$_SESSION['statement_date']="";
										$_SESSION['statement_year']="";
										$_SESSION['statement_monthyear']="";
										$_SESSION['chooseDate']="";
										$_SESSION["cutOffPayment"] =  "";
										$_SESSION["statement_ChooseDate"] =  "";
										$_SESSION["statementby"] = "";
										$_GET["statementby"]= "";
										$_GET["statement_year"] = "";
										$_GET["statement_monthyear"] = "";
										$_GET["statement_date"] = "";
										$_GET["statement_ByChooseDate"] = "";
										$_GET["selected_cutOffPayment"] = "";
										$_GET["dateFrom"] = "";
										$_GET["dateTo"] = "";
										$_GET["chooseDate"] = "";
										$_GET["cutOffPayment"] = "";
										$_GET["statement_ChooseDate"] = "";
										
										
										
										$_SESSION["aged_date"] ="";
										$_SESSION["projectLocation"] = "";
										$_SESSION["tenantInfo"] = "";
										$_SESSION["cutOffPayment"] = "";
										$_SESSION["cutOffPayment"] = "";
										$selectedDate = "";
										$selectedLocation = "";
										$selectedTenantInfo = "";
										$cutOffPayment = "";
										$tenant_status = "";
										 $displayYear = "display:none";
										$displayMonthYear = "display:none";
										$displayDateFromTo = "display:none";
										$displayChooseDate = "display:none";
										$displayCheckBox = "display:none";
										$statementby = "";
										$displayStatementOption = "display:none";
									}
									if(isset($_GET["searchAgeing"])){
										
										$dateFrom = "";
										$dateTo = "";
										$statementby = $_GET["statementby"];
										$_SESSION['statementby'] = $statementby;
										$tenant_id = $_GET["tenant_id"];
										$cond_selectedCutOffPayment = "";
										$cond_monthYear_BF = "";
										$cond_date_BF = "";
										$selected_cutOffPayment = "";
										$statement_year_cutOFF ="";
										$infoTarikhTunggakan = "";
										
										
										$selectedDate = $_GET["aged_date"];
										$selectedLocation = $_GET["projectLocation"];
										$selectedTenantInfo = $_GET["tenantInfo"];
										$selected_cutOffPayment = $_GET["cutOffPayment"];
										$tenant_status = $_GET["tenant_status"];
										$_SESSION["aged_date"] = $selectedDate;
										$_SESSION["projectLocation"] = $selectedLocation;
										$_SESSION["tenantInfo"] = $selectedTenantInfo;
										$_SESSION["cutOffPayment"] = $selected_cutOffPayment;
										$_SESSION["tenant_status"] = $tenant_status;
										
										if($selectedLocation != "" || $selectedLocation != null){
											$projectLocation = $_GET["projectLocation"];
											include "splitLocationName_project.php";
											$project_id = $project_id;
											$location_id = $location_id;
										}
										
										
										$cond = "";
										$cond_project = "";
										$cond_location = "";
										$cond_ageingDate = "";
										$cond_tenantInfo = "";
										$cond_tenantStatus = "";
										$cond_staffID = "";
										$groupBY = "";
										$ageingDateInfo ="";
										$cond_selectedCutOffPayment = "";
										
										
										if($statementby == 'statement_year'){
												$displayYear = "display:block";
												$displayMonthYear = "display:none";
												$displayDateFromTo = "display:none";
												$displayChooseDate = "display:none";
												$displayCheckBox = "display:block";
												
												$statement_year = $_GET["statement_year"];
												$_SESSION['statement_year']=$statement_year;
												$selected_cutOffPayment = $_GET["cutOffPayment"];
												$_SESSION["cutOffPayment"] = $selected_cutOffPayment;
												$cutOffDate = date("Y-m-d",strtotime($statement_year . '-12-31')); //tarikh hujung tahun
												$firstYearDate =  date("Y-m-d",strtotime($statement_year . '-01-01')); //tarikh awal tahun
												$statement_year_cutOFF = date('Y-m-d', strtotime($cutOffDate. ' + 1 days'));
												IF($selected_cutOffPayment == true){
													
													$cond_selectedCutOffPayment = " and YEAR(payments.created_at) < '$statement_year_cutOFF'";
												}
												
												$year_selected = date("Y",strtotime($firstYearDate));
												$cond_monthYear_BF = " and year(bills.issue_date) < '$statement_year' ";
												$cond_date_BF = " and payments.created_at < '$firstYearDate' ";
												$sqlDate = "  YEAR(bills.issue_date)  = $year_selected ";
												$infoTarikhTunggakan = " TAHUN $statement_year";
												$date_cutOFF = date('Y-m-d', strtotime($cutOffDate. ' + 1 days'));	
										}
										else if($statementby == 'statement_monthyear'){
												$displayYear = "display:none";
												$displayMonthYear = "display:block";
												$displayDateFromTo = "display:none";
												$displayChooseDate = "display:none";
												$displayCheckBox = "display:block";
												$statement_monthyear = $_GET["statement_monthyear"];
												$_SESSION['statement_monthyear']=$statement_monthyear;
												$selected_cutOffPayment = $_GET["cutOffPayment"];
												$_SESSION["cutOffPayment"] = $selected_cutOffPayment;
												$payment_monthYear = date("m/Y", strtotime($statement_monthyear));
												
												$firstDay = "";
												$lastDay = "";
												
												$firstDay = date("Y-m-01", strtotime($statement_monthyear));
												$lastDay = date("Y-m-t", strtotime($statement_monthyear));
												
												$cond_monthYear_BF = " and issue_date < '$firstDay ' ";
												$cond_date_BF = " and payments.created_at < '$firstDay' ";
												
												$cond_selectedCutOffPayment = " and payments.created_at between '$firstDay' and '$lastDay' ";
											
											$date_monthYear = date("Y-m-01",strtotime($statement_monthyear));
												$lastdate = $date_monthYear . "-01";
												$lastdate = date("Y-m-t", strtotime($lastdate));			
												$cutOffDate = $lastdate;
												
												$sqlDate = "  bills.issue_date  = '$date_monthYear' ";
												$infoTarikhTunggakan = " BULAN $payment_monthYear ";
												$date_cutOFF = date('Y-m-d', strtotime($cutOffDate. ' + 1 days'));	
										}
										else if($statementby == 'statement_date'){
												
												$displayYear = "display:none";
												$displayMonthYear = "display:none";
												$displayDateFromTo = "display:block";
												$displayChooseDate = "display:none";
												$displayCheckBox = "display:block";
												$statement_date = $_GET["statement_date"];
												$dateFrom = date("Y-m-d",strtotime($_GET["dateFrom"]));
												$dateTo =  date("Y-m-d",strtotime($_GET["dateTo"]));
												$_SESSION['statement_date']=$statement_date;
												$_SESSION['dateFrom']=$dateFrom;
												$_SESSION['dateTo']=$dateTo;
												$date_cutOFF = date('Y-m-d', strtotime($dateTo. ' + 1 days'));	
												
												$firstDay = $dateFrom;
												$lastDay = $date_cutOFF;
												
												$cond_selectedCutOffPayment = " and payments.created_at between '$firstDay' and '$lastDay' ";
												$sqlDate = " (bills.issue_date  >= '$dateFrom'  and bills.issue_date < '$date_cutOFF') ";
												$infoTarikhTunggakan = " DARI ".date("d/m/Y",strtotime($dateFrom)) . " SEHINGGA " . date("d/m/Y",strtotime($dateTo));
										}
										else if($statementby == 'statement_ChooseDate'){
												$displayYear = "display:none";
												$displayMonthYear = "display:none";
												$displayDateFromTo = "display:none";
												$displayChooseDate = "display:block";
												$displayCheckBox = "display:block";
												$chooseDate = date("Y-m-d",strtotime($_GET["chooseDate"]));
												$_SESSION['chooseDate']=$chooseDate;
												$selected_cutOffPayment = $_GET["cutOffPayment"];
												$_SESSION["cutOffPayment"] = $selected_cutOffPayment;
												$date_cutOFF = date('Y-m-d', strtotime($chooseDate. ' + 1 days'));	
												$cond_selectedCutOffPayment = "";
												if($_GET["chooseDate"] != "" || $_GET["chooseDate"] == null){
													$cond_selectedCutOffPayment = " and payments.created_at >= '$date_cutOFF'";
												}
												$sqlDate = " bills.issue_date < '$date_cutOFF' ";
												$cutOffDate = $chooseDate;
												$infoTarikhTunggakan = " SEHINGGA ". date("d/m/Y",strtotime($chooseDate));
										}
										else if($statementby == ""){
											$cutOffDate = date('Y-m-d', strtotime($chooseDate. ' + 1 days'));
											$cond_selectedCutOffPayment = " and payments.created_at < '$cutOffDate'";
											$sqlDate = " bills.issue_date < '$cutOffDate' ";
											$infoTarikhTunggakan = " SEHINGGA " . DATE("d/m/Y");
											$date_cutOFF = date('Y-m-d', strtotime($cutOffDate. ' + 1 days'));	
										}
										
										if($tenant_status != ""){
											if($tenant_status == "Active"){
												$cond_tenantStatus = " and  UPPER(tenants.status) = 'ENABLE' ";
											}
											else if($tenant_status == "Deactive"){
												$cond_tenantStatus = " and  UPPER(tenants.status) = 'DISABLE' ";
											}
											else if($tenant_status == "allTenant"){
												$cond_tenantStatus = "";
											}
											
										}
										
										
										//check ID staff_id
										if($_SESSION["username"] != "admin"){
											$cond_staffID = " and extra_locations.user_id = " .$_SESSION["staff_id"];
										}
										
										//selection option
										//1. pilih tarikh shj
										if($selectedDate != "" && $selectedLocation == "" && $selectedTenantInfo == ""){
											$groupBY = " group by locations.id";
											
										}
										//2. pilih location shj
										if($selectedDate == "" && $selectedLocation != "" && $selectedTenantInfo == ""){
											$groupBY = " group by  tenants.id ";
											$cond_location = " and locations.id = $location_id and  projects.id  = $project_id ";
											
										}
										//3. pilih nama/ic/mykad/company name shj
										if($selectedDate == "" && $selectedLocation == "" && $selectedTenantInfo != ""){
											$groupBY = " group by locations.id";
											$cond_tenantInfo = " and (properties.unit_no LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.tenant_name  LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.ic_no  LIKE '%".$selectedTenantInfo."%'" ."  )";
											
										}
										//4. pilih tarikh dan location
										if($selectedDate != "" && $selectedLocation != "" && $selectedTenantInfo == ""){
											$groupBY = " group by  tenants.id ";
											$cond_location = " and locations.id = $location_id and  projects.id  = $project_id";
											
										}
										//5. pilih tarikh dan nama/ic/mykad/company name shj
										if($selectedDate != "" && $selectedLocation == "" && $selectedTenantInfo != ""){
											$groupBY = " group by  tenants.id ";
											$cond_tenantInfo = " and (properties.unit_no LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.tenant_name  LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.ic_no  LIKE '%".$selectedTenantInfo."%'" ."  )";
											
										}
										//6. pilih location dan nama/ic/mykad/company name shj
										if($selectedDate == "" && $selectedLocation != "" && $selectedTenantInfo != ""){
											$groupBY = " group by  tenants.id ";
											$cond_location = " and locations.id = $location_id and  projects.id  = $project_id";
											$cond_tenantInfo = " and (properties.unit_no LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.tenant_name  LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.ic_no  LIKE '%".$selectedTenantInfo."%'" ." )";
											
										}
										//7. tak pilih semua
										if($selectedDate == "" && $selectedLocation == "" && $selectedTenantInfo == ""){
											$groupBY = " group by locations.id";
											
										}
										//8. pilih semua
										if($selectedDate != "" && $selectedLocation != "" && $selectedTenantInfo != ""){
											$groupBY = " group by  tenants.id ";
											$cond_location = " and locations.id = $location_id and  projects.id  = $project_id";
											$cond_tenantInfo = " and (properties.unit_no LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.tenant_name  LIKE '%".$selectedTenantInfo."%'" ." or 
														 tenants.ic_no  LIKE '%".$selectedTenantInfo."%'" ." )";
										}
										if($selectedDate == "" && $statementby == ""){
											$selectedDate = date("d/m/Y");
											$ageingDateInfo = " SEHINGGA " .$selectedDate;
											
										}
										else{
											$ageingDateInfo = " SEHINGGA " .date("d/m/Y",strtotime($selectedDate));
											
										}
										
										IF($selected_cutOffPayment == true){
													
											//$cond_selectedCutOffPayment = " and YEAR(payments.created_at) < '$statement_year_cutOFF'";
										}
										
										$cond = $cond_location . $cond_ageingDate . $cond_tenantInfo . $cond_staffID . $cond_tenantStatus ;
										
										 $sqlAgeingGroupBy = "select 
															 tenants.id as tenant_id,
															locations.id as location_id, 
															 locations. location_name , 
															properties.unit_no as unit, 
															concat( tenants.tenant_name) as name, 
															SUM(bills.bill_amount ) as total_outstanding,
															extra_locations.user_id
															from bills 
															inner join tenants on bills.tenant_id =  tenants.id
															inner join properties on properties.id = tenants.property_id
															inner join locations on properties.location_id = locations.id 
															inner join projects on locations.project_id = projects.id
															inner join extra_locations on locations.id = extra_locations.location_id 
															inner join users on extra_locations.user_id = users.id
															where (lower(bills.payment_status) = 'unpaid' or lower(bills.payment_status) = 'partial') 
															AND bills.bill_amount  <> 0 
															$cond order by properties.id
															";
										$runSqlAgeingGroupBy = mysqli_query($link, $sqlAgeingGroupBy);
										if($runSqlAgeingGroupBy === FALSE){
											die(mysqli_error($link));
										}
										
										
										
										
									}
										
										

									?>
							<div class="col-lg-12">
									<div align="center">
										<form action="<?php $_SERVER['PHP_SELF']; ?>" method="get">
											<input type="hidden" name="tenant_id" value="<?php echo $tenant_id?>">
											<input type="hidden" name="login" value="<?php echo $_GET["login"]?>">
											
												<div class="card shadow mb-4">
													<div class="card-header py-3">
														<h3 class="m-0 font-weight-bold text-primary">AGED RECEIVABLES [DETAIL]</h3>
													</div>
													<div class="card-body">
														<div class="table-responsive">
															<table class="table table-bordered" id="dataTable" width="50%" cellspacing="0" style="font-size: 12px" class="form-control">
																<tr>
																	<td><b>LOCATION</b></td>
																	<td>
																		<input type="text" list="projectLocation" name="projectLocation" class="form-control" onChange="javascript: submit();"  value="<?php echo $_SESSION['projectLocation']?>" placeholder="Select Location"/>
																		<datalist id="projectLocation">
																		
																		<?php
																		
																			if($_SESSION["username"] != "admin"){
																				
																				$sqlLocations = "SELECT * FROM ( 
																							(select EL.location_id, locations.location_name, projects.project_name from extra_locations as EL 
																							inner join locations on locations.id = EL.location_id 
																							inner join projects on locations.project_id = projects.id 
																							inner join users on EL.user_id =  users.id
																							where users.id = ". $_SESSION['staff_id'] .") 
																						UNION 
																							(select locations.id, locations.location_name, projects.project_name from locations 
																							inner join users on locations.id = users.location_id 
																							inner join projects on locations.project_id = projects.id
																							where users.id = ". $_SESSION['staff_id'] .") 
																						) results ORDER BY project_name ASC";
																				
																				$runLocations = mysqli_query($link,$sqlLocations);
																				if($runLocations === FALSE){
																					die(mysqli_error($link));//TODO: better error handling
																				}
																			}
																			else if($_SESSION["username"] == "admin"){
																				$sqlLocations = "select locations.*, projects.project_name ,  projects.id as project_id  from locations 
																									inner join projects on locations.project_id = projects.id 
																									ORDER BY projects.project_name ASC";
																				$runLocations = mysqli_query($link, $sqlLocations);
																				if($runLocations === FALSE){
																					die(mysqli_error($link));
																				}
																			}

																			while($resultLocations = mysqli_fetch_array($runLocations)){
																				$location_id = $resultLocations["id"];
																				$location_name = $resultLocations["location_name"];
																				$project_name = $resultLocations["project_name"];
																					?>
																					
																					<option value="<?php echo $project_name . "-" . $location_name; ?>">
																					<?php
																			}
																		?>
																		</datalist> <?php //echo $sqlLocations?>
																	</td>
																</tr>
																<tr>
																	<tH VALIGN="TOP" ALIGN="LEFT" >STATEMENT OPTION</tH>
																	<td>
															
																		<select name="statementby" id="statementby" onchange="statementbyFunc()" class="form-control" >
																			<option value="">Select Statement Option</option>
																			<option value="statement_year" <?php echo ($_SESSION["statementby"] ==  'statement_year')  ? "selected" : "" ?>>STATEMENT BY YEAR</option>
																			<option value="statement_monthyear" <?php echo ($_SESSION["statementby"] ==  'statement_monthyear')  ? "selected" : "" ?>>STATEMENT BY MONTH AND YEAR</option>
																			<option value="statement_date" <?php echo ($_SESSION["statementby"] ==  'statement_date')  ? "selected" : "" ?>>STATEMENT BY DATE (BETWEEN TWO DATES)</option>
																			<option value="statement_ChooseDate" <?php echo ($_SESSION["statementby"] ==  'statement_ChooseDate')  ? "selected" : "" ?> >STATEMENT BY CUT OFF DATE</option>
																		</select>
																	</td>
																</tr>
															<tr id="statement_option" style="$displayStatementOption">
																<td>&nbsp;</td>
																<td id="statement_ByYear" style='<?php echo $displayYear ?>;font-size:12px'>
																	<?php //if($_SESSION["statement_year"])?>
																	<select name="statement_year" class="form-control">
																		<option value="">Please Select Year</option>
																		<?php while($resultYear = mysqli_fetch_array($runSqlYear)){?>
																				<option value="<?php echo $resultYear["year"]?>" <?php echo ($_SESSION["statement_year"] ==  $resultYear["year"])  ? "selected" : "" ?> ><?php echo $resultYear["year"]?></option>
																		<?php } ?>
																	</select>
																</td>
																<td id="statement_ByMonthYear" style='<?php echo $displayMonthYear  ?>;font-size:12px'>
																	<input type="month"  name="statement_monthyear" id="statement_monthyear" value="<?php echo $_SESSION["statement_monthyear"]?>" class="form-control" size="20"/>
																</td>
																<td id="statement_ByDate" style='<?php echo $displayDateFromTo ?>;font-size:12px'>
																	From <input id='dateFrom' name='dateFrom' type='date' size='10' class="form-control" value="<?php echo $_SESSION["dateFrom"]?>"> 
																	To <input id='dateTo' name='dateTo' type='date' size='10'  class="form-control" value="<?php echo $_SESSION["dateTo"]?>">
																</td>
																<td id="statement_ByChooseDate" style='<?php echo $displayChooseDate ?>;font-size:12px'>
																	Choose Date <?echo $_SESSION["statementby"]?><input class="form-control" id='chooseDate' name='chooseDate' type='date' size='10' value="<?php echo $_SESSION["chooseDate"]?>"> 
																</td>
															</tr>
																		
															<tr>
																<td>&nbsp;</td>
																<td id="statement_cutOff" style='<?php  echo $displayCheckBox  ?>;font-size:12px'>
																<div>
																	<input type="checkbox" id="cutOffPayment" name="cutOffPayment" <?php echo ($_SESSION["cutOffPayment"]) ? "checked" : "" ?> value="true">
																	<label for="cutOffPayment" style="font-size:16px"><b> View Ageing Record based on cut off payments same as selected Month / Year </b></label>
																</div>
																</td>
															</tr>
															</tr>
																<tr>
																	<td><strong>TENANT STATUS </strong></td>
																	<td class="form-control">
																		<input type="radio" name="tenant_status" value="allTenant" <?php echo (strtoupper($_SESSION["tenant_status"]) == 'ALLTENANT') ?'CHECKED' : '';?>>ALL TENANTS
																		<input type="radio" name="tenant_status" value="Active" <?php echo (strtoupper($_SESSION["tenant_status"]) == 'ACTIVE') ?'CHECKED' : '';?>>Active only
																		<input type="radio" name="tenant_status" value="Deactive" <?php echo (strtoupper($_SESSION["tenant_status"]) == 'DEACTIVE') ? 'CHECKED' : '';?>>Deactive only
																	</td>	
																</tr>
																<tr>
																	<td><b>INDIVIDUAL RECORD: </b></td>
																	<td>
																		<input type="text" class="form-control" name = "tenantInfo" placeholder = "Enter Unit No. / MyKad / Tenant Name / Company Name" size ="40" style="border:solid 2px; border-color:#66ccff" value="<?php echo $_SESSION["tenantInfo"]?>">
																	</td>
																</tr>
																<tr>
																	<td colspan="2" align="center">
																		<br/>
																		<button class="btn btn-primary" type="submit" name="searchAgeing">SEARCH AGEING</button>
																		<button class="btn btn-secondary" type="submit" name="reset">RESET</button>
																	</td>
																</tr>
															</table>
														</DIV>
													</DIV>
												</DIV>
										</form>
									</div>
									<?php if(isset($_GET["searchAgeing"])){ ?>
									<div class="card shadow mb-4">
										<div class="card-header py-3">
											<h3 class="m-0 font-weight-bold text-primary">MAKLUMAT TUNGGAKAN  <?PHP echo strtoupper($locationName) . " - " . $infoTarikhTunggakan?></h3>
										</div>
										<div class="card-body">
											<div class="table-responsive">
												<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0" style="font-size: 12px">
													<thead>
													
														<tr >
															<td colspan="11">
																<div align="center">
																	<form action="print_ageingStatement.php" method="get">
																		<input type="hidden" name="selectedDate" value="<?php echo $sqlDate?>">
																		<input type="hidden" name="selectedLocation" value="<?php echo $selectedLocation?>">
																		<input type="hidden" name="selectedTenantInfo" value="<?php echo $selectedTenantInfo?>">
																		<input type="hidden" name="sqlAgeingGroupBy" value="<?php echo $sqlAgeingGroupBy?>">
																		<input type="hidden" name="selected_cutOffPayment" value="<?php echo $selected_cutOffPayment?>">
																		<button type="submit" name="printReport" >PRINT AGEING RECORD</button>
																	</form>
																	
																</div>
															</td>
														</tr>
														<tr bgcolor="#ebeced">
															<th>Bil.</th>
															<th>Unit No.</th>
															<th>Invois ID#</th>
															<th>Tarikh</th>
															<th>Jumlah (RM)</th>
															<th>0-30 Hari</th>
															<th>31-60 Hari</th>
															<th>61-90 Hari</th>
															<th>91-120 Hari</th>
															<th>121-150 Hari</th>
															<th>150+ Hari</th>
														</tr>
													</thead>
														<?php
														$tenantLocationGroup = "";
														$bil_location = 1;
														$grandTotalOutstanding_all = 0; 
														
														$all_bill_ball30 = 0;
														$all_bill_ball3160 = 0;
														$all_bill_ball6190 = 0;
														$all_bill_ball91120 = 0;
														$all_bill_ball121150 = 0;
														$all_bill_ball151 = 0;
														while($resultSqlAgeingGroupBy = mysqli_fetch_array($runSqlAgeingGroupBy)){
															
															$tenant_id =  $resultSqlAgeingGroupBy['tenant_id'];
															$tenant_name =  $resultSqlAgeingGroupBy['tenant_name'];
															//$tenant_company =  $resultSqlAgeingGroupBy['company'];
															$tenant_unit =  $resultSqlAgeingGroupBy['unit'];
															$location_id =  $resultSqlAgeingGroupBy['location_id'];
															$groupBY = "";
															$sqlRentalMonth = "";
															
														?>
														<tr bgcolor="#4F6AAE">
															<td colspan="11">
																<!--<h3><?php echo "$bil_location ".strtoupper($location_group); ?></h3>-->
																<font style="color:white"><b><?php echo "$locationName "; ?></b></font>
															</td>
														</tr>
														<?php
															//sql group by tenant
																					//sqlAgeing_byTenant
																					
														$sqlOrderBy = "";
														 "sqlAgeing_byTenant 1: ". $sqlAgeing_byTenant = "SELECT * FROM ( 
																							(select sum( payments.amount_paid ) + bills.bill_amount  as total_outstanding , 
																							 tenants.id as tenant_id, 
																							  locations. location_name  as location,
																							 properties.unit_no as unit, 
																							  tenants.tenant_name  as name,  
																							  locations. location_name 
																							from payments 
																							 inner join bills on payments.bill_id = bills.id 
																							 inner join tenants on bills.tenant_id =  tenants.id 
																							 inner join properties on tenants.property_id = properties.id
																							 inner join locations on properties.location_id = locations.id
																							 inner join projects on locations.project_id = projects.id
																							 where $sqlDate and (lower(bills.payment_status) = 'paid' or lower(bills.payment_status) = 'partial') 
																							 and locations.id = $location_id $cond_selectedCutOffPayment $cond_tenantStatus and bills.bill_type_id = 1
																							 group by  tenants.id  having sum(bills.bill_amount ) > 0) 
																							UNION ALL 
																							(select SUM(bills.bill_amount ) as total_outstanding , 
																							 tenants.id as tenant_id, 
																							  locations. location_name  as location,
																							 properties.unit_no as unit, 
																							  tenants.tenant_name  as name,  
																							  locations. location_name 
																							from bills 
																							inner join tenants on bills.tenant_id =  tenants.id
																							inner join properties on tenants.property_id = properties.id 
																							inner join locations on properties.location_id = locations.id 
																							inner join projects on locations.project_id = projects.id 
																							where $sqlDate and (lower(bills.payment_status) = 'unpaid' or lower(bills.payment_status) = 'partial') 
																							and locations.id = $location_id $cond_tenantStatus and bills.bill_type_id = 1
																							group by  tenants.id   
																							having sum(bills.bill_amount ) > 0) ) 
																							results group by tenant_id ORDER BY tenant_id ASC	"; 
															
															if($_SESSION["projectName"] == 'PPR'){
																$sqlOrderBy = " order by property_id ASC";
															}
															else{
																$sqlOrderBy = " ORDER BY (CASE WHEN unit_no like '[a-z]%' THEN 0 ELSE 1 END),unit_no ";
																if($location_id == 44 || $location_id == 9 || $location_id == 18 ||  $location_id == 43 || $location_id == 2 || $location_id == 5){
																	$sqlOrderBy = " ORDER BY (CASE WHEN unit_no like '[a-z]%' THEN 0 ELSE 1 END),unit_no , CAST(unit_no AS SIGNED integer), SUBSTRING_INDEX(unit_no, '-', 1) ASC, CAST(SUBSTRING_INDEX(unit_no, '-', -1) AS SIGNED)";
																}					//ORDER BY (CASE WHEN unit_no like '[a-z]%' THEN 0 ELSE 1 END),unit_no , CAST(unit_no AS SIGNED integer), SUBSTRING_INDEX(unit_no, '-', 1) ASC, CAST(SUBSTRING_INDEX(unit_no, '-', -1) AS SIGNED) ASC
															}
																					//sqlAgeing_byTenant
															   

															   /*   ECHO "sqlAgeing_byTenant 2: ". $sqlAgeing_byTenant = "SELECT * FROM ( 
																																	(select (bills.bill_amount -  sum(payments.amount_paid)) as total_outstanding, bills.*, payments.created_at as payment_created_at, 
																																				properties.unit_no, tenants.tenant_name as name, properties.id as property_id from payments 
																																				inner join bills on payments.bill_id = bills.id 
																																				inner join tenants on bills.tenant_id = tenants.id 
																																				inner join properties on tenants.property_id = properties.id 
																																				inner join locations on properties.location_id = locations.id  
																																				where locations.id = $location_id  
																																				$cond_selectedCutOffPayment
																																				and $sqlDate and bills.bill_type_id = 1   
																																				group by bills.issue_date, tenants.id  having total_outstanding <> 0 ) 
																																UNION (select bills.bill_amount as total_outstanding, 
																																			bills.* , bills.created_at as payment_created_at, properties.unit_no, tenants.tenant_name as name , properties.id as property_id
																																			from bills 
																																			inner join tenants on bills.tenant_id = tenants.id 
																																			inner join properties on tenants.property_id = properties.id 
																																			inner join locations on properties.location_id = locations.id 
																																			where $sqlDate
																																			and bills.id not in (select payments.bill_id from payments 
																																										inner join bills on payments.bill_id = bills.id 
																																										inner join tenants on bills.tenant_id = tenants.id 
																																										inner join properties on tenants.property_id = properties.id 
																																										inner join locations on properties.location_id = locations.id WHERE locations.id = $location_id ) 
																																			and locations.id = $location_id 
																																			and bills.bill_type_id = 1 
																																			group by bills.issue_date,tenants.id having total_outstanding > 0 ) 
																																	 
																																	UNION (select bills.bill_amount as total_outstanding, 
																																			bills.* , bills.created_at as payment_created_at, properties.unit_no, tenants.tenant_name as name , properties.id as property_id
																																			from bills 
																																			inner join tenants on bills.tenant_id = tenants.id 
																																			inner join properties on tenants.property_id = properties.id 
																																			inner join locations on properties.location_id = locations.id 
																																			where $sqlDate
																																			and bills.id  in (select payments.bill_id from payments 
																																										inner join bills on payments.bill_id = bills.id 
																																										inner join tenants on bills.tenant_id = tenants.id 
																																										inner join properties on tenants.property_id = properties.id 
																																										inner join locations on properties.location_id = locations.id 
																																										WHERE locations.id = $location_id  $cond_selectedCutOffPayment ) 
																																			and locations.id = $location_id 
																																			and bills.bill_type_id = 1 
																																			group by bills.issue_date,tenants.id having total_outstanding > 0
																																	
																																	)
																																	)
																																	results 
																																group by tenant_id having total_outstanding > 0 $sqlOrderBy "; */
															
															//include tenant rental rate
															 ECHO "sqlAgeing_byTenant 2: ". $sqlAgeing_byTenant = "SELECT * FROM ( 
																																	(select (bills.bill_amount -  sum(payments.amount_paid)) as total_outstanding, bills.*, payments.created_at as payment_created_at, 
																																				properties.unit_no, tenants.tenant_name as name, properties.id as property_id from payments 
																																				inner join bills on payments.bill_id = bills.id 
																																				inner join tenants on bills.tenant_id = tenants.id 
																																				inner join properties on tenants.property_id = properties.id 
																																				inner join locations on properties.location_id = locations.id  
																																				where locations.id = $location_id  
																																				$cond_selectedCutOffPayment
																																				and $sqlDate and bills.bill_type_id = 1   
																																				group by bills.issue_date, tenants.id  having total_outstanding <> 0 ) 
																																UNION (select bills.bill_amount as total_outstanding, 
																																			bills.* , bills.created_at as payment_created_at, properties.unit_no, tenants.tenant_name as name , properties.id as property_id
																																			from bills 
																																			inner join tenants on bills.tenant_id = tenants.id 
																																			inner join properties on tenants.property_id = properties.id 
																																			inner join locations on properties.location_id = locations.id 
																																			 
																																			where $sqlDate 
																																			and bills.id not in (select payments.bill_id from payments 
																																										inner join bills on payments.bill_id = bills.id 
																																										inner join tenants on bills.tenant_id = tenants.id 
																																										inner join properties on tenants.property_id = properties.id 
																																										inner join locations on properties.location_id = locations.id WHERE locations.id = $location_id ) 
																																			and locations.id = $location_id 
																																			and bills.bill_type_id = 1 
																																			
																																			group by bills.issue_date,tenants.id having total_outstanding > 0 ) 
																																	 
																																	UNION (select bills.bill_amount as total_outstanding, 
																																			bills.* , bills.created_at as payment_created_at, properties.unit_no, tenants.tenant_name as name , properties.id as property_id
																																			from bills 
																																			inner join tenants on bills.tenant_id = tenants.id 
																																			inner join properties on tenants.property_id = properties.id 
																																			inner join locations on properties.location_id = locations.id 
																																			where $sqlDate
																																			and bills.id  in (select payments.bill_id from payments 
																																										inner join bills on payments.bill_id = bills.id 
																																										inner join tenants on bills.tenant_id = tenants.id 
																																										inner join properties on tenants.property_id = properties.id 
																																										inner join locations on properties.location_id = locations.id 
																																										WHERE locations.id = $location_id  $cond_selectedCutOffPayment ) 
																																			and locations.id = $location_id 
																																			and bills.bill_type_id = 1 
																																			group by bills.issue_date,tenants.id having total_outstanding > 0
																																	
																																	)
																																	)
																																	results 
																																group by tenant_id having total_outstanding > 0 $sqlOrderBy ";
															
															
															
															
															
															$runSqlAgeing_byTenant = mysqli_query($link, $sqlAgeing_byTenant);
															if($runSqlAgeing_byTenant === FALSE){
																die(mysqli_error($link));
															}
															$bil_tenant = 1;
															$location_bill_ball30 = 0;
															$location_bill_ball3160 = 0;
															$location_bill_ball6190 = 0;
															$location_bill_ball91120 = 0;
															$location_bill_ball121150 = 0;
															$location_bill_ball151 = 0;
															$grandTotalOutstanding_location = 0; 
														
															while($resultSqlAgeing_byTenant = mysqli_fetch_array($runSqlAgeing_byTenant)){
																$tenant_unit = $resultSqlAgeing_byTenant["unit_no"];
																$tenant_name = $resultSqlAgeing_byTenant["name"];
																$company_name = $resultSqlAgeing_byTenant["company"];
																$tenant_location = $resultSqlAgeing_byTenant["location"];
																 $tenant_id = $resultSqlAgeing_byTenant["tenant_id"];
																//$tenant_name = "";
																
														?>
														<tr bgcolor="#D8E2FB">
															<td colspan="11">
																<font style="color:white">TENANT<a href="viewTenantDashboard.php?tenant_id=<?php echo $tenant_id?>" target="_blank"><?php echo $bil_tenant . ". " . strtoupper($tenant_unit . " " .$tenant_name ); ?></a></font>
																
															</td>
														</tr>
														
														<?php
															echo "::SQL DATE::".$sqlRentalMonth = " $sqlDate ";
															
															//AGEING SQL PART
															include("sql_ageingPart.php");
															
															$runSqlAgeing = mysqli_query($link, $sqlAgeing);
															if($runSqlAgeing === FALSE){
																die(mysqli_error($link));
															}
															//AGEING SQL PART END
															//ECHO $sqlAgeing;
															
															$bil = 1;
															
															$tenant_totalOutstanding = 0;
															$bill_ball30 = 0;
															$bill_ball3160 = 0;
															$bill_ball6190 = 0;
															$bill_ball91120 = 0;
															$bill_ball121150 = 0;
															$bill_ball151 = 0;
															$grandTotalOutstanding_tenant = 0; 
															while($resultSqlAgeing = mysqli_fetch_array($runSqlAgeing)){
																$bill_bal = $resultSqlAgeing['total_outstanding'];
																$invDate = $resultSqlAgeing['issue_date'];
																$location = $resultSqlAgeing['location'];
																$unit = $resultSqlAgeing['unit'];
																$tenant_name = $resultSqlAgeing['name'];
																$invDate = date("Y-m-d",strtotime($resultSqlAgeing['issue_date']));
																$aged_date = date("Y-m-d", strtotime($date_cutOFF));
																 
																$start_date = $invDate;
																$end_date = $aged_date;
																// call dateDifference() function to find the number of days between two dates
																$diff = dateDifference($start_date, $end_date);
																
														?>
														<tr bgcolor="#F8FAFE">
															<td align="center"><b><?php echo $bil; ?></b></td>
															<td align="center"><b><?php echo $tenant_unit; ?></b></td>
															<td align="center"><b><?php echo $resultSqlAgeing['bill_no']; ?></b></td>
															<td align="center"><b><?php echo date("d/m/Y",strtotime($resultSqlAgeing['issue_date'])); ?></b></td>
															<td align="center"><b><?php echo number_format($bill_bal,2); ?></b></td>
															<td align="center">
																<b><?php 
																		if($diff <= 30){
																			echo number_format($bill_bal,2);
																			$bill_ball30 += $bill_bal;
																			
																		}
																	?>
																</b>
															</td>
															<td align="center">
																<b><?php 
																		if($diff >= 31 && $diff <= 60){
																			echo number_format($bill_bal,2);
																			$bill_ball3160 += $bill_bal;
																			
																		}
																	?>
																</b>
															</td>
															<td align="center">
																<b><?php 
																		if($diff >= 61 && $diff <= 90){
																			echo number_format($bill_bal,2);
																			$bill_ball6190 += $bill_bal;
																			
																		}
																	?>
																</b>
															</td>
															<td align="center">
																<b><?php 
																		if($diff >= 91 && $diff <= 120){
																			echo number_format($bill_bal,2);
																			$bill_ball91120 += $bill_bal;
																			
																		}
																	?>
																</b>
															</td>
															<td align="center">
																<b><?php 
																		if($diff >= 121 && $diff <= 150){
																			echo number_format($bill_bal,2);
																			$bill_ball121150 += $bill_bal;
																			
																		}
																	?>
																</b>
															</td>
															<td align="center">
																<b><?php 
																		if($diff > 150){
																			echo number_format($bill_bal,2);
																			$bill_ball151 += $bill_bal;
																			
																		}
																	?>
																</b>
															</td>
														</tr>
														<?php
																$bil++;
																$tenant_totalOutstanding  += $bill_bal;
																$grandTotalOutstanding_tenant += $bill_bal;
															}//close grandTotalOutstanding_tenant
																$bil_tenant++;
															
															?>
														<tr  bgcolor="#F8FAFE">
															<td align="RIGHT" colspan = "4" ><b>Jumlah (RM): </b></td>
															<td align="center"><b><?php echo number_format($grandTotalOutstanding_tenant,2);?></b></td>
															<td align="center"><b><?php echo number_format($bill_ball30,2);?></b></td>
															<td align="center"><b><?php echo number_format($bill_ball3160,2);?></b></td>
															<td align="center"><b><?php echo number_format($bill_ball6190,2);?></b></td>
															<td align="center"><b><?php echo number_format($bill_ball91120,2);?></b></td>
															<td align="center"><b><?php echo number_format($bill_ball121150,2);?></b></td>
															<td align="center"><b><?php echo number_format($bill_ball151,2);?></b></td>
														</tr>
															<?php
															//$tenantLocationGroup = $tenant_location;
															$total_billBal += $tenant_totalOutstanding;
															$grandTotalOutstanding_location += $grandTotalOutstanding_tenant;
															$location_bill_ball30 += $bill_ball30;
															$location_bill_ball3160 += $bill_ball3160;
															$location_bill_ball6190 += $bill_ball6190;
															$location_bill_ball91120 += $bill_ball91120;
															$location_bill_ball121150 += $bill_ball121150;
															$location_bill_ball151 += $bill_ball151;
															}//close grandTotalOutstanding_location
														?>
														<tr bgcolor="#D8E2FB">
															<td align="RIGHT" colspan = "4" ><b>JUMLAH KESELURUHAN TUNGGAKAN LOKASI <?PHP ECHO strtoupper($locationName)?>(RM): </b></td>
															<td align="center"><b><?php echo number_format($grandTotalOutstanding_location,2);?></b></td>
															<td align="center"><b><?php echo number_format($location_bill_ball30,2);?></b></td>
															<td align="center"><b><?php echo number_format($location_bill_ball3160,2);?></b></td>
															<td align="center"><b><?php echo number_format($location_bill_ball6190,2);?></b></td>
															<td align="center"><b><?php echo number_format($location_bill_ball91120,2);?></b></td>
															<td align="center"><b><?php echo number_format($location_bill_ball121150,2);?></b></td>
															<td align="center"><b><?php echo number_format($location_bill_ball151,2);?></b></td>
														</tr>
														<?php
															$bil_location++;
															$grandTotalOutstanding_all += $grandTotalOutstanding_location;
															$all_bill_ball30 += $location_bill_ball30;
															$all_bill_ball3160 += $location_bill_ball3160;
															$all_bill_ball6190 += $location_bill_ball6190;
															$all_bill_ball91120 += $location_bill_ball91120;
															$all_bill_ball121150 += $location_bill_ball121150;
															$all_bill_ball151 += $location_bill_ball151;
														} //close grandTotalOutstanding_all
														?>
														<tr bgcolor="red">
															<td align="RIGHT" colspan = "4" ><font style="color:white"><b>JUMLAH KESELURUHAN TUNGGAKAN (RM): </b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($grandTotalOutstanding_all,2);?></b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($all_bill_ball30,2);?></b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($all_bill_ball3160,2);?></b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($all_bill_ball6190,2);?></b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($all_bill_ball91120,2);?></b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($all_bill_ball121150,2);?></b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($all_bill_ball151,2);?></b></font></td>
														</tr>
														<?PHP 
														//KIRAAN AGEING PERCENT - MULA
														//100% = grandTotalOutstanding_all
														$percent_bill_ball30 = ($all_bill_ball30 / $grandTotalOutstanding_all) * 100;
														$percent_bill_ball3160 = ($all_bill_ball3160 / $grandTotalOutstanding_all) * 100;
														$percent_bill_ball6190 = ($all_bill_ball6190 / $grandTotalOutstanding_all) * 100;
														$percent_bill_ball91120 = ($all_bill_ball91120 / $grandTotalOutstanding_all) * 100;
														$percent_bill_ball121150 = ($all_bill_ball121150 / $grandTotalOutstanding_all) * 100;
														$percent_bill_ball151 = ($all_bill_ball151 / $grandTotalOutstanding_all) * 100;
														//KIRAAN AGEING PERCENT - TAMAT
														?>
														<tr bgcolor="red">
															<td align="RIGHT" colspan = "4" ><font style="color:white"><b>AGEING PERCENT: </b></font></td>
															<td align="center"><b></b></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($percent_bill_ball30,2);?>%</b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($percent_bill_ball3160,2);?>%</b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($percent_bill_ball6190,2);?>%</b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($percent_bill_ball91120,2);?>%</b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($percent_bill_ball121150,2);?>%</b></font></td>
															<td align="center"><font style="color:white"><b><?php echo number_format($percent_bill_ball151,2);?>%</b></font></td>
														</tr>
												</table>
											</div>
										</div>
									</div>
									<?php } ?>
							
							
							
							
                        </div>
                        
                        <?PHP include "footer.php";?>
                        
                    </div>
                </div>
            </div>
            <!-- END MAIN CONTENT-->
            <!-- END PAGE CONTAINER-->
        </div>
		
    </div>
    <?PHP include "footerLink.php";?>
</body>

</html>
<!-- end document-->
