<?php

	session_start();
	header("Content-type: application/json");
	date_default_timezone_set('Africa/Mogadishu');
	include("../library/conn.php");
	//Include required PHPMailer files
	require '../library/mailer/PHPMailer.php';
	require '../library/mailer/SMTP.php';
	require '../library/mailer/Exception.php';
	//Define name spaces
	use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\SMTP;
	use PHPMailer\PHPMailer\Exception;
	$action = $_POST['action'];
	$errorList = array();

	// Time formatter function
	function time_formatter($time_ago) {
		$time_ago = strtotime($time_ago);
		$cur_time   = time();
		$time_elapsed   = $cur_time - $time_ago;
		$seconds    = $time_elapsed ;
		$minutes    = round($time_elapsed / 60 );
		$hours      = round($time_elapsed / 3600);
		$days       = round($time_elapsed / 86400 );
		$weeks      = round($time_elapsed / 604800);
		$months     = round($time_elapsed / 2600640 );
		$years      = round($time_elapsed / 31207680 );
		
		if ($seconds <= 60) { return "Few moments ago"; }		// Seconds
		else if ($minutes <= 60) {								// Minutes
			if ($minutes==1) { return "One minute ago"; }
			else { return "$minutes minutes ago"; }
		} else if ($hours <= 24) {								// Hours
			if ($hours==1) { return "One hour ago"; }
			else { return "$hours hours ago"; }
		} else if ($days <= 7) {								// Days
			if($days==1){ return "Yesterday at ". date('H:i', $time_ago); }
			else { return "$days days ago (". date('F j H:i', $time_ago). ")"; }
		} else {
			return date('F j, Y H:i', $time_ago);
		}
	}

	// ========================== Our Encrytion Function =======================================
	$ereyFure = 'qkwjdiw239&&jdafweihbrhnan&^%$ggdnawhd4njshjwuuO';
	function bedelXogta($xogta, $ereyFure) {
		$encryption_key = base64_decode($ereyFure);
		$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
		$encrypted = openssl_encrypt($xogta, 'aes-256-cbc', $encryption_key, 0, $iv);
		return base64_encode($encrypted . '::' . $iv);
	}
	function kuceliAsalka($xogta, $ereyFure) {
		$encryption_key = base64_decode($ereyFure);
		list($encrypted_data, $iv) = array_pad(explode('::', base64_decode($xogta), 2), 2, null);
		return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
	}
	//=========================================================================================

	//========== Generate 15 Mixed Random Confirmation code when admin/users signup ===========
	function generateRandomString($length = 25) {
		$characters = '0123456789';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}
	//========================================================================================

	// ========================== Start of Manage Menus ======================================
	
	// Display System Menus Table
	function display_system_menus($conn) {
		$getSystemMenus = mysqli_query($conn, "SELECT * FROM main_menus ORDER BY mainMenuRank ASC");
		if ($getSystemMenus) {
			if (mysqli_num_rows($getSystemMenus) > 0) {
                ?><table class="table table-striped table-sm" id="systemMenusTable">
					<thead>
						<tr class="text-center bg-primary text-light" height="38px">
							<th class="align-middle text-center" width="10%">+ New Menu</th>
							<th class="align-middle text-center" width="20%">Menus Name</th>
							<th class="align-middle text-center">Sub Menus</th>
							<th class="align-middle text-center" width="12%">Action</th>
						</tr>
					</thead>
                    <tbody class="menu_ranking"><?php
				        while ($main_rs = mysqli_fetch_array($getSystemMenus)) { ?>
							<tr style="cursor: all-scroll;" menu-id="<?php echo $main_rs[0] ?>">
							    
								<td class="align-middle text-center"><span id="generateNewMenu" style="cursor: pointer;"><i class="fa fa-plus fa-lg p-2 text-white bg-success rounded"></i></span></td>
								
								<td class="align-middle text-left">
									<i class="<?php echo $main_rs[2]; ?> fa-lg pl-2"></i> <a href="<?php echo $main_rs[3]; ?>"><b><?php echo $main_rs[1]; ?></b></a>
								</td>
								
								<td class="align-middle text-left">
								    <?php
										$getSubmenus = mysqli_query($conn, "SELECT * FROM sub_menus WHERE mainMenuID = '". $main_rs[0] ."' ORDER BY subMenuRank ASC");
										if ($getSubmenus) {
											$submenu_num = mysqli_num_rows($getSubmenus);
											if ($submenu_num > 0) {
											    ?><table class="table table-sm" id="systemSubmenusTable">
                                                    <thead>
														<tr height="35px">
															<th width="10%">+Submenu </th>
															<th>Submenu Name</th>
															<th width="15%" class="text-center"><center>Action</center> </th>
														</tr>
													</thead>
													<tbody class="submenu_ranking"><?php
														while ($submenu_rs = mysqli_fetch_array($getSubmenus)) {?>
															<tr submenu-id="<?php echo $submenu_rs[0] ?>">
															    <td class="align-middle text-left"><span id="generateNewSubmenu" style="cursor: pointer;"><i class="fa fa-plus fa-lg p-2 text-white bg-dark rounded"></i></span></td>
																<td class="align-middle text-left">
																	<i class="<?php echo $submenu_rs[2]; ?> fa-lg"></i> &nbsp;&nbsp;<a href="<?php echo $submenu_rs[3]; ?>"><?php echo $submenu_rs[1]; ?></a>
																</td>
																<td class="align-center">
																    <div class="btn-group col-md-10">
                                                                        <button type="button" class="btn btn-success btn-sm">Action</button>
                                                                        <button type="button" class="btn btn-success btn-sm dropdown-toggle dropdown-toggle-split" data-toggle="dropdown">
                                                                            <span class="caret"></span>
                                                                        </button>
                                                                        <div class="dropdown-menu" style="min-width: 8rem;">
                                                                            <a href="#" class="dropdown-item text-primary updateSubMenu" id="<?php echo "Update". $submenu_rs[0]; ?>" data-id="<?php echo $submenu_rs[0]; ?>" data-toggle="modal" data-target="#updateSubMenuModals"><i class="fa fa-fw fa-lg fa-edit"></i> Edit</a>
                                                                            <a href="#" class="dropdown-item text-danger subMenuDeletion" id="<?php echo "Delete". $submenu_rs[0]; ?>" data-id="<?php echo $submenu_rs[0]; ?>"><i class="fa fa-fw fa-lg fa-trash"></i> Delete</a>
                                                                        </div>
                                                                    </div>
																</td>
															</tr><?php
														} ?>
													</tbody>
												</table><?php
											} else {
											    ?><table class="table table-sm">
												    <tbody>
                                                        <tr>
													        <td class="align-middle text-left"></td>
                                                			<td class='align-middle' colspan='3'>
                                                			    <div class='row no-gutters'>
                                                    			    <div class='col-md-4 pr-1'><input type='text' class='form-control' name='txtFirstSubmenuNamesList[]' id='txtFirstSubmenuNamesList' placeholder='Enter first submenu name' required /></div>
                                                    			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtFirstSubmenuIconsList[]' id='txtFirstSubmenuIconsList' placeholder='Enter fa icon' required /></div>
                                                    			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtFirstSubmenuLinksList[]' id='txtFirstSubmenuLinksList' placeholder='Enter submenu link' required /></div>
                                                    			    <div class='col-md-2 text-right pr-1'>
                                                			            <span class='btn btn-primary btnSaveFirstGeneratedSubmenu'><i class='fa fa-save'></i> Save</span>
                                                			        </div>
                                                    		    </div>
                                                		    </td>
                                                		</tr>
                                                	</tbody>
                                                </table><?php
											}
										} else {
											echo mysqli_error($conn);
										}
									?>
									
								</td>
						
								<td class="align-middle text-center">
								    <div class="btn-group col-md-10">
                                        <button type="button" class="btn btn-dark btn-sm">Action</button>
                                        <button type="button" class="btn btn-dark btn-sm dropdown-toggle dropdown-toggle-split" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <div class="dropdown-menu" style="min-width: 8rem;">
                                            <a href="#" class="dropdown-item text-primary updateMainMenu" id="<?php echo "Update". $main_rs[0]; ?>" data-id="<?php echo $main_rs[0]; ?>" data-toggle="modal" data-target="#updateMainMenuModal"><i class="fa fa-fw fa-lg fa-edit"></i> Edit</a>
                                            <a href="#" class="dropdown-item text-danger mainMenuDeletion" id="<?php echo "Delete". $main_rs[0]; ?>" data-id="<?php echo $main_rs[0]; ?>"><i class="fa fa-fw fa-lg fa-trash"></i> Delete</a>
                                        </div>
                                    </div>
								</td>
					        </tr><?php
				        } ?>
				   </tbody>
		        </table><?php
		        
			} else {
			    
			    ?><table class="table table-sm">
			        <thead>
						<tr class="text-center bg-primary text-light" height="38px">
							<th class="align-middle text-center" width="10%">+ New Menu</th>
							<th class="align-middle text-center" width="20%">Menus Name</th>
							<th class="align-middle text-center">Sub Menus</th>
							<th class="align-middle text-center" width="12%">Action</th>
						</tr>
					</thead>
				    <tbody>
                        <tr>
                			<td class='align-middle text-center'></td>
                			<td class='align-middle' colspan='3'>
                			    <div class='row no-gutters'>
                    			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtFirstMenuNamesList[]' id='txtFirstMenuNamesList' placeholder='Enter first menu name' required /></div>
                    			    <div class='col-md-4 pr-1'><input type='text' class='form-control' name='txtFirstMenuIconsList[]' id='txtFirstMenuIconsList' placeholder='Enter font awesome icon' required /></div>
                    			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtFirstMenuLinksList[]' id='txtFirstMenuLinksList' placeholder='Enter menu link (URL)' required /></div>
                			        <div class='col-md-2 text-center pr-1'>
                			            <span class='btn btn-primary btnSaveFirstGeneratedMenu'><i class='fa fa-save'></i> Save Menu</span>
                			        </div>
                			    </div>
                            </td>
                		</tr>
                	</tbody>
                </table><?php

			}
		} else {
			echo mysqli_error($conn);
		}
	}
	
	// Add First System Menu
	function register_first_system_menu($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
	    $registerFirstSystemMenu = mysqli_query($conn, "INSERT INTO main_menus(mainMenuText, mainMenuIcon, mainMenuURL, mainMenuRank, registeredBy, registerDate, updatedBy, updateDate) VALUES ('" . mysqli_real_escape_string($conn, $first_system_menu_name) . "', '" . mysqli_real_escape_string($conn, $first_system_menu_icon) . "', '" . mysqli_real_escape_string($conn, $first_system_menu_link) . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
	    if ($registerFirstSystemMenu) {
	        $data = json_encode(array('Status' => true, 'Message' => 'System menu has been registered successfully'));
	    } else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	
	// Add New System Menu
	function register_new_system_menu($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$getPreviousMenuRanking = mysqli_query($conn, "SELECT mainMenuRank FROM main_menus WHERE mainMenuID = '" . mysqli_real_escape_string($conn, $prev_menu_id) . "'") or die(mysqli_error($conn));
		$prev_menu_rank_rs = mysqli_fetch_array($getPreviousMenuRanking);
        $new_menurank_no = $prev_menu_rank_rs[0] + 1;
        $rank_start_no = $prev_menu_rank_rs[0] + 1;
        $getMenuIddFromStartRank = mysqli_query($conn, "SELECT mainMenuID FROM main_menus WHERE mainMenuRank >= $rank_start_no ORDER BY mainMenuRank ASC") or die(mysqli_error($conn));
        if (mysqli_num_rows($getMenuIddFromStartRank) > 0) {
            while ($menu_id_rs = mysqli_fetch_array($getMenuIddFromStartRank)) {
                $rank_start_no++;
                mysqli_query($conn, "UPDATE main_menus SET mainMenuRank = '". mysqli_real_escape_string($conn, $rank_start_no) ."' WHERE mainMenuID = '". mysqli_real_escape_string($conn, $menu_id_rs[0]) ."'") or die(mysqli_error($conn));
            }
        }
	    $registerNewSystemMenu = mysqli_query($conn, "INSERT INTO main_menus(mainMenuText, mainMenuIcon, mainMenuURL, mainMenuRank, registeredBy, registerDate, updatedBy, updateDate) VALUES ('" . mysqli_real_escape_string($conn, $system_menu_name) . "', '" . mysqli_real_escape_string($conn, $system_menu_icon) . "', '" . mysqli_real_escape_string($conn, $system_menu_link) . "', '" . mysqli_real_escape_string($conn, $new_menurank_no) . "', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
	    if ($registerNewSystemMenu) {
	        $data = json_encode(array('Status' => true, 'Message' => 'System menu has been registered successfully'));
	    } else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	
	// Chane Menu Rank By Drugging
	function change_menu_rank ($conn) {
		$returned_data = array();
		$data = array();
		extract($_POST);
		$count_menu = 1;
        foreach ($all_menu_ids as $key => $menu_id) {
            mysqli_query($conn, "UPDATE main_menus SET mainMenuRank = '". $count_menu ."' WHERE mainMenuID = '" . mysqli_real_escape_string($conn, $menu_id). "'") or die(mysqli_error($conn));
            $count_menu++;
        }
	}
	
	// Chane Submnu Rank By Drugging
	function change_submenu_rank ($conn) {
		$returned_data = array();
		$data = array();
		extract($_POST);
		$count_submenu = 1;
        foreach ($all_submenu_ids as $key => $submenu_id) {
            mysqli_query($conn, "UPDATE sub_menus SET subMenuRank = '". $count_submenu ."' WHERE subMenuID = '" . mysqli_real_escape_string($conn, $submenu_id). "'") or die(mysqli_error($conn));
            $count_submenu++;
        }
	}
	
	// Fetch Menu Details
	function fetch_menu_details ($conn) {
		$returned_data = array();
		$data = array();
		extract($_POST);
		$getMenuDetails = mysqli_query($conn, "SELECT * FROM main_menus WHERE mainMenuID = '" . mysqli_real_escape_string($conn, $selected_menu_id) . "'");
		if ($getMenuDetails) {
			if (mysqli_num_rows($getMenuDetails) > 0) {
				$row = mysqli_fetch_array($getMenuDetails);
				$returned_data[] = $row;
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Menu Not Found"));
			}
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
		echo $data;
	}
	
	// Update Menu Details
	function update_menu_details($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
	    $updateMenuDetails = mysqli_query($conn, "UPDATE main_menus SET mainMenuText = '" . mysqli_real_escape_string($conn, $selected_menu_name) . "', mainMenuIcon = '" . mysqli_real_escape_string($conn, $selected_menu_icon) . "', mainMenuURL = '" . mysqli_real_escape_string($conn, $selected_menu_link) . "', updatedBy = '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', updateDate = '". date("Y-m-d H:i") ."' WHERE mainMenuID = '" . mysqli_real_escape_string($conn, $selected_menu_id) . "'") or die(mysqli_error($conn));
	    if ($updateMenuDetails) {
	        $data = json_encode(array('Status' => true, 'Message' => 'System menu has been updated successfully'));
	    } else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	
	// Add New First Submenu for a Parent Menu
	function register_first_submenu($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
	    $registerFirstSubmenuMenu = mysqli_query($conn, "INSERT INTO sub_menus(subMenuText, subMenuIcon, subMenuURL, subMenuRank, mainMenuID, registeredBy, registerDate, updatedBy, updateDate) VALUES ('" . mysqli_real_escape_string($conn, $first_submenu_menu_name) . "', '" . mysqli_real_escape_string($conn, $first_submenu_menu_icon) . "', '" . mysqli_real_escape_string($conn, $first_submenu_menu_link) . "', '1', '" . mysqli_real_escape_string($conn, $parent_menu_id) . "', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
	    if ($registerFirstSubmenuMenu) {
	        $data = json_encode(array('Status' => true, 'Message' => 'Submenu has been registered successfully'));
	    } else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	
	// Add New Submenu
	function register_new_submenu($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$getPreviousSubmenuRanking = mysqli_query($conn, "SELECT subMenuRank FROM sub_menus WHERE subMenuID = '" . mysqli_real_escape_string($conn, $prev_submenu_id) . "'") or die(mysqli_error($conn));
		$prev_submenu_rank_rs = mysqli_fetch_array($getPreviousSubmenuRanking);
        $new_submenu_rank_no = $prev_submenu_rank_rs[0] + 1;
        $rank_start_no = $prev_submenu_rank_rs[0] + 1;
        $getSubmenuIddFromStartRank = mysqli_query($conn, "SELECT subMenuID FROM sub_menus WHERE subMenuRank >= $rank_start_no AND mainMenuID = '". mysqli_real_escape_string($conn, $parent_menu_id) ."' ORDER BY subMenuRank ASC") or die(mysqli_error($conn));
        if (mysqli_num_rows($getSubmenuIddFromStartRank) > 0) {
            while ($submenu_id_rs = mysqli_fetch_array($getSubmenuIddFromStartRank)) {
                $rank_start_no++;
                mysqli_query($conn, "UPDATE sub_menus SET subMenuRank = '". mysqli_real_escape_string($conn, $rank_start_no) ."' WHERE subMenuID = '". mysqli_real_escape_string($conn, $submenu_id_rs[0]) ."'") or die(mysqli_error($conn));
            }
        }
        $registerNewSubmenuMenu = mysqli_query($conn, "INSERT INTO sub_menus(subMenuText, subMenuIcon, subMenuURL, subMenuRank, mainMenuID, registeredBy, registerDate, updatedBy, updateDate) VALUES ('" . mysqli_real_escape_string($conn, $submenu_menu_name) . "', '" . mysqli_real_escape_string($conn, $submenu_menu_icon) . "', '" . mysqli_real_escape_string($conn, $submenu_menu_link) . "', '". mysqli_real_escape_string($conn, $new_submenu_rank_no) ."', '" . mysqli_real_escape_string($conn, $parent_menu_id) . "', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
	    if ($registerNewSubmenuMenu) {
	        $data = json_encode(array('Status' => true, 'Message' => 'Submenu has been registered successfully'));
	    } else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	
	// Fetch Submenu Details
	function fetch_submenu_details ($conn) {
		$returned_data = array();
		$data = array();
		extract($_POST);
		$getSubmenuDetails = mysqli_query($conn, "SELECT * FROM sub_menus WHERE subMenuID = '" . mysqli_real_escape_string($conn, $selected_submenu_id) . "'");
		if ($getSubmenuDetails) {
			if (mysqli_num_rows($getSubmenuDetails) > 0) {
				$row = mysqli_fetch_array($getSubmenuDetails);
				$returned_data[] = $row;
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Submenu Not Found"));
			}
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
		echo $data;
	}
	
	// Update Submenu Details
	function update_submenu_details($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
	    $updateMenuDetails = mysqli_query($conn, "UPDATE sub_menus SET subMenuText = '" . mysqli_real_escape_string($conn, $selected_submenu_name) . "', subMenuIcon = '" . mysqli_real_escape_string($conn, $selected_submenu_icon) . "', subMenuURL = '" . mysqli_real_escape_string($conn, $selected_submenu_link) . "', updatedBy = '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', updateDate = '". date("Y-m-d H:i") ."' WHERE subMenuID = '" . mysqli_real_escape_string($conn, $selected_submenu_id) . "'") or die(mysqli_error($conn));
	    if ($updateMenuDetails) {
	        $data = json_encode(array('Status' => true, 'Message' => 'Submenu has been updated successfully'));
	    } else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	
	// Search Menu or Submenu Live
	function search_menu_submenu_live($conn) {
		global $ereyFure;
		global $errorList;
		$data = array();
		$already_fetched_menu = array();
		extract($_POST);
		$menu_submenu_name = mysqli_real_escape_string($conn, $menu_submenu_name);
		
        if ($_SESSION['userTypeID'] == 'PS0001') {
    		    
    			$getSystemMenus = mysqli_query($conn, "SELECT * FROM main_menus WHERE mainMenuText LIKE '%". $menu_submenu_name ."%' ORDER BY mainMenuRank");
    			if ($getSystemMenus) {
    				if (mysqli_num_rows($getSystemMenus) > 0) {
    					while ($system_menus_rs = mysqli_fetch_array($getSystemMenus)) {
                            if ($system_menus_rs[1] == "Logout") {
        						?><li><a class="app-menu__item" href="<?php echo $system_menus_rs[3]; ?>" id="logoutOutSide" data-id="<?php echo $_SESSION['userName']; ?>"><i class="app-menu__icon <?php echo $system_menus_rs[2]; ?>"></i><span class="app-menu__label">Logout</a></li><?php
        					} else {
        						?><li><a class="app-menu__item" href="<?php echo $system_menus_rs[3]; ?>"><i class="app-menu__icon <?php echo $system_menus_rs[2]; ?>"></i><span class="app-menu__label"><?php echo $system_menus_rs[1]; ?></span></a></li><?php
        					}
                        }
                    } else {
                        
                        // If this is not a menu then search it from the submenus
                        $getSubMenus = mysqli_query($conn, "SELECT * FROM sub_menus WHERE subMenuText LIKE '%". $menu_submenu_name ."%' ORDER BY subMenuRank");
                        if ($getSubMenus) {
            				if (mysqli_num_rows($getSubMenus) > 0) {
            					while ($sub_menus_rs = mysqli_fetch_array($getSubMenus)) {
            					    
            					    $getSystemMenus2 = mysqli_query($conn, "SELECT * FROM main_menus WHERE mainMenuID = '". $sub_menus_rs[5] ."' ORDER BY mainMenuRank");
                        			if ($getSystemMenus2) {
                        				if (mysqli_num_rows($getSystemMenus2) > 0) {
                        				    $system_menus_rs2 = mysqli_fetch_array($getSystemMenus2);
                        				    if (!in_array($system_menus_rs2[0], $already_fetched_menu)) {
                        				        ?><li class="treeview is-expanded-live"><a class="app-menu__item" href="#" data-toggle="treeview"><i class="app-menu__icon <?php echo $system_menus_rs2[2]; ?>"></i><span class="app-menu__label"><?php echo $system_menus_rs2[1]; ?></span><i class="treeview-indicator fa fa-angle-right"></i></a>
						                            <ul class="treeview-menu">
						                                <?php
						                                
        					                                $getSubMenus2 = mysqli_query($conn, "SELECT * FROM sub_menus WHERE subMenuText LIKE '%". $menu_submenu_name ."%' AND mainMenuID = '". $system_menus_rs2[0] ."' ORDER BY subMenuRank");
                                                            if ($getSubMenus2) {
                                                				if (mysqli_num_rows($getSubMenus2) > 0) {
                                                					while ($sub_menus_rs2 = mysqli_fetch_array($getSubMenus2)) {
                                                					    if ($sub_menus_rs2[1] == "Change Password") {
                                    										?><li><a class="treeview-item" href="<?php echo $sub_menus_rs2[3]; ?>" data-id="<?php echo $_SESSION['userName']; ?>" data-toggle="modal" data-target="#changePasswordModal"><i class="icon <?php echo $sub_menus_rs2[2]; ?>"></i> <?php echo $sub_menus_rs2[1]; ?></a></li><?php
                                    									} else if ($sub_menus_rs2[1] == "Security Options") {
                                    										?><li><a class="treeview-item" href="<?php echo $sub_menus_rs2[3]; ?>" id="securitySubMenu" data-id="<?php echo $_SESSION['userIdd']; ?>" data-toggle="modal" data-target="#securitySettingsModal"><i class="icon <?php echo $sub_menus_rs2[2]; ?>"></i> <?php echo $sub_menus_rs2[1]; ?></a></li><?php
                                    									} else {
                                    										?><li><a class="treeview-item" href="<?php echo $sub_menus_rs2[3]; ?>"><i class="icon <?php echo $sub_menus_rs2[2]; ?>"></i> <?php echo $sub_menus_rs2[1]; ?></a></li><?php
                                    									}
                                                					}
                                                				}
                                                            }
                                                            
                        							    ?>
                        						    </ul>
                        					    </li><?php
                        				        $already_fetched_menu[] = $system_menus_rs2[0];
                        				    }
                        				    

                        				} else {
                        				    
                        				}
                        			} else {
                        			    
                        			}
            					}
            				} else {
            				    echo "<center><p class='text-light text-center'>Task Not Found</p></center>";
            				}
                        } else {
                            echo mysqli_error($conn);
                        }

                    }
                } else {
                    echo mysqli_error($conn);
                }
            
            } else {

                $getSystemMenus = mysqli_query($conn, "SELECT DISTINCT main_menus.mainMenuID, main_menus.mainMenuText, main_menus.mainMenuIcon, main_menus.mainMenuURL, user_main_menus.userID FROM user_main_menus JOIN main_menus ON (user_main_menus.mainMenuID = main_menus.mainMenuID AND user_main_menus.userID = '" . $_SESSION['userIdd'] . "') ORDER BY mainMenuRank");
                if ($getSystemMenus) {
                    if (mysqli_num_rows($getSystemMenus) > 0) {
                        while ($system_menus_rs = mysqli_fetch_array($getSystemMenus)) {
                            $getSubmenus = mysqli_query($conn, "SELECT DISTINCT sub_menus.subMenuID, sub_menus.subMenuText, sub_menus.subMenuIcon, sub_menus.subMenuURL, sub_menus.mainMenuID, user_sub_menus.userID FROM sub_menus JOIN user_sub_menus ON (user_sub_menus.subMenuID = sub_menus.subMenuID AND user_sub_menus.userID = '" . $_SESSION['userIdd'] . "' AND sub_menus.mainMenuID = '" . $system_menus_rs[0] . "') ORDER BY subMenuRank");
                            if ($getSubmenus) {
                                if (mysqli_num_rows($getSubmenus) > 0) {
                                    ?><li class="treeview"><a class="app-menu__item" href="#" data-toggle="treeview"><i class="app-menu__icon <?php echo $system_menus_rs[2]; ?>"></i><span class="app-menu__label"><?php echo $system_menus_rs[1]; ?></span><i class="treeview-indicator fa fa-angle-right"></i></a>
                                        <ul class="treeview-menu">
                                            <?php
                                                while ($submenu_rs = mysqli_fetch_array($getSubmenus)) {
                                            	    if ($submenu_rs[1] == "Change Password") {
                                                        ?><li><a class="treeview-item" href="<?php echo $submenu_rs[3]; ?>" data-id="<?php echo $_SESSION['userName']; ?>" data-toggle="modal" data-target="#changePasswordModal"><i class="icon <?php echo $submenu_rs[2]; ?>"></i> <?php echo $submenu_rs[1]; ?></a></li><?php
                							        } else if ($submenu_rs[1] == "Security Options") {
                                                        ?><li><a class="treeview-item" href="<?php echo $submenu_rs[3]; ?>" id="securitySubMenu" data-id="<?php echo $_SESSION['userIdd']; ?>" data-toggle="modal" data-target="#securitySettingsModal"><i class="icon <?php echo $submenu_rs[2]; ?>"></i> <?php echo $submenu_rs[1]; ?></a></li><?php
                                                    } else {
                                                        ?><li><a class="treeview-item" href="<?php echo $submenu_rs[3]; ?>"><i class="icon <?php echo $submenu_rs[2]; ?>"></i> <?php echo $submenu_rs[1]; ?></a></li><?php
                                                    }
                                                }
                                            ?>
                                        </ul>
                                    </li><?php
                                } else {
                                    if ($system_menus_rs[1] == "Logout") {
                                        ?><li><a class="app-menu__item" href="<?php echo $system_menus_rs[3]; ?>" id="logoutOutSide" data-id="<?php echo $_SESSION['userName']; ?>"><i class="app-menu__icon <?php echo $system_menus_rs[2]; ?>"></i><span class="app-menu__label">Logout</a></li><?php
                                    } else {
                                        ?><li><a class="app-menu__item" href="<?php echo $system_menus_rs[3]; ?>"><i class="app-menu__icon <?php echo $system_menus_rs[2]; ?>"></i><span class="app-menu__label"><?php echo $system_menus_rs[1]; ?></span></a></li><?php
                                    }
                                }
                            } else {
                                echo mysqli_error($conn);
                            }
                        }
                    } else {
                        echo "<center><h6 class='text-light text-center'>Menus Not Found</h6></center>";
                    }
                } else {
                    echo mysqli_error($conn);
                }
            }
	}

	// ========================== End of Manage Menus ====================================

	// ========================== Start of User Privileges ===============================
	// ----------------------- Fill username in the user privileges page -----------------
	function userNamesPrivileges($conn) {
		$user_names = array();
		$data = array();
		$result = mysqli_query($conn, "SELECT system_users.userID, system_users.Username, employees.employeeName FROM system_users JOIN employees ON (system_users.employeeID = employees.employeeID AND employees.employeeStatus = 1 AND system_users.registeredBy = '" . $_SESSION['userIdd'] . "')");
		if ($result) {
			$num_rows = mysqli_num_rows($result);
			if ($num_rows > 0) {
				while ($row = mysqli_fetch_assoc($result)) {
					$user_names[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $user_names));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "User Names Not Found"));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill active users
	function fill_active_users($conn) {
		$returned_data = array();
		$data = array();
		$getActiveUsers = mysqli_query($conn, "SELECT system_users.userID, system_users.Username, employees.employeeName, employees.employeeMobileNo FROM system_users JOIN employees ON system_users.employeeID = employees.employeeID WHERE employees.employeePosition != 'PS0001' AND employees.employeeStatus = 1");
		if ($getActiveUsers) {
			if (mysqli_num_rows($getActiveUsers) > 0) {
				while ($row = mysqli_fetch_array($getActiveUsers)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Active Users Not Found"));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Fill users for privileges
	function fill_users_for_privileges($conn) {
		$returned_data = array();
		$data = array();
		$getUsersForPrivileges = mysqli_query($conn, "SELECT system_users.userID, system_users.Username, employees.employeeName, employees.employeeMobileNo
		FROM system_users 
		JOIN employees ON system_users.employeeID = employees.employeeID 
		WHERE system_users.userID != '". $_SESSION['userIdd'] ."' AND employees.employeePosition != 'PS0001' AND employees.employeeStatus = '1'");
		if ($getUsersForPrivileges) {
			if (mysqli_num_rows($getUsersForPrivileges) > 0) {
				while ($row = mysqli_fetch_array($getUsersForPrivileges)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Users Not Found"));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fetch User Privileges
	function fetch_full_user_privileges($conn) {
		global $ereyFure;
		global $errorList;
		$data = array();
		extract($_POST);
		$dn = kuceliAsalka($dn, $ereyFure); 
		?>
		<div class="tile mt-3">
			<div class="tile-body">
				<div class="row">
					<div class="col-md-12">
						<h3 class="text-uppercase">Allowed Pages To Visit</h3>
					</div>
				</div>
				<div class="row">
					<div class="col-md-12">
						<table class="table table-striped" id="grantUserWebpagesToVisitTable">
							<?php
							    // First get the current privileges of the selected user
							    $user_system_menus_list = array();
							    $user_submenus_list = array();
								$getUserSystemMenus = mysqli_query($conn, "SELECT DISTINCT main_menus.mainMenuID, main_menus.mainMenuText, main_menus.mainMenuIcon, main_menus.mainMenuURL, user_main_menus.userID 
								FROM user_main_menus 
								JOIN main_menus ON user_main_menus.mainMenuID = main_menus.mainMenuID
								WHERE user_main_menus.userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'
								ORDER BY main_menus.mainMenuRank") or die(mysqli_error($conn));
								if ($getUserSystemMenus) {
									if (mysqli_num_rows($getUserSystemMenus) > 0) {
									    while ($user_system_menu_rs = mysqli_fetch_array($getUserSystemMenus)) {
                            				$user_system_menus_list[] = $user_system_menu_rs[0];
                            				$getUserSubmenus = mysqli_query($conn, "SELECT DISTINCT sub_menus.subMenuID, sub_menus.subMenuText, sub_menus.subMenuIcon, sub_menus.subMenuURL, sub_menus.mainMenuID, user_sub_menus.userID 
                            				FROM sub_menus 
                            				JOIN user_sub_menus ON user_sub_menus.subMenuID = sub_menus.subMenuID
                            				WHERE user_sub_menus.userID = '" . $selected_user_id . "' AND sub_menus.mainMenuID = '" . $user_system_menu_rs[0] . "'
                            				ORDER BY sub_menus.subMenuRank") or die(mysqli_error($conn));
											if ($getUserSubmenus) {
												if (mysqli_num_rows($getUserSubmenus) > 0) {
												     while ($user_submenu_rs = mysqli_fetch_array($getUserSubmenus)) {
												        $user_submenus_list[] = $user_submenu_rs[0];
												     }
												}
											}
                            			}
									}
								}

							    // If the current user is super admin, then fetch all the privileges
							    if ($_SESSION['userTypeID'] == 'PS0001') {
							        
							        $getSystemMenus = mysqli_query($conn, "SELECT * FROM main_menus ORDER BY mainMenuRank");
                        			if ($getSystemMenus) {
                        				if (mysqli_num_rows($getSystemMenus) > 0) {
                        					while ($system_menus_rs = mysqli_fetch_array($getSystemMenus)) { ?>
                        					    <tr class="user_system_menu_item" id="user_system_menu_item">
    												<td style="padding: 10px 0px 10px 10px;">
    													<?php 
    													    if (in_array($system_menus_rs[0], $user_system_menus_list)) {
    													        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSystemMenuPrivilege" id="cbxEnableDisableUserSystemMenuPrivilege" data-id="<?php echo $system_menus_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked /><?php
    													    } else {
    													        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSystemMenuPrivilege" id="cbxEnableDisableUserSystemMenuPrivilege" data-id="<?php echo $system_menus_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>"><?php
    													    } 
    												    ?>
    													<i class="<?php echo $system_menus_rs[2]; ?>"></i> &nbsp;&nbsp;<a href="<?php echo $system_menus_rs[3]; ?>"><b><?php echo $system_menus_rs[1]; ?></b></a>
    												</td>
    											</tr>
    											<tr class="user_submenu_group" id="user_submenu_group">
    												<td class="user_submenu_single_item" id="user_submenu_single_item">
    													<div class="row">
    														<?php
    														    $getSubmenus = mysqli_query($conn, "SELECT * FROM sub_menus WHERE mainMenuID = '" . $system_menus_rs[0] . "' ORDER BY subMenuRank");
                                        						if ($getSubmenus) {
                                        							if (mysqli_num_rows($getSubmenus) > 0) {
                                        							    while ($submenu_rs = mysqli_fetch_array($getSubmenus)) {
                                        							        ?><div class="col-md-4" style="padding: 10px 10px 10px 75px;">
    																		    <?php 
    													                            if (in_array($submenu_rs[0], $user_submenus_list)) {
    																			        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSubmenuenuPrivilege" id="cbxEnableDisableUserSubmenuenuPrivilege" data-id="<?php echo $submenu_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked /><?php
    																			    } else {
    																			        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSubmenuenuPrivilege" id="cbxEnableDisableUserSubmenuenuPrivilege" data-id="<?php echo $submenu_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>"><?php
    																			    } 
    																	        ?>
    																			<i class="<?php echo $submenu_rs[2]; ?>"></i> &nbsp;&nbsp;<a href="<?php echo $submenu_rs[3]; ?>"><?php echo $submenu_rs[1]; ?></a>
    																		</div><?php
                                        							    }
                                            					    }
                                                                } else {
                                                                    echo mysqli_error($conn);
                                                                }
                                                            ?>
                                                        </div>
                                                    </td>
                                                </tr><?php
                                            }
                                        } else {
                                            echo "<center><h6 class='text-light text-center'>Menus Not Found</h6></center>";
                                        }
                                    } else {
                                        echo mysqli_error($conn);
                                    }
                                    
							    } else {
							        
							        $getSystemMenus = mysqli_query($conn, "SELECT main_menus.mainMenuID, main_menus.mainMenuText, main_menus.mainMenuIcon, main_menus.mainMenuURL, main_menus.mainMenuRank, main_menus.registeredBy, main_menus.registerDate, main_menus.updatedBy, main_menus.updateDate
                                    FROM user_main_menus 
                                    JOIN main_menus ON user_main_menus.mainMenuID = main_menus.mainMenuID 
                                    WHERE user_main_menus.userID = '". $_SESSION['userIdd'] ."'
                                    ORDER BY main_menus.mainMenuRank ASC");
                        			if ($getSystemMenus) {
                        				if (mysqli_num_rows($getSystemMenus) > 0) {
                        					while ($system_menus_rs = mysqli_fetch_array($getSystemMenus)) { ?>
                        					    <tr class="user_system_menu_item" id="user_system_menu_item">
    												<td style="padding: 10px 0px 10px 10px;">
    													<?php 
    													    if (in_array($system_menus_rs[0], $user_system_menus_list)) {
    													        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSystemMenuPrivilege" id="cbxEnableDisableUserSystemMenuPrivilege" data-id="<?php echo $system_menus_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked /><?php
    													    } else {
    													        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSystemMenuPrivilege" id="cbxEnableDisableUserSystemMenuPrivilege" data-id="<?php echo $system_menus_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>"><?php
    													    } 
    												    ?>
    													<i class="<?php echo $system_menus_rs[2]; ?>"></i> &nbsp;&nbsp;<a href="<?php echo $system_menus_rs[3]; ?>"><b><?php echo $system_menus_rs[1]; ?></b></a>
    												</td>
    											</tr>
    											<tr class="user_submenu_group" id="user_submenu_group">
    												<td class="user_submenu_single_item" id="user_submenu_single_item">
    													<div class="row">
    														<?php
    														    $getSubmenus = mysqli_query($conn, "SELECT sub_menus.subMenuID, sub_menus.subMenuText, sub_menus.subMenuIcon, sub_menus.subMenuURL, sub_menus.subMenuRank, sub_menus.mainMenuID, sub_menus.registeredBy, sub_menus.registerDate, sub_menus.updatedBy, sub_menus.updateDate
                                                                FROM user_sub_menus
                                                                JOIN sub_menus
                                                                ON user_sub_menus.subMenuID = sub_menus.subMenuID
                                                                WHERE sub_menus.mainMenuID = '" . $system_menus_rs[0] . "' AND user_sub_menus.userID = '". $_SESSION['userIdd'] ."'
                                                                ORDER BY sub_menus.subMenuRank ASC");
                                        						if ($getSubmenus) {
                                        							if (mysqli_num_rows($getSubmenus) > 0) {
                                        							    while ($submenu_rs = mysqli_fetch_array($getSubmenus)) {
                                        							        ?><div class="col-md-4" style="padding: 10px 10px 10px 75px;">
    																		    <?php 
    													                            if (in_array($submenu_rs[0], $user_submenus_list)) {
    																			        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSubmenuenuPrivilege" id="cbxEnableDisableUserSubmenuenuPrivilege" data-id="<?php echo $submenu_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked /><?php
    																			    } else {
    																			        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUserSubmenuenuPrivilege" id="cbxEnableDisableUserSubmenuenuPrivilege" data-id="<?php echo $submenu_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>"><?php
    																			    } 
    																	        ?>
    																			<i class="<?php echo $submenu_rs[2]; ?>"></i> &nbsp;&nbsp;<a href="<?php echo $submenu_rs[3]; ?>"><?php echo $submenu_rs[1]; ?></a>
    																		</div><?php
                                        							    }
                                            					    }
                                                                } else {
                                                                    echo mysqli_error($conn);
                                                                }
                                                            ?>
                                                        </div>
                                                    </td>
                                                </tr><?php
                                            }
                                        } else {
                                            echo "<center><h6 class='text-light text-center'>Menus Not Found</h6></center>";
                                        }
                                    } else {
                                        echo mysqli_error($conn);
                                    }
							    }
							   ?>
						</table>
					</div>
				</div>

				<div class="row mb-2">
					<div class="col-md-12">
						<h3 class="text-uppercase">Allowed Roles To Perform</h3>
					</div>
				</div>

				<div class="row">
					<div class="col-md-12">
						<?php
						    $user_role_names = array();
						    //Get the roles allwed for this user
							$getUserRoles = mysqli_query($conn, "SELECT roleName FROM user_role_privileges WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'");
							if ($getUserRoles) {
								if (mysqli_num_rows($getUserRoles) > 0) {
								     while ($user_roles_rs = mysqli_fetch_array($getUserRoles)) {
								        $user_role_names[] = $user_roles_rs[0];
								     }
								}
							}
							
						    // If the current user is super admin, then fetch all the role privileges
						    if ($_SESSION['userTypeID'] == 'PS0001') {
						        
						        ?><table class="table table-bordered table-hover" id="grantUserRolesToPerformTable"><?php
							        $get_db_tables = mysqli_query($conn, "SELECT Table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" . mysqli_real_escape_string($conn, $dn) . "'") or die(mysqli_error());
        							if ($get_db_tables) {
        								if (mysqli_num_rows($get_db_tables) > 0) {
        								     ?><thead>
        										<tr class="text-center bg-primary text-light">
        											<th class="align-middle pl-5 text-left" width="15%"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableFullRolesOnce" id="cbxEnableDisableFullRolesOnce" role-userid="<?php echo $selected_user_id; ?>" checked /> Check All</th>
        											<th class="align-middle text-left" width="40%">Role Name</th>
        											<th class="align-middle text-center" colspan="3"> Actions</th>
        										</tr>
        									</thead>
        									<tbody class="insertUpdateDeleteRoles">
        									    
        									    <?php
            									    $notAllowedTables = array("main_menus", "sub_menus", "user_main_menus", "user_sub_menus", "user_role_privileges", "user_logins", "payment_gateways", "system_configurations", "charge_pay_salaries", "check_edahab_payments", "tenant_statement2", "tenant_statement", "tenant_profile", "tenant_menus", "request_messages", "rental_property_statuses", "rental_property_payment_types", "maintenance_requests", "tenant_logins", "tenant_privileges", "investor_logins","landlord_logins", "floors", "charge_types");
								                    while ($role_rs = mysqli_fetch_array($get_db_tables)) {
                                                        if (in_array($role_rs[0], $notAllowedTables)) {
                                                            continue;
                                                        } else {
                                                            if (in_array($role_rs[0], $user_role_names)) {
                									            $getRoleDetails = mysqli_query($conn, "SELECT * FROM user_role_privileges WHERE roleName = '". mysqli_real_escape_string($conn, $role_rs[0]) ."' AND userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'") or die(mysqli_error($conn));
                    									        $user_role_info_rs = mysqli_fetch_array($getRoleDetails);
                    									        ?><tr class="singleRoleFullDetails" role-name="<?php echo $user_role_info_rs[1]; ?>">
                									                <td class="align-middle pl-5 text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableSingleRoleFully" id="cbxEnableDisableSingleRoleFully" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /></td>
                    												<td class="align-middle text-left"><?php echo ucwords(str_replace("_", " ", $user_role_info_rs[2])); ?><input type="hidden" name="txtUserRoleName" id="txtUserRoleName" value="<?php echo $user_role_info_rs[2]; ?>" /></td>
                    									            <td class="align-middle text-left">
                    													<?php 
                    													    if ($user_role_info_rs[3] == 1) { 
                    													        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableInsertRole" id="cbxEnableDisableInsertRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /> <span class="text-success"> <i class="fa fa-save fa-lg pl-1"></i> Register</span><?php
                        													} else if ($user_role_info_rs[3] == 0) { 
                        													    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableInsertRole" id="cbxEnableDisableInsertRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" /> <span class="text-success"> <i class="fa fa-save fa-lg pl-1"></i> Register</span><?php
                    													    } 
                    												    ?>
                    												</td>
                    												<td class="align-middle text-left">
                    													<?php 
                    													    if ($user_role_info_rs[4] == 1) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUpdateRole" id="cbxEnableDisableUpdateRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /> <span class="text-primary"><i class="fa fa-pencil fa-lg pl-1"></i> Edit</span><?php
                    													    } else if ($user_role_info_rs[4] == 0) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUpdateRole" id="cbxEnableDisableUpdateRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" /> <span class="text-primary"><i class="fa fa-pencil fa-lg pl-1"></i> Edit</span><?php
                    													    } 
                    												    ?>
                    												</td>
                    												<td class="align-middle text-left">
                    													<?php 
                    													    if ($user_role_info_rs[5] == 1) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableDeleteRole" id="cbxEnableDisableDeleteRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /> <span class="text-danger"><i class="fa fa-trash fa-lg pl-1"></i> Delete</span><?php
                    													    } else if ($user_role_info_rs[5] == 0) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableDeleteRole" id="cbxEnableDisableDeleteRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" /> <span class="text-danger"><i class="fa fa-trash fa-lg pl-1"></i> Delete</span><?php
                    												        } 
                    												    ?>
                    												</td>
                    									        </tr><?php
                    									    } else {
            										            //  echo "<p class='text-danger'>" .$x ."- ". $role_rs[0]. " not found. INSERT => UK ---- UPDATE => UK  ---- DELETE => UK</p>";
                    									        ?><tr class="singleRoleFullDetails" role-name="<?php echo $role_rs[0]; ?>">
                									                <td class="align-middle pl-5 text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableSingleRoleFully" id="cbxEnableDisableSingleRoleFully" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /></td>
                    												<td class="align-middle text-left"><?php echo ucwords(str_replace("_", " ", $role_rs[0])); ?><input type="hidden" name="txtUserRoleName" id="txtUserRoleName" value="<?php echo $role_rs[0]; ?>" /></td>
                    									            <td class="align-middle text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableInsertRole" id="cbxEnableDisableInsertRole" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /> <span class="text-success"> <i class="fa fa-save fa-lg pl-1"></i> Register</span></td>
                    												<td class="align-middle text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUpdateRole" id="cbxEnableDisableUpdateRole" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /> <span class="text-primary"><i class="fa fa-pencil fa-lg pl-1"></i> Edit</span></td>
                    												<td class="align-middle text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableDeleteRole" id="cbxEnableDisableDeleteRole" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /> <span class="text-danger"><i class="fa fa-trash fa-lg pl-1"></i> Delete</span></td>
                    									        </tr><?php
                    									    }
                                                        }
								                    
                								    }
                    					        ?>
                    					   </tbody><?php
    								    } else {
    								        echo "Roles Not Found";
    								    }
    							    } else {
    							        echo mysqli_error($conn);
    							    }
					            ?></table><?php

    					    } else {
    					        
    					        ?><table class="table table-bordered table-hover" id="grantUserRolesToPerformTable"><?php
							        $get_db_tables = mysqli_query($conn, "SELECT user_role_privileges.roleName FROM user_role_privileges WHERE user_role_privileges.userID = '". $_SESSION['userIdd'] ."'") or die(mysqli_error());
        							if ($get_db_tables) {
        								if (mysqli_num_rows($get_db_tables) > 0) {
        								     ?><thead>
        										<tr class="text-center bg-primary text-light">
        											<th class="align-middle pl-5 text-left" width="15%"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableFullRolesOnce" id="cbxEnableDisableFullRolesOnce" role-userid="<?php echo $selected_user_id; ?>" checked /> Check All</th>
        											<th class="align-middle text-left" width="40%">Role Name</th>
        											<th class="align-middle text-center" colspan="3"> Actions</th>
        										</tr>
        									</thead>
        									<tbody class="insertUpdateDeleteRoles">
        									    
        									    <?php
            									    $notAllowedTables = array("main_menus", "sub_menus", "user_main_menus", "user_sub_menus", "user_role_privileges", "user_logins", "payment_gateways", "system_configurations", "charge_pay_salaries", "check_edahab_payments", "tenant_statement2", "tenant_statement", "tenant_profile", "tenant_menus", "request_messages", "rental_property_statuses", "rental_property_payment_types", "maintenance_requests", "tenant_logins", "tenant_privileges", "investor_logins","landlord_logins", "floors", "charge_types");
								                    while ($role_rs = mysqli_fetch_array($get_db_tables)) {
                                                        if (in_array($role_rs[0], $notAllowedTables)) {
                                                            continue;
                                                        } else {
                                                            if (in_array($role_rs[0], $user_role_names)) {
                									            $getRoleDetails = mysqli_query($conn, "SELECT * FROM user_role_privileges WHERE roleName = '". mysqli_real_escape_string($conn, $role_rs[0]) ."' AND userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'") or die(mysqli_error($conn));
                    									        $user_role_info_rs = mysqli_fetch_array($getRoleDetails);
                    									        ?><tr class="singleRoleFullDetails" role-name="<?php echo $user_role_info_rs[1]; ?>">
                									                <td class="align-middle pl-5 text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableSingleRoleFully" id="cbxEnableDisableSingleRoleFully" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /></td>
                    												<td class="align-middle text-left"><?php echo ucwords(str_replace("_", " ", $user_role_info_rs[2])); ?><input type="hidden" name="txtUserRoleName" id="txtUserRoleName" value="<?php echo $user_role_info_rs[2]; ?>" /></td>
                    									            <td class="align-middle text-left">
                    													<?php 
                    													    if ($user_role_info_rs[3] == 1) { 
                    													        ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableInsertRole" id="cbxEnableDisableInsertRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /> <span class="text-success"> <i class="fa fa-save fa-lg pl-1"></i> Register</span><?php
                        													} else if ($user_role_info_rs[3] == 0) { 
                        													    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableInsertRole" id="cbxEnableDisableInsertRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" /> <span class="text-success"> <i class="fa fa-save fa-lg pl-1"></i> Register</span><?php
                    													    } 
                    												    ?>
                    												</td>
                    												<td class="align-middle text-left">
                    													<?php 
                    													    if ($user_role_info_rs[4] == 1) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUpdateRole" id="cbxEnableDisableUpdateRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /> <span class="text-primary"><i class="fa fa-pencil fa-lg pl-1"></i> Edit</span><?php
                    													    } else if ($user_role_info_rs[4] == 0) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUpdateRole" id="cbxEnableDisableUpdateRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" /> <span class="text-primary"><i class="fa fa-pencil fa-lg pl-1"></i> Edit</span><?php
                    													    } 
                    												    ?>
                    												</td>
                    												<td class="align-middle text-left">
                    													<?php 
                    													    if ($user_role_info_rs[5] == 1) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableDeleteRole" id="cbxEnableDisableDeleteRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" checked /> <span class="text-danger"><i class="fa fa-trash fa-lg pl-1"></i> Delete</span><?php
                    													    } else if ($user_role_info_rs[5] == 0) {
                    														    ?><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableDeleteRole" id="cbxEnableDisableDeleteRole" role-userid="<?php echo $user_role_info_rs[1]; ?>" role-name="<?php echo $user_role_info_rs[2]; ?>" /> <span class="text-danger"><i class="fa fa-trash fa-lg pl-1"></i> Delete</span><?php
                    												        } 
                    												    ?>
                    												</td>
                    									        </tr><?php
                    									    } else {
            										            //  echo "<p class='text-danger'>" .$x ."- ". $role_rs[0]. " not found. INSERT => UK ---- UPDATE => UK  ---- DELETE => UK</p>";
                    									        ?><tr class="singleRoleFullDetails" role-name="<?php echo $role_rs[0]; ?>">
                									                <td class="align-middle pl-5 text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableSingleRoleFully" id="cbxEnableDisableSingleRoleFully" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /></td>
                    												<td class="align-middle text-left"><?php echo ucwords(str_replace("_", " ", $role_rs[0])); ?><input type="hidden" name="txtUserRoleName" id="txtUserRoleName" value="<?php echo $role_rs[0]; ?>" /></td>
                    									            <td class="align-middle text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableInsertRole" id="cbxEnableDisableInsertRole" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /> <span class="text-success"> <i class="fa fa-save fa-lg pl-1"></i> Register</span></td>
                    												<td class="align-middle text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableUpdateRole" id="cbxEnableDisableUpdateRole" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /> <span class="text-primary"><i class="fa fa-pencil fa-lg pl-1"></i> Edit</span></td>
                    												<td class="align-middle text-left"><input type="checkbox" class="form-control" style="height: 17px; width: 17px; display: inline;" name="cbxEnableDisableDeleteRole" id="cbxEnableDisableDeleteRole" role-userid="<?php echo $selected_user_id; ?>" role-name="<?php echo $role_rs[0]; ?>" /> <span class="text-danger"><i class="fa fa-trash fa-lg pl-1"></i> Delete</span></td>
                    									        </tr><?php
                    									    }
                                                        }
								                    
                								    }
                    					        ?>
                    					   </tbody><?php
    								    } else {
    								        echo "Roles Not Found";
    								    }
    							    } else {
    							        echo mysqli_error($conn);
    							    }
					            ?></table><?php
    					        
    					    }
    				    ?>
    				</div>
    			</div>
    	    </div>
	    </div><?php
	}

	// Enable User System Menu Privilege
	function enable_user_system_menu_privilege($conn) {
		$data = array();
		extract($_POST);
		$enableUserSystemMenu = mysqli_query($conn, "INSERT INTO user_main_menus(userID, mainMenuID) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_menu_id) . "')");
		if ($enableUserSystemMenu) {
		    foreach ($user_submenus_list as $k=>$submenu) {
		        mysqli_query($conn, "INSERT INTO user_sub_menus(userID, subMenuID) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $submenu) . "')") or die(mysqli_error($conn));
			} 
			$data = json_encode(array('Status' => true, 'Message' => 'System menu is set to <b>allowed</b> mode'));
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Disable User System Menu Privilege
	function disable_user_system_menu_privilege($conn) {
		$data = array();
		extract($_POST);
		$disableUserSystemMenu = mysqli_query($conn, "DELETE FROM user_main_menus WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND mainMenuID = '" . mysqli_real_escape_string($conn, $selected_menu_id) . "'");
		if ($disableUserSystemMenu) {
		    foreach ($user_submenus_list as $k=>$submenu) {
		        mysqli_query($conn, "DELETE FROM user_sub_menus WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND subMenuID = '" . mysqli_real_escape_string($conn, $submenu) . "'") or die(mysqli_error($conn));
			}
			$data = json_encode(array('Status' => true, 'Message' => 'System menu is set to <b>not allowed</b> mode'));
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Enable User Submenu Privilege
	function enable_user_submenu_privilege($conn) {
		$data = array();
		extract($_POST);
		if (mysqli_real_escape_string($conn, $selected_menu_id) == 0) {
		    $enableUserSystemMenu = mysqli_query($conn, "INSERT INTO user_sub_menus(userID, subMenuID) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_submenu_id) . "')");
		    if ($enableUserSystemMenu) {
    			$data = json_encode(array('Status' => true, 'Message' => 'Submenu is set to <b>allowed</b> mode'));
    		} else {
    			$errorMsg = mysqli_error($conn);
    			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    		}
		} else {
		    $enableUserSystemMenu = mysqli_query($conn, "INSERT INTO user_main_menus(userID, mainMenuID) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_menu_id) . "')");
		    if ($enableUserSystemMenu) {
		        mysqli_query($conn, "INSERT INTO user_sub_menus(userID, subMenuID) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_submenu_id) . "')");
		        $data = json_encode(array('Status' => true, 'Message' => 'Submenu is set to <b>allowed</b> mode'));
    		} else {
    			$errorMsg = mysqli_error($conn);
    			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    		}
		}
		echo $data;
	}
	
	// Disable User Submenu Privilege
	function disable_user_submenu_privilege($conn) {
		$data = array();
		extract($_POST);
		$enableUserSystemMenu = mysqli_query($conn, "DELETE FROM user_sub_menus WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND subMenuID = '" . mysqli_real_escape_string($conn, $selected_submenu_id) . "'");
		if ($enableUserSystemMenu) {
			$data = json_encode(array('Status' => true, 'Message' => 'Submenu is set to <b>not allowed</b> mode'));
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Enable All User Role Privileges Once
	function enable_user_role_privileges_once($conn) {
		$data = array();
		extract($_POST);
	    foreach ($selected_user_roles_list as $key => $user_role) {
	        mysqli_query($conn, "INSERT INTO user_role_privileges(userID, roleName, insertRole, updateRole, deleteRole) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $user_role) . "', 1, 1, 1)") or die(mysqli_error($conn));
		} 
		$data = json_encode(array('Status' => true, 'Message' => 'All user roles are set to <b>allowed</b> mode'));
		echo $data;
	}
	
	// Disable All User Role Privileges Once
	function disable_user_role_privileges_once($conn) {
		$data = array();
		extract($_POST);
	    foreach ($selected_user_roles_list as $key => $user_role) {
	        mysqli_query($conn, "DELETE FROM user_role_privileges WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $user_role) . "'") or die(mysqli_error($conn));
		} 
		$data = json_encode(array('Status' => true, 'Message' => 'All user roles are set to <b>not allowed</b> mode'));
		echo $data;
	}
	
	// Enable Single User Role Fully
	function enable_single_user_role_fully($conn) {
		$data = array();
		extract($_POST);
	    $enableSingleUserRoleFully = mysqli_query($conn, "INSERT INTO user_role_privileges(userID, roleName, insertRole, updateRole, deleteRole) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "', 1, 1, 1)") or die(mysqli_error($conn));
	    if ($enableSingleUserRoleFully) {
    		$data = json_encode(array('Status' => true, 'Message' => 'Role has been set to <b>allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}
	
    // Disable Single User Role Fully
	function disable_single_user_role_fully($conn) {
		$data = array();
		extract($_POST);
	    $disableSingleUserRoleFully = mysqli_query($conn, "DELETE FROM user_role_privileges WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	    if ($disableSingleUserRoleFully) {
    		$data = json_encode(array('Status' => true, 'Message' => 'Role has been set to <b>not allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}
	
	// Enable Single User Insert Role Privilege
	function enable_single_insert_role($conn) {
		$data = array();
		extract($_POST);
	    $enableSingleUserInsertRole = mysqli_query($conn, "SELECT * FROM user_role_privileges WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	    if ($enableSingleUserInsertRole) {
	        if (mysqli_num_rows($enableSingleUserInsertRole) > 0) {
	            mysqli_query($conn, "UPDATE user_role_privileges SET insertRole = '1' WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	        } else {
	            mysqli_query($conn, "INSERT INTO user_role_privileges(userID, roleName, insertRole, updateRole, deleteRole) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "', 1, 0, 0)") or die(mysqli_error($conn));
	        }
    		$data = json_encode(array('Status' => true, 'Message' => 'Register role has been set to <b>allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}
	
	// Disable Single User Insert Role Privilege
	function disable_single_insert_role($conn) {
		$data = array();
		extract($_POST);
		$disableSingleUserInsertRole = mysqli_query($conn, "UPDATE user_role_privileges SET insertRole = '0' WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	    if ($disableSingleUserInsertRole) {
    		$data = json_encode(array('Status' => true, 'Message' => 'Register role has been set to <b>not allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}

	// Enable Single User Update Role Privilege
	function enable_single_update_role($conn) {
		$data = array();
		extract($_POST);
	    $enableSingleUserUpdateRole = mysqli_query($conn, "SELECT * FROM user_role_privileges WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	    if ($enableSingleUserUpdateRole) {
	        if (mysqli_num_rows($enableSingleUserUpdateRole) > 0) {
	            mysqli_query($conn, "UPDATE user_role_privileges SET updateRole = '1' WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	        } else {
	            mysqli_query($conn, "INSERT INTO user_role_privileges(userID, roleName, insertRole, updateRole, deleteRole) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "', 0, 1, 0)") or die(mysqli_error($conn));
	        }
    		$data = json_encode(array('Status' => true, 'Message' => 'Update role has been set to <b>allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}
	
	// Disable Single User Update Role Privilege
	function disable_single_update_role($conn) {
		$data = array();
		extract($_POST);
		$disableSingleUserUpdateRole = mysqli_query($conn, "UPDATE user_role_privileges SET updateRole = '0' WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	    if ($disableSingleUserUpdateRole) {
    		$data = json_encode(array('Status' => true, 'Message' => 'Update role has been set to <b>not allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}
	
	// Enable Single User Delete Role Privilege
	function enable_single_delete_role($conn) {
		$data = array();
		extract($_POST);
	    $enableSingleUserDeleteRole = mysqli_query($conn, "SELECT * FROM user_role_privileges WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	    if ($enableSingleUserDeleteRole) {
	        if (mysqli_num_rows($enableSingleUserDeleteRole) > 0) {
	            mysqli_query($conn, "UPDATE user_role_privileges SET deleteRole = '1' WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	        } else {
	            mysqli_query($conn, "INSERT INTO user_role_privileges(userID, roleName, insertRole, updateRole, deleteRole) VALUES ('" . mysqli_real_escape_string($conn, $selected_user_id) . "', '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "', 0, 0, 1)") or die(mysqli_error($conn));
	        }
    		$data = json_encode(array('Status' => true, 'Message' => 'Delete role has been set to <b>allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}
	
	// Disable Single User Delete Role Privilege
	function disable_single_delete_role($conn) {
		$data = array();
		extract($_POST);
		$disableSingleUserUpdateRole = mysqli_query($conn, "UPDATE user_role_privileges SET deleteRole = '0' WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "' AND roleName = '" . mysqli_real_escape_string($conn, $selected_user_role_name) . "'") or die(mysqli_error($conn));
	    if ($disableSingleUserUpdateRole) {
    		$data = json_encode(array('Status' => true, 'Message' => 'Delete role has been set to <b>not allowed</b> mode'));
    	} else {
    		$errorMsg = mysqli_error($conn);
    		$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    	}
		echo $data;
	}

	// ========================== End of User Privileges ===============================

	// ========================== Direct Login Process =====================================================
	function system_login_process($conn) {
		global $ereyFure;
		global $errorList;
		$data = array();
		extract($_POST);

		//--------------------- Direct login process starts here -----------------------------
        $checkUserName = mysqli_query($conn, "SELECT system_users.userID, system_users.Username, system_users.Passcode, system_users.twoStepVerification, employees.employeeName, departments.departmentName, employees.employeePosition, employee_positions.positionName, employees.employeeMobileNo, employees.employeeEmailAddress, employees.employeePhoto, employees.employeeStatus 
		FROM system_users 
		JOIN employees ON employees.employeeID = system_users.employeeID 
        JOIN departments ON employees.employeeDepartment = departments.departmentID
        JOIN employee_positions ON employees.employeePosition = employee_positions.positionID		
        WHERE system_users.Username = '" . mysqli_real_escape_string($conn, $user_name) . "'");
		if ($checkUserName) {
			if (mysqli_num_rows($checkUserName) > 0) {
				$userDetails = mysqli_fetch_array($checkUserName);
				$emp_Status = $userDetails[10];
				if ($emp_Status == "0") {
					$errorList[] = "Sorry, this user has been bloacked, please contact the administrator";
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				} else {
					$entered_user_password = $pass_word;
					$user_stored_enc_pass = $userDetails[2];
					$stored_dec_password = kuceliAsalka($user_stored_enc_pass, $ereyFure);
					if ($entered_user_password === $stored_dec_password) {
						//Check Two-Step Verification process
						if ($userDetails[3] == 1) {
							$_SESSION["tempUserID"] = $userDetails[0];
							$_SESSION["tempFullName"] = $userDetails[4];
							$_SESSION["tempUserPhone"] = $userDetails[8];
							$_SESSION["tempUserEmail"] = $userDetails[9];
							//Generate the Activiation code and set it to the logging admin/user, and make the status Confirmation Code Sent
							$verification_code = "M-" . generateRandomString(6);
							$update_verification_code = mysqli_query($conn, "UPDATE system_users SET verificationCode = '" . $verification_code . "' WHERE userID = '" . mysqli_real_escape_string($conn, $_SESSION["tempUserID"]) . "'") or die(mysqli_error($conn));
							if ($update_verification_code) {
							    
							    $messageBody = "Dear " . $_SESSION["tempFullName"] . ", Your verification code to login into Lighthouse system is: ". $verification_code;
    							$data = array(
    								"refid" => "0", "mobile" => $_SESSION["tempUserPhone"], "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
    							);
    							$data1 = json_encode($data);
    							$username = 'lighthouse1';
    							$password = 'Sja3wj5EhSr4tggVLJmcCw==';
					
    							$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
    							$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
    							curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    							curl_setopt($ch, CURLOPT_HEADER, 1);
    							curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    							curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
    							curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    							$return = curl_exec($ch);
    							// print_r($return);
    							$return = explode(':', $return);
    					
    							// for ($i=0; $i < count($return) ; $i++) {
    							//     echo $i. ':' . $return[$i];
    							// }
    							$stat = explode('"', $return[17]);
    							$msg1 = explode(',', $return[20]);
    							$msg = explode('"', $msg1[0]);
    							// print_r($msg[1]);
							
    							if ($stat[1] != 'Failed.') {
    								$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $_SESSION["tempUserID"] . "', '" . $_SESSION["tempUserID"] . "', 'Login Verification Code', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $_SESSION["tempUserPhone"] ."', '" . mysqli_real_escape_string($conn, $_SESSION['tempUserID']) . "', '". date("Y-m-d H:i:s") ."')");
    								if ($saveSms) {
    									//$success_arr = array('message' => $msg[1]);
    									
    								    $messageBody = "<h2 class='text-info'>Dear " . $_SESSION["tempFullName"] . ",</h2><p style='font: 17px Arial; line-height: 1.7'>Your verification code to login into Lighthouse system <strong><a href='lighthousecore.com/admin_panel'>Lighthouse System</a></strong> is: <span class='text-info' style='font-size: 20px;'><strong>" . $verification_code . "</strong></span> <br /><br />Best regards,<br><strong>Lighthouse Team</strong><br /><br />";
        								$mail = new PHPMailer(true);							                                    //Create instance of PHPMailer
        								$mail->isSMTP();									                                        //Set mailer to use smtp
        								//$mail->SMTPDebug = 2;
        								$mail->Host = "mail.lighthousecore.com";						                            //Define smtp host
        								//$mail->SMTPAuth = true;								                                    //Enable smtp authentication
        								//$mail->SMTPSecure = "ssl";							                                    //Set smtp encryption type (ssl/tls)
        								$mail->Port = "25";								                                            //Port to connect smtp
        								$mail->Username = "no-reply@lighthousecore.com";	    	                                //Set gmail username
        								$mail->Password = "Lighthouse9414";						                                    //Set gmail password
        								$mail->Subject = "Login Verification Code";	                                                //Email subject
        								$mail->setFrom("no-reply@lighthousecore.com", "Lighthouse Construction & Real Estates");    //Set sender email
        								$mail->isHTML(true);									                                    //Enable HTML
        								//$mail->addAttachment('img/attachment.png');			                                    //Attachment
        								//Email body
        								$mail->Body = $messageBody;
        								$mail->addAddress($_SESSION["tempUserEmail"]);				                                //Add recipient
        
        								//Finally send email
        								if ($mail->send()) {
        									//echo $mail->send();
        									$data = json_encode(array('Status' => true, 'Message' => 'enabled2StepVerifying'));
        								} else {
        									//echo "Message could not be sent. Mailer Error: ". $mail->ErrorInfo;
        									$errorMsg = $mail->ErrorInfo;
        									$errorList[] = $errorMsg;
        									$data = json_encode(array('Status' => false, 'Message' => $errorList));
        								}
        								$mail->smtpClose();										                                    //Closing smtp connection
    
    								} else {
    									$errorMsg = mysqli_error($conn);
    									$errorList[] = $errorMsg;
    									$data = json_encode(array('Status' => false, 'Message' => $errorList));
    								}
    							} else {
    								$errorList[] = $msg[1];
    								$data = json_encode(array('Status' => false, 'Message' => $errorList));
    							}

							} else {
        						$errorList[] = mysqli_error($conn);
        						$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
							
						} else {

							$_SESSION["lastLoginTimeStamp"] = time();
							
							$loginDate = date("Y-m-d H:i:s");
							$_SESSION["userIdd"] = $userDetails[0];
							$_SESSION["userName"] = $userDetails[1];
							$_SESSION["fullName"] = $userDetails[4];
							$_SESSION["departmentName"] = $userDetails[5];
							$_SESSION["userTypeID"] = $userDetails[6];
							$_SESSION["userType"] = $userDetails[7];
							$_SESSION["userPhone"] = $userDetails[8];
							$_SESSION["userEmail"] = $userDetails[9];
							$_SESSION["userPhoto"] = $userDetails[10];
							unset($_SESSION['tempUserID']);
							unset($_SESSION['tempFullName']);
							unset($_SESSION['tempUserPhone']);
							unset($_SESSION['tempUserEmail']);
							mysqli_query($conn, "INSERT INTO `user_logins`(`userID`, `loginDateTime`) VALUES ('" . $_SESSION["userIdd"] . "', '" . $loginDate . "')") or die(mysqli_error($conn));
							mysqli_query($conn, "UPDATE system_users SET loginStatus = '1' WHERE userID = '" . $_SESSION["userIdd"] . "'") or die(mysqli_error($conn));

                		    $getCurrentUser = mysqli_query($conn, "SELECT visitedPageURL FROM last_visited_page WHERE userID = '". $_SESSION['userIdd'] ."'") or die(mysqli_error($conn));
                		    if ($getCurrentUser) {
                		        if (mysqli_num_rows($getCurrentUser) > 0) {
                		            $visited_url_rs = mysqli_fetch_array($getCurrentUser);
                		            $data = json_encode(array('Status' => true, 'Message' => $visited_url_rs[0]));
                		        } else {
							        $data = json_encode(array('Status' => true, 'Message' => 'dashboard'));
                		        }
                		    }
						}

					} else {
						$errorMsg = "<strong>Admin</strong>: Sorry, password is incorrect. Try again!";;
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}

			} else {

			    // Investor Login Section
			    $checkInvestorLogin = mysqli_query($conn, "SELECT investorID, investorName, investorMobile, investorEmail, investorPasscode, investorPhoto, investorStatus FROM investors WHERE investorMobile = '". $user_name ."' OR investorEmail = '". $user_name ."' OR investorID = '". $user_name ."'");
		        if ($checkInvestorLogin) {
                    if (mysqli_num_rows($checkInvestorLogin) > 0) {
        				$investorDetails = mysqli_fetch_array($checkInvestorLogin);
        				$invstr_Status = $investorDetails[6];
        				if ($invstr_Status == 0) {
        					$errorMsg = "Sorry, <b>". $user_name ."</b> is bloacked by the admin, please contact the administrator";;
        					$errorList[] = $errorMsg;
        					$data = json_encode(array('Status' => false, 'Message' => $errorList));
        				} else {
        					$investorLoginQry = mysqli_query($conn, "SELECT investorPasscode FROM investors WHERE (investorMobile = '". $investorDetails[2] ."' OR investorEmail = '". $investorDetails[3] ."' OR investorID = '". $investorDetails[0] ."') AND investorPasscode = '". $pass_word ."'");
        					if ($investorLoginQry) {
        						if (mysqli_num_rows($investorLoginQry) > 0) {
                                    $loginDate = date("Y-m-d H:i:s");				
        							$_SESSION["investorIdd"] = $investorDetails[0];
        							$_SESSION["investorName"] = $investorDetails[1];
        							$_SESSION["investorMobile"] = $investorDetails[3];
        							$_SESSION["investorEmail"] = $investorDetails[4];
        							$_SESSION["investorPhoto"] = $investorDetails[5];
        							$_SESSION["userType"] = 'Investor';
        							mysqli_query($conn, "INSERT INTO `investor_logins`(`investorID`, `loginDateTime`) VALUES ('". $_SESSION["investorIdd"] ."', '". $loginDate ."')") or die(mysqli_error($conn));
        							mysqli_query($conn, "UPDATE investors SET investorLoginStatus = '1' WHERE tenantID = '". $_SESSION["investorIdd"] ."'") or die(mysqli_error($conn));
        							$data = json_encode(array('Status' => true, 'Message' => 'dashboard'));
        						} else {
        							$errorMsg = "Sorry, investor password is incorrect. Try again!";;
        							$errorList[] = $errorMsg;
        							$data = json_encode(array('Status' => false, 'Message' => $errorList));
        						}
        					} else {
        					    $errorMsg = "Investor:". mysqli_error($conn);
            					$errorList[] = $errorMsg;
            					$data = json_encode(array('Status' => false, 'Message' => $errorList));
        					}
        				}

                    } else {

						// Tenant Login Section
						$checkTenantLogin = mysqli_query($conn, "SELECT tenantID, tenantName, tenantAddress, tenantMobile, tenantEmail, tenantPasscode, tenantPhoto, tenantStatus FROM tenants WHERE tenantMobile = '". $user_name ."' OR tenantEmail = '". $user_name ."' OR tenantID = '". $user_name ."'");
						if ($checkTenantLogin) {
							if (mysqli_num_rows($checkTenantLogin) > 0) {
								$tenantDetails = mysqli_fetch_array($checkTenantLogin);
								$tenant_Status = $tenantDetails[7];
								if ($tenant_Status == 0) {
									$errorMsg = "Sorry, <b>". $user_name ."</b> is bloacked by the admin, please contact the administrator";;
									$errorList[] = $errorMsg;
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								} else {
									$tenantLoginQry = mysqli_query($conn, "SELECT tenantPasscode FROM tenants WHERE (tenantMobile = '". $tenantDetails[2] ."' OR tenantEmail = '". $tenantDetails[3] ."' OR tenantID = '". $tenantDetails[0] ."') AND tenantPasscode = '". $pass_word ."'");
									if ($tenantLoginQry) {
										if (mysqli_num_rows($tenantLoginQry) > 0) {
											$loginDate = date("Y-m-d H:i:s");
											$_SESSION["lastLoginTimeStamp"] = time();				
											$_SESSION["tenantIdd"] = $tenantDetails[0];
											$_SESSION["tenantName"] = $tenantDetails[1];
											$_SESSION["tenantAddress"] = $tenantDetails[2];
											$_SESSION["tenantMobile"] = $tenantDetails[3];
											$_SESSION["tenantEmail"] = $tenantDetails[4];
											$_SESSION["tenantPhoto"] = $tenantDetails[6];
											$_SESSION["userType"] = 'Tenant';
											mysqli_query($conn, "INSERT INTO `tenant_logins`(`tenantID`, `loginDateTime`) VALUES ('". $_SESSION["tenantIdd"] ."', '". $loginDate ."')") or die(mysqli_error($conn));
											mysqli_query($conn, "UPDATE tenants SET tenantLoginStatus = '1' WHERE tenantID = '". $_SESSION["tenantIdd"] ."'") or die(mysqli_error($conn));
											$data = json_encode(array('Status' => true, 'Message' => 'tenant/dashboard'));
										} else {
											$errorMsg = "Sorry, tenant password is incorrect. Try againtenant!";;
											$errorList[] = $errorMsg;
											$data = json_encode(array('Status' => false, 'Message' => $errorList));
										}
									} else {
										$errorMsg = mysqli_error($conn);
										$errorList[] = $errorMsg;
										$data = json_encode(array('Status' => false, 'Message' => $errorList));
									}
								}

							} else {

								// Landlord Login Section
								$checkLandlordLogin = mysqli_query($conn, "SELECT landlordID, landlordName, landlordAddress, landlordMobile, landlordEmail, landlordPasscode, landlordPhoto, landlordStatus FROM landlords WHERE landlordMobile = '". $user_name ."' OR landlordEmail = '". $user_name ."' OR landlordID = '". $user_name ."'");
								if ($checkLandlordLogin) {
									if (mysqli_num_rows($checkLandlordLogin) > 0) {
										$landlordDetails = mysqli_fetch_array($checkLandlordLogin);
										$landlord_Status = $landlordDetails[7];
										if ($landlord_Status == 0) {
											$errorMsg = "Sorry, <b>". $user_name ."</b> is bloacked by the admin, please contact the administrator";;
											$errorList[] = $errorMsg;
											$data = json_encode(array('Status' => false, 'Message' => $errorList));
										} else {
											$landlordLoginQry = mysqli_query($conn, "SELECT landlordPasscode FROM landlords WHERE (landlordMobile = '". $landlordDetails[2] ."' OR landlordEmail = '". $landlordDetails[3] ."' OR landlordID = '". $landlordDetails[0] ."') AND landlordPasscode = '". $pass_word ."'");
											if ($landlordLoginQry) {
												if (mysqli_num_rows($landlordLoginQry) > 0) {
													$loginDate = date("Y-m-d H:i:s");
													$_SESSION["lastLoginTimeStamp"] = time();				
													$_SESSION["landlordIdd"] = $landlordDetails[0];
													$_SESSION["landlordName"] = $landlordDetails[1];
													$_SESSION["landlordAddress"] = $landlordDetails[2];
													$_SESSION["landlordMobile"] = $landlordDetails[3];
													$_SESSION["landlordEmail"] = $landlordDetails[4];
													$_SESSION["landlordPhoto"] = $landlordDetails[6];
													$_SESSION["userType"] = 'Landlord';
													mysqli_query($conn, "INSERT INTO `landlord_logins`(`landlordID`, `loginDateTime`) VALUES ('". $_SESSION["landlordIdd"] ."', '". $loginDate ."')") or die(mysqli_error($conn));
													mysqli_query($conn, "UPDATE landlords SET landlordLoginStatus = '1' WHERE landlordID = '". $_SESSION["landlordIdd"] ."'") or die(mysqli_error($conn));
													$data = json_encode(array('Status' => true, 'Message' => 'landlord/dashboard'));
												} else {
													$errorMsg = "Sorry, landlord password is incorrect. Try againtenant!";;
													$errorList[] = $errorMsg;
													$data = json_encode(array('Status' => false, 'Message' => $errorList));
												}
											} else {
												$errorMsg = mysqli_error($conn);
												$errorList[] = $errorMsg;
												$data = json_encode(array('Status' => false, 'Message' => $errorList));
											}
										}
									} else {
										$errorMsg = "Sorry, <b>". $user_name ."</b> does not exist anymore";;
										$errorList[] = $errorMsg;
										$data = json_encode(array('Status' => false, 'Message' => $errorList));
									}
								} else {
									$errorMsg = mysqli_error($conn);
									$errorList[] = $errorMsg;
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								}
							}

						} else {
							$errorMsg = mysqli_error($conn);
							$errorList[] = $errorMsg;
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}

					}

		        } else {
		            $errorMsg = "Investor: ". mysqli_error($conn);
        			$errorList[] = $errorMsg;
        			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		        }

			}
			
		} else {
			$errorMsg = "Administration". mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}

		echo $data;
	}
	// ========================== End of Direct Login Process ==============================================

	// ========================== Start of Resend Verification Code ========================================
	
	function resend_verification_code($conn) {
	    
		$verification_code = "M-" . generateRandomString(6);
		
		$update_verification_code = mysqli_query($conn, "UPDATE system_users SET verificationCode = '" . $verification_code . "' WHERE userID = '" . mysqli_real_escape_string($conn, $_SESSION["tempUserID"]) . "'") or die(mysqli_error($conn));
		if ($update_verification_code) {
		    
		    $messageBody = "Dear " . $_SESSION["tempFullName"] . ", Your verification code to login into Lighthouse system is: ". $verification_code;
			$data = array(
				"refid" => "0", "mobile" => $_SESSION["tempUserPhone"], "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
			);
			$data1 = json_encode($data);
			$username = 'lighthouse1';
			$password = 'Sja3wj5EhSr4tggVLJmcCw==';

			$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
			$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_HEADER, 1);
			curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$return = curl_exec($ch);
			// print_r($return);
			$return = explode(':', $return);
	
			// for ($i=0; $i < count($return) ; $i++) {
			//     echo $i. ':' . $return[$i];
			// }
			$stat = explode('"', $return[17]);
			$msg1 = explode(',', $return[20]);
			$msg = explode('"', $msg1[0]);
			// print_r($msg[1]);
		
			if ($stat[1] != 'Failed.') {
				$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $_SESSION["tempUserID"] . "', '" . $_SESSION["tempUserID"] . "', 'Login Verification Code', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $_SESSION["tempUserPhone"] ."', '" . mysqli_real_escape_string($conn, $_SESSION['tempUserID']) . "', '". date("Y-m-d H:i:s") ."')");
				if ($saveSms) {
					//$success_arr = array('message' => $msg[1]);
					
				    $messageBody = "<h2 class='text-info'>Dear " . $_SESSION["tempFullName"] . ",</h2><p style='font: 17px Arial; line-height: 1.7'>Your verification code to login into Lighthouse system <strong><a href='lighthousecore.com/admin_panel'>Lighthouse System</a></strong> is: <span class='text-info' style='font-size: 20px;'><strong>" . $verification_code . "</strong></span> <br /><br />Best regards,<br><strong>Lighthouse Team</strong><br /><br />";
					$mail = new PHPMailer(true);							                                    //Create instance of PHPMailer
					$mail->isSMTP();									                                        //Set mailer to use smtp
					//$mail->SMTPDebug = 2;
					$mail->Host = "mail.lighthousecore.com";						                            //Define smtp host
					//$mail->SMTPAuth = true;								                                    //Enable smtp authentication
					//$mail->SMTPSecure = "ssl";							                                    //Set smtp encryption type (ssl/tls)
					$mail->Port = "25";								                                            //Port to connect smtp
					$mail->Username = "no-reply@lighthousecore.com";	    	                                //Set gmail username
					$mail->Password = "Lighthouse9414";						                                    //Set gmail password
					$mail->Subject = "Login Verification Code";	                                                //Email subject
					$mail->setFrom("no-reply@lighthousecore.com", "Lighthouse Construction & Real Estates");    //Set sender email
					$mail->isHTML(true);									                                    //Enable HTML
					//$mail->addAttachment('img/attachment.png');			                                    //Attachment
					//Email body
					$mail->Body = $messageBody;
					$mail->addAddress($_SESSION["tempUserEmail"]);				                                //Add recipient

					//Finally send email
					if ($mail->send()) {
						//echo $mail->send();
						$user_email = explode("@", $_SESSION["tempUserEmail"]);
						$successMessage = "Verification code sent to <strong>". substr($user_email[0], 0, 3)."****@". $user_email[1] ."</strong>";
						$data = json_encode(array('Status' => true, 'Message' => $successMessage));
					} else {
						//echo "Message could not be sent. Mailer Error: ". $mail->ErrorInfo;
						$errorMsg = $mail->ErrorInfo;
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
					$mail->smtpClose();										                                    //Closing smtp connection

				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				$errorList[] = $msg[1];
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		} else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
	    
	    echo $data;
       
	}
	
	// ========================== End of Resend Verification Code ==========================================
	
	// ========================== Login process with 2 step verification starts here =======================
	
	function login_with_2step_verification($conn) {
		global $errorList;
        $data = array();
        extract($_POST);
        $getVerificationCode = mysqli_query($conn, "SELECT verificationCode FROM system_users WHERE userID = '". mysqli_real_escape_string($conn, $_SESSION["tempUserID"]) ."'");
        if ($getVerificationCode) {
            if (mysqli_num_rows($getVerificationCode) > 0) {
    			$verify_rs = mysqli_fetch_array($getVerificationCode);
    			$verifyCode = $verify_rs[0];
    			$userEnteredCode = $verify_code;
    			if ($verifyCode == $userEnteredCode) {
                    $getLoggedUser = mysqli_query($conn, "SELECT system_users.userID, system_users.Username, system_users.Passcode, employees.employeeName, departments.departmentName, employees.employeePosition, employee_positions.positionName, employees.employeeMobileNo, employees.employeeEmailAddress, employees.employeePhoto 
            		FROM system_users 
            		JOIN employees ON employees.employeeID = system_users.employeeID 
                    JOIN departments ON employees.employeeDepartment = departments.departmentID
                    JOIN employee_positions ON employees.employeePosition = employee_positions.positionID		
                    WHERE system_users.userID = '" . mysqli_real_escape_string($conn, $_SESSION["tempUserID"]) . "'");
                    if ($getLoggedUser) {
                        if (mysqli_num_rows($getLoggedUser) > 0) {
                            $userDetails = mysqli_fetch_array($getLoggedUser);
        					$_SESSION["lastLoginTimeStamp"] = time();
        					$loginDate = date("Y-m-d H:i:s");
        					$_SESSION["userIdd"] = $userDetails[0];
        					$_SESSION["userName"] = $userDetails[1];
        					$_SESSION["fullName"] = $userDetails[3];
        					$_SESSION["departmentName"] = $userDetails[4];
        					$_SESSION["userTypeID"] = $userDetails[5];
        					$_SESSION["userType"] = $userDetails[6];
        					$_SESSION["userPhone"] = $userDetails[7];
        					$_SESSION["userEmail"] = $userDetails[8];
        					$_SESSION["userPhoto"] = $userDetails[9];
        					unset($_SESSION['tempUserID']);
        					unset($_SESSION['tempFullName']);
        					unset($_SESSION['tempUserPhone']);
        					unset($_SESSION['tempUserEmail']);
        					mysqli_query($conn, "INSERT INTO `user_logins`(`userID`, `loginDateTime`) VALUES ('" . $_SESSION["userIdd"] . "', '" . $loginDate . "')") or die(mysqli_error($conn));
        					mysqli_query($conn, "UPDATE system_users SET loginStatus = '1' WHERE userID = '" . $_SESSION["userIdd"] . "'") or die(mysqli_error($conn));
        					
        					$getCurrentUser = mysqli_query($conn, "SELECT visitedPageURL FROM last_visited_page WHERE userID = '". $_SESSION['userIdd'] ."'") or die(mysqli_error($conn));
                		    if ($getCurrentUser) {
                		        if (mysqli_num_rows($getCurrentUser) > 0) {
                		            $visited_url_rs = mysqli_fetch_array($getCurrentUser);
                		            $data = json_encode(array('Status' => true, 'Message' => $visited_url_rs[0]));
                		        } else {
							        $data = json_encode(array('Status' => true, 'Message' => 'dashboard'));
                		        }
                		    }
                        }
                    } else {
            		    $errorList[] = mysqli_error($conn);
            			$data = json_encode(array('Status' => false, 'Message' => $errorList));
                    }
                } else {
    			    $errorList[] = "Provided verification code is incorrect, try again";
        			$data = json_encode(array('Status' => false, 'Message' => $errorList));
                }
            } else {
    		    $errorList[] = mysqli_error($conn);
    			$data = json_encode(array('Status' => false, 'Message' => $errorList));
            }
        } else {
            $errorList[] = mysqli_error($conn);
            $data = json_encode(array('Status' => false, 'Message' => $errorList));
        }
        echo $data;
    }
    
	// ========================== End of 2 Step Verification Login Process =================================
	
	// ========================== Start of Password Reset Code =============================================
	
	function send_reset_password_code($conn) {
	    global $ereyFure;
	    global $errorList;
        $data = array();
        extract($_POST);

		$get_user_info = mysqli_query($conn, "SELECT employees.employeeName, employees.empEmail, system_users.Username, system_users.password FROM employees JOIN system_users ON (system_users.employeeID = employees.employeeID) WHERE employees.empEmail = '". mysqli_real_escape_string($conn, $emailToReset) ."'") or die (mysqli_error($conn));
		
		if ($get_user_info) {
		    
		    if (mysqli_num_rows($get_user_info) > 0) {
		        
    		    $emp_id_rs = mysqli_fetch_array($get_user_info);
    		    $employeee_namee = $emp_id_rs[0];
    		    $employeee_email = $emp_id_rs[1];
    		    $user_nameeeeeee = $emp_id_rs[2];
    		    $employeee_password = kuceliAsalka($emp_id_rs[3], $ereyFure);
    
    	        $messageBody = "<h2 class='text-info'>Dear ". $employeee_namee .",</h2><p style='font: 17px Arial; line-height: 1.7'>This email contains your login credentials to login to Lighthouse system => <br><br><span class='text-info'>Username: <strong>". $user_nameeeeeee ."</strong></span><br><span class='text-info'>Password: <strong>". $employeee_password ."</strong></span><br><br>This email contains sensitive information, please do not share this email with others. <br><br>Best regards,<br><strong>Lighthouse Team</strong><br><br>";
    
    
    	        $mail = new PHPMailer(true);							                                    //Create instance of PHPMailer
				$mail->isSMTP();									                                        //Set mailer to use smtp
				//$mail->SMTPDebug = 2;
				$mail->Host = "mail.lighthousecore.com";						                            //Define smtp host
				//$mail->SMTPAuth = true;								                                    //Enable smtp authentication
				//$mail->SMTPSecure = "ssl";							                                    //Set smtp encryption type (ssl/tls)
				$mail->Port = "25";								                                            //Port to connect smtp
				$mail->Username = "no-reply@lighthousecore.com";	    	                                //Set gmail username
				$mail->Password = "Lighthouse9414";						                                    //Set gmail password
				$mail->Subject = "Login Verification Code";	                                                //Email subject
				$mail->setFrom("no-reply@lighthousecore.com", "Lighthouse Construction & Real Estates");    //Set sender email
				$mail->isHTML(true);									                                    //Enable HTML
				//$mail->addAttachment('img/attachment.png');			                                    //Attachment
				//Email body
				$mail->Body = $messageBody;
				$mail->addAddress($_SESSION["$employeee_email"]);
    
            	//Finally send email
            	if ( $mail->send() ) {
            		//echo "Email Sent..!";
            		$successMessage = "Your password has been sent to ". $employeee_email;
            		$data = json_encode(array('Status'=>true, 'Message'=> $successMessage));
            	} else {
            		//echo "Message could not be sent. Mailer Error: ". $mail->ErrorInfo;
            		$errorMsg = $mail->ErrorInfo;
                    $errorList[] = $errorMsg;
            		$data = json_encode(array('Status'=>false, 'Message'=> $errorList));
            	}
            	
            	$mail->smtpClose();										//Closing smtp connection
            	
    		} else {
    		    
    		    $get_investor_info = mysqli_query($conn, "SELECT investorName, Email, tenantID, investorPasscode FROM investors WHERE Email = '". mysqli_real_escape_string($conn, $emailToReset) ."'") or die (mysqli_error($conn));
		        
		        if ($get_investor_info) {
		            
		            if (mysqli_num_rows($get_investor_info) > 0) {
            		    $investor_id_rs = mysqli_fetch_array($get_investor_info);
            		    $investorr_namee = $investor_id_rs[0];
            		    $investorr_email = $investor_id_rs[1];
            		    $investorr_idddd = $investor_id_rs[2];
            		    $investorr_password = $investor_id_rs[3];
            
            	        $messageBody = "<h2 class='text-info'>Dear ". $investorr_namee .",</h2><p style='font: 17px Arial; line-height: 1.7'>This email contains your login credentials to login to Marjan system => <br><br><span class='text-info'>Username: <strong>". $investorr_idddd ."</strong></span><br><span class='text-info'>Password: <strong>". $investorr_password ."</strong></span><br><br>This email contains sensitive information, please do not share this email with others. <br><br>Best regards,<br><strong>Marjan Real Estate Team</strong><br><br>";
            
                    	$mail = new PHPMailer(true);							                                    //Create instance of PHPMailer
                    	$mail->isSMTP();									                                        //Set mailer to use smtp
                    	$mail->Host = "mail.marjan.so";						                                        //Define smtp host
                    	//$mail->SMTPAuth = true;								                                    //Enable smtp authentication
                    	//$mail->SMTPSecure = "ssl";							                                    //Set smtp encryption type (ssl/tls)
                    	$mail->Port = "25";								                                            //Port to connect smtp
                    	$mail->Username = "no-reply@marjan.so";	    	                                            //Set gmail username
                    	$mail->Password = "Marjaan9414";						                                    //Set gmail password
                    	$mail->Subject = "Marjan Login Credentials";	                                            //Email subject
                    	$mail->setFrom("no-reply@marjan.so", "Marjan Real Estate");	    		                    //Set sender email
                    	$mail->isHTML(true);									                                    //Enable HTML
                    	//$mail->addAttachment('img/attachment.png');			                                    //Attachment
                    	//Email body
                    	$mail->Body = $messageBody;
                    	$mail->addAddress($investorr_email);				                                       //Add recipient
                    
                    	//Finally send email
                    	if ( $mail->send() ) {
                    		//echo "Email Sent..!";
                    		$successMessage = "Your password has been sent to ". $investorr_email;
                    		$data = json_encode(array('Status'=>true, 'Message'=> $successMessage));
                    	} else {
                    		//echo "Message could not be sent. Mailer Error: ". $mail->ErrorInfo;
                    		$errorMsg = $mail->ErrorInfo;
                            $errorList[] = $errorMsg;
                    		$data = json_encode(array('Status'=>false, 'Message'=> $errorList));
                    	}
                    	
                    	$mail->smtpClose();									//Closing smtp connection
                    	
                    } else {
                        
                        $errorMsg = "Sorry, ". $emailToReset ." is not registered in the system, please try again";
            			$errorList[] = $errorMsg;
            			$data = json_encode(array('Status'=>false, 'Message'=> $errorList));
            			
                    }
                    
		        } else {
		            
		            $errorMsg = mysqli_error($conn);
        			$errorList[] = $errorMsg;
        			$data = json_encode(array('Status'=>false, 'Message'=> $errorList));
        			
		        }

    		}
		    
		} else {
		    
		    $errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status'=>false, 'Message'=> $errorList));
			
		}
		    
	    echo $data;

	}
	
	// ========================== End of Password Reset Code ==========================
	
	// ========================== Start of Check Files Function =======================
	function check_every_file($file) {
		global $errorList;
		if (substr($file, 0, 5) == "photo") {
			// If the uploaded file is photo, then do the following....
			$filename = $_FILES[$file]['name'];
			$thisExt = pathinfo($filename, PATHINFO_EXTENSION);
			$fileSize = $_FILES[$file]['size'];
			$allowedExt = array("jpg", "jpeg", "png", "gif", "ico", "JPEG", "JPG", "PNG", "GIF", "ICO");
			if (in_array($thisExt, $allowedExt)) {
				if ($fileSize > 1000000) {
					$errorList[] = "<b>" . $filename . "</b> is greater than <b>1 MB</b> which is the allowed size";
				} else {
					return "Success###" . $filename . "###" . $thisExt;
				}
			} else {
				$errorList[] = "Images with <b>" . strtoupper($thisExt) . " extension are not allowed</b>";
			}
		} else {
			// If the uploaded file is document, then do the following....
			$filename = $_FILES[$file]['name'];
			$thisExt = pathinfo($filename, PATHINFO_EXTENSION);
			$fileSize = $_FILES[$file]['size'];
			$allowedExt = array("pdf", "jpg", "jpeg", "png", "gif", "PDF", "JPEG", "JPG", "PNG", "GIF");
			if (in_array($thisExt, $allowedExt)) {
				if ($fileSize > 2000000) {
					$errorList[] = "<b>" . $filename . "</b> is bigger than <b>2 MB</b> which is the allowed size";
				} else {
					return "Success###" . $filename . "###" . $thisExt;
				}
			} else {
				$errorList[] = "Documents with <b>" . strtoupper($thisExt) . " extension are not allowed</b>";
			}
		}
	}
	// ========================== End of Check Files Function ========================

	//========================== Insert, Update and Delete Function ========================
	function ins_upd_del_everything($conn) {
		global $ereyFure;
		global $errorList;
		$data = array();
		extract($_POST);
		$tn = kuceliAsalka($tn, $ereyFure);
		$getValues = explode("###", $vl);
		$valID = $getValues[0];
		if ($commandType == "insert_command") {
			// Insert Query section goes here .....
			//Generate New ID for the current inserted row....
			$getMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM " . $tn . "") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxID) > 0) {
				$maxID = mysqli_fetch_array($getMaxID);
				$curMaxID = $maxID[0] + 1;
				$generatedID = $objPre. "". sprintf("%04d", $curMaxID);
			} else {
				$curMaxID = 1;
				$generatedID = $objPre. "". sprintf("%04d", $curMaxID);
			}
			
			if ($hasFile == "Yes") {
				//Insert if the query contains images and other files ...
				$fileList = explode("###", $files);
				$fileValues = "";
				$p = 0; $d = 0;
				foreach ($fileList as $file) {
					if (substr($file, 0, 5) == "photo") {
						if (isset($_FILES[$file])) {
							$checked_file = check_every_file($file);
							$fileInfo = explode("###", $checked_file);
							if (count($errorList) > 0) {
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							} else {
								$fileNewName = $generatedID . "_" . $p . "." . $fileInfo[2];
								$photoPath = "../uploads/photos/" . $fileNewName;
								move_uploaded_file($_FILES[$file]['tmp_name'], $photoPath);
								$fileValues .= "uploads/photos/" . $fileNewName . "###";
							}
						} else {
							$uploadDefaultPhoto = "../img/no-image.jpg";
							copy($uploadDefaultPhoto, "../uploads/photos/no-image.jpg");
							$fileValues .= "uploads/photos/no-image.jpg" . "###";
						}
						$p++;
					} else {
						if (isset($_FILES[$file])) {
							$checked_file = check_every_file($file);
							$fileInfo = explode("###", $checked_file);
							if (count($errorList) > 0) {
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							} else {
								$fileNewName = $generatedID . "_" . $d . "." . $fileInfo[2];
								$photoPath = "../uploads/documents/" . $fileNewName;
								move_uploaded_file($_FILES[$file]['tmp_name'], $photoPath);
								$fileValues .= "uploads/documents/" . $fileNewName . "###";
							}
						} else {
							$uploadDefaultPhoto = "../img/no-file.png";
							copy($uploadDefaultPhoto, "../uploads/documents/no-file.png");
							$fileValues .= "uploads/documents/no-file.png" . "###";
						}
						$d++;
					}
				}
				$vl .= "###" . substr($fileValues, 0, -3);
				$getValues = explode("###", $vl);

				$getVal = "";
				foreach ($getValues as $val) {
					if ($val == "") {
						continue;
					};
					$getVal .= "'" . mysqli_real_escape_string($conn, $val) . "'" . ",";
				}
				// echo "INSERT INTO " . $tn . " VALUES ('', '" . mysqli_real_escape_string($conn, $generatedID) . "'," . rtrim($getVal, ",") . ")";
				if (count($errorList) <= 0) {
					$regQry = mysqli_query($conn, "INSERT INTO " . $tn . " VALUES ('', '" . mysqli_real_escape_string($conn, $generatedID) . "'," . rtrim($getVal, ",") . ")");
					if ($regQry) {
						if ($tn == "rented_properties") {
							$getRentalPropertyInformation = mysqli_query($conn, "SELECT property_types.propertyTypeDescription, rental_properties.propertyName, buildings.buildingName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, rental_properties.depositAmount, rental_properties.rentalPrice
							FROM rental_properties
							JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID
							JOIN buildings ON rental_properties.buildingID = buildings.buildingID
							JOIN property_locations ON buildings.locationID = property_locations.locationID
							WHERE rental_properties.rentalPropertyID = '". mysqli_real_escape_string($conn, $getValues[0]) ."'") or die(mysqli_error($conn));
							if (mysqli_num_rows($getRentalPropertyInformation) > 0) {
								$rent_property_info_rs = mysqli_fetch_array($getRentalPropertyInformation);
							}
							$getTenantInformation = mysqli_query($conn, "SELECT tenantID, tenantName, tenantGender, tenantMobile, tenantPasscode FROM tenants WHERE tenantID = '". mysqli_real_escape_string($conn, $getValues[1]) ."'") or die(mysqli_error($conn));
							if (mysqli_num_rows($getTenantInformation) > 0) {
								$tenant_info_rs = mysqli_fetch_array($getTenantInformation);
							}
							if ($tenant_info_rs[2] == "Male") {
							    $cutomer_information = "Mudane ". $tenant_info_rs[1];
							} else if ($tenant_info_rs[2] == "Female") {
							    $cutomer_information = "Marwo ". $tenant_info_rs[1];
							}
							
                            $messageBody = $cutomer_information. ", kusoo dhawoow shirkadda Lighthouse iyo deegaankaaga cusub ". $rent_property_info_rs[1] .", ". $rent_property_info_rs[2] ." oo ku yaala ". $rent_property_info_rs[3] .", ". $rent_property_info_rs[4] ."-". $rent_property_info_rs[5].".  Waxaan rajaynaynaa in aad waqti fiican ku qaadan doonto IA.  Kiradaada waxay ka bilaabanaysaa ". date_format(date_create($getValues[2]),"F d,Y").".  Si aad u heshid macmuulaadka la xiriira deegaankaaga sida kiro dalacida, lacag bixinta iyo ogaysiisyada kale waxaad booqataa: https://lighthousecore.com/admin_panel.  Si aad u gasho mareegta, isticmaal teleefoonka numberkaaga: ". $tenant_info_rs[3] ." iyo erayga sirta: ". $tenant_info_rs[4] .". Wixii talo iyo tusaalooyiin ah, Fadlan naga soo wac +252614273333 ama noogu soo dir info@lighthousecore.com";
							$data = array(
								"refid" => "0", "mobile" => $tenant_info_rs[3], "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
							);
							$data1 = json_encode($data);
							$username = 'lighthouse1';
							$password = 'Sja3wj5EhSr4tggVLJmcCw==';
					
							$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
							$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
							curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
							curl_setopt($ch, CURLOPT_HEADER, 1);
							curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
							curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
							curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
							$return = curl_exec($ch);
							// print_r($return);
							$return = explode(':', $return);
					
							// for ($i=0; $i < count($return) ; $i++) {
							//     echo $i. ':' . $return[$i];
							// }
							$stat = explode('"', $return[17]);
							$msg1 = explode(',', $return[20]);
							$msg = explode('"', $msg1[0]);
							// print_r($msg[1]);
							
							if ($stat[1] != 'Failed.') {
								$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedID) . "', '" . $tenant_info_rs[0] . "', 'Renting Start', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $tenant_info_rs[3] ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')");
								if ($saveSms) {
									//$success_arr = array('message' => $msg[1]);

									$getDepositAmount = mysqli_query($conn, "SELECT depositAmount FROM rental_properties WHERE rentalPropertyID = '". mysqli_real_escape_string($conn, $getValues[0]) ."'") or die(mysqli_error($conn));
									if (mysqli_num_rows($getDepositAmount) > 0) {
										$prop_rs = mysqli_fetch_array($getDepositAmount);
										// If deposit amount is greater than 0, charge that deposit automatically
										if ($prop_rs[0] > 0) {
											// Charge the deposit amount automatically

											//Generate Charge ID for the current inserted row....
											$getChargeMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenant_charges") or die(mysqli_error($conn));
											if (mysqli_num_rows($getChargeMaxID) > 0) {
												$maxChargeID = mysqli_fetch_array($getChargeMaxID);
												$curChargeMaxID = $maxChargeID[0] + 1;
												$generatedChargeID = "CH" . sprintf("%04d", $curChargeMaxID);
											} else {
												$curChargeMaxID = 1;
												$generatedChargeID = "CH" . sprintf("%04d", $curChargeMaxID);
											}
											$chargeDepositAmount = mysqli_query($conn, "INSERT INTO tenant_charges VALUES (NULL, '". $generatedChargeID ."', '". $generatedID ."', '". $getValues[1] ."', '". $getValues[0] ."', 'CHT0002', '". $prop_rs[0] ."', '". date("F-Y") ."', 'Deposit Fee Charge', '" . $_SESSION['userIdd'] . "',  '" . date("Y-m-d H:i") . "', '-', '-')") or die(mysqli_error($conn));
											if ($chargeDepositAmount) {
											    $messageBody2 = $cutomer_information. ", waxaan kugu wargelinaynaa in lagugu dalacay lacag dhan $". number_format($prop_rs[0], 2)."  taas oo ah lacagta horumariska (deebaaji) ee guriga: ". $rent_property_info_rs[1] .", ". $rent_property_info_rs[2] ."  kaas oo ku yaala ". $rent_property_info_rs[3] .", ". $rent_property_info_rs[4] ."-". $rent_property_info_rs[5] .". Wixii talo iyo tusaalooyiin ah, fadlan naga soo wac +252614273333 ama noogu soo dir info@lighthousecore. Mahadsanid";
												// $messageBody2 = "Hello Dear ". $tenant_info_rs[1] .", We would like to inform you that you have been charged a total of $". number_format($prop_rs[0], 2) ." which is the deposit fee for your residence: ". $rent_property_info_rs[1] .", ". $rent_property_info_rs[2] ." which is located in ". $rent_property_info_rs[3] .", ". $rent_property_info_rs[4] ."-". $rent_property_info_rs[5] .". If you have any questions or guidance, please call us on +252615273333 or email us on info@lighthousecore.com or visit our website: https://lighthousecore.com. Best wishes.";
												$data = array(
													"refid" => "0", "mobile" => $tenant_info_rs[3], "message" => $messageBody2, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
												);
												$data1 = json_encode($data);
												$username = 'lighthouse1';
												$password = 'Sja3wj5EhSr4tggVLJmcCw==';
										
												$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
												$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
												curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
												curl_setopt($ch, CURLOPT_HEADER, 1);
												curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
												curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
												curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
												$return = curl_exec($ch);
												$return = explode(':', $return);
										
												// for ($i=0; $i < count($return) ; $i++) {
												//     echo $i. ':' . $return[$i];
												// }
												$stat = explode('"', $return[17]);
												$msg1 = explode(',', $return[20]);
												$msg = explode('"', $msg1[0]);
												// print_r($msg[1]);
												
												if ($stat[1] != 'Failed.') {
													$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedID) . "', '" . $tenant_info_rs[0] . "', 'Deposit Charge', '" . mysqli_real_escape_string($conn, $messageBody2) . "', '1', '". $tenant_info_rs[3] ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')");
													if ($saveSms) {
														// Update property status
														mysqli_query($conn, "UPDATE rental_properties SET propertyStatus = '2' WHERE rentalPropertyID = '". mysqli_real_escape_string($conn, $getValues[0]) ."'") or die(mysqli_error($conn));
														$successMsg = $objName . " has been registered successfully";
														$data = json_encode(array('Status' => true, 'Message' => $successMsg));
													} else {
														$errorList[] = $msg[1];
														$data = json_encode(array('Status' => false, 'Message' => $errorList));
													}
												}

											} else {
												$errorMsg = mysqli_error($conn);
												$errorList[] = $errorMsg;
												$data = json_encode(array('Status' => false, 'Message' => $errorList));
											}
										} else {
											// Update property status
											mysqli_query($conn, "UPDATE rental_properties SET propertyStatus = '2' WHERE rentalPropertyID = '". mysqli_real_escape_string($conn, $getValues[0]) ."'") or die(mysqli_error($conn));
											$successMsg = $objName . " has been registered successfully";
											$data = json_encode(array('Status' => true, 'Message' => $successMsg));
										}

									}
								} else {
									$errorMsg = mysqli_error($conn);
									$errorList[] = $errorMsg;
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								}
							} else {
								$errorList[] = $msg[1];
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
							
						} else if ($tn == "tenants") {

							// First give tenant privileges of allowed menus
							$getTenantMenues = mysqli_query($conn, "SELECT * FROM tenant_menus") or die(mysqli_error($conn));
							if ($getTenantMenues) {
								if (mysqli_num_rows($getTenantMenues) > 0) {
									while ($tenant_menu_rs = mysqli_fetch_array($getTenantMenues)) {
										mysqli_query($conn, "INSERT INTO tenant_privileges(tenantID, tenantMenuID, mainMenuMode) VALUES ('". mysqli_real_escape_string($conn, $generatedID) ."', '". $tenant_menu_rs[0] ."', '". $tenant_menu_rs[4] ."')") or die(mysqli_error($conn));
									}
								}
							} else {
        						$errorList[] = mysqli_error($conn);
        						$data = json_encode(array('Status'=>false, 'Message'=> $errorList));
							}

							$tenant_id = $generatedID;
							$tenant_full_name = $getValues[0];
							$tenant_gender = $getValues[3];
							if ($tenant_gender == "Male") {
							    $cutomer_information = "Mudane ". $tenant_full_name;
							} else if ($tenant_info_rs[2] == "Female") {
							    $cutomer_information = "Marwo ". $tenant_full_name;
							}
							$tenant_tell_no = $getValues[6];
							// Send welcome message to the new registered Tenant through this mobile number
							$messageBody = $cutomer_information. ", Ku soo dhowow shirkadda iibinta, kireynta iyo dhisida guryaha ee Lighthouse, waan ku faraxsanahay inaad nagu soo biirtay, si guul ah ayaa laguu diiwaan geliyay.";

							$data = array(
								"refid" => "0", "mobile" => $tenant_tell_no, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
							);
							$data1 = json_encode($data);
							$username = 'lighthouse1';
							$password = 'Sja3wj5EhSr4tggVLJmcCw==';
					
							$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
							$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
							curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
							curl_setopt($ch, CURLOPT_HEADER, 1);
							curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
							curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
							curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
							$return = curl_exec($ch);
							$return = explode(':', $return);
					
							// for ($i=0; $i < count($return) ; $i++) {
							//     echo $i. ':' . $return[$i];
							// }
							$stat = explode('"', $return[17]);
							$msg1 = explode(',', $return[20]);
							$msg = explode('"', $msg1[0]);
							// print_r($msg[1]);
							
							if ($stat[1] != 'Failed.') {
								$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedID) . "', '" . $tenant_id . "', 'Registration Message', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $tenant_tell_no ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')");
								if ($saveSms) {
									//$success_arr = array('message' => $msg[1]);
									mysqli_query($conn, "INSERT INTO tenant_profile VALUES (NULL, '". $tenant_id ."', '-', '-', '-', '-', '-')") or die(mysqli_error($conn));
									$successMsg = "Tenant has been registered successfully";
									$data = json_encode(array('Status' => true, 'Message' => $successMsg));
								} else {
									$errorMsg = mysqli_error($conn);
									$errorList[] = $errorMsg;
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								}
							} else {
								$errorList[] = $msg[1];
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
						} else {
							$successMsg = $objName . " has been registered successfully";
							$data = json_encode(array('Status' => true, 'Message' => $successMsg));
						}
					} else {
						$errorMsg = mysqli_error($conn);
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}
			} else {
				//Insert if the query don't have files ...
				$getVal = "";
				if ($tn == "system_users") {
					foreach ($getValues as $k=>$val) {
						if ($k == 2) {
							$getVal .= "'". mysqli_real_escape_string($conn, bedelXogta($val, $ereyFure)) ."'".",";
						} else if ($val == "") {
							continue;
						} else {
							$getVal .= "'". mysqli_real_escape_string($conn, $val) ."'".",";
						}
					} 
				} else {
					foreach ($getValues as $val) {
						if ($val == "") {
							continue;
						}
						$getVal .= "'". mysqli_real_escape_string($conn, $val) ."'".",";
					} 
				}
				// echo "INSERT INTO " . $tn . " VALUES ('', '" . mysqli_real_escape_string($conn, $generatedID) . "'," . rtrim($getVal, ",") . ")";
				if (count($errorList) <= 0) {
					$regQry = mysqli_query($conn, "INSERT INTO " . $tn . " VALUES ('', '" . mysqli_real_escape_string($conn, $generatedID) . "'," . rtrim($getVal, ",") . ")");
					if ($regQry) {
						if ($tn == "property_types") {
							$data = json_encode(array('Status' => true, 'Message' => $generatedID));
						} else if ($tn == "property_locations") {
							$data = json_encode(array('Status' => true, 'Message' => $generatedID));
						} else if ($tn == "account_numbers") {
							//Save Openning Balance Transaction into account_transactions Table
							//Generate New ID for the current inserted row....
							$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
							if (mysqli_num_rows($getTransactionMaxID) > 0) {
								$transMaxID = mysqli_fetch_array($getTransactionMaxID);
								$currentMaxID = $transMaxID[0] + 1;
								$generatedTransactionID = "TR" . $currentMaxID . "-" . date("Y");
							} else {
								$currentMaxID = 1;
								$generatedTransactionID = "TR" . $currentMaxID . "-" . date("Y");
							}
							mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . mysqli_real_escape_string($conn, $generatedID) . "', '0', '" . mysqli_real_escape_string($conn, $getValues[3]) . "', '0', 'Openning Balance', '1', '" . mysqli_real_escape_string($conn, $getValues[4]) . "', '" . mysqli_real_escape_string($conn, $getValues[5]) . "', '-', '-')") or die(mysqli_error($conn));
							$successMsg = $objName . " has been registered successfully";
							$data = json_encode(array('Status' => true, 'Message' => $successMsg));
						} else if ($tn == "expenses") {
							//Save Customer Payment Transaction into account_transactions Table
							//Generate New ID for the current inserted row....
							$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
							if (mysqli_num_rows($getTransactionMaxID) > 0) {
								$transMaxID = mysqli_fetch_array($getTransactionMaxID);
								$currentMaxID = $transMaxID[0] + 1;
								$generatedTransactionID = "TR" . $currentMaxID . "-" . date("Y");
							} else {
								$currentMaxID = 1;
								$generatedTransactionID = "TR" . $currentMaxID . "-" . date("Y");
							}
							mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . mysqli_real_escape_string($conn, $getValues[2]) . "', '" . mysqli_real_escape_string($conn, $getValues[1]) . "', '0', '" . mysqli_real_escape_string($conn, $generatedID) . "', '" . mysqli_real_escape_string($conn, $getValues[3]) . "', '1', '" . mysqli_real_escape_string($conn, $getValues[5]) . "', '" . mysqli_real_escape_string($conn, $getValues[6]) . "', '-', '-')") or die(mysqli_error($conn));
							$successMsg = $objName . " has been registered successfully";
							$data = json_encode(array('Status' => true, 'Message' => $successMsg));
						} else {
							$successMsg = $objName . " has been registered successfully";
							$data = json_encode(array('Status' => true, 'Message' => $successMsg));
						}
					} else {
						$errorMsg = mysqli_error($conn);
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}
			}
		} else if ($commandType == "update_command") {
			// Update Query section goes here .....
			$cm = kuceliAsalka($cm, $ereyFure);
			$getColumns = explode("###", $cm);
			if ($hasFile == "Yes") {
				//Update if the query contains images and other files ...
				$imageNames = explode("###", $photoNames);
				$documentNames = explode("###", $docNames);
				$fileList = explode("###", $files);
				$fileValues = "";
				$p = 0;
				$d = 0;
				foreach ($fileList as $file) {
					if (substr($file, 0, 5) == "photo") {
						if (isset($_FILES[$file])) {
							$checked_file = check_every_file($file);
							$fileInfo = explode("###", $checked_file);
							if (count($errorList) > 0) {
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							} else {
								$fileNewName =  $valID . "_" . $p . "." . $fileInfo[2];
								$photoPath = "../uploads/photos/" . $fileNewName;
								move_uploaded_file($_FILES[$file]['tmp_name'], $photoPath);
								$fileValues .= "uploads/photos/" . $fileNewName . "###";
							}
						} else {
							$fileValues .= $imageNames[$p] . "###";
						}
						$p++;
					} else {
						if (isset($_FILES[$file])) {
							$checked_file = check_every_file($file);
							$fileInfo = explode("###", $checked_file);
							if (count($errorList) > 0) {
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							} else {
								$fileNewName =  $valID . "_" . $d . "." . $fileInfo[2];
								$photoPath = "../uploads/documents/" . $fileNewName;
								move_uploaded_file($_FILES[$file]['tmp_name'], $photoPath);
								$fileValues .= "uploads/documents/" . $fileNewName . "###";
							}
						} else {
							$fileValues .= $documentNames[$d] . "###";
						}
						$d++;
					}
				}
				$vl .= "###" . substr($fileValues, 0, -3);
				$getValues = explode("###", $vl);
				$colVal = "";
				for ($i = 0; $i <= count($getValues) - 1; $i++) {
					if ($i == 0) {
						continue;
					}
					$colVal .= " " . $getColumns[$i] . " = " . "'" . mysqli_real_escape_string($conn, $getValues[$i]) . "',";
				}
				// echo "UPDATE ". $tn ." SET ". rtrim($colVal, ",") ." WHERE ". $getColumns[0] ." = '". $getValues[0] ."'";
				if (count($errorList) <= 0) {
					$updateQry = mysqli_query($conn, "UPDATE " . $tn . " SET " . rtrim($colVal, ",") . " WHERE " . $getColumns[0] . " = '" . $getValues[0] . "'");
					if ($updateQry) {
						$successMsg = $objName . " has been updated successfully";
						$data = json_encode(array('Status' => true, 'Message' => $successMsg));
					} else {
						$errorMsg = mysqli_error($conn);
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}
			} else {

				//Update if the query don't have files ...

				$colVal = "";
				for ($i = 0; $i <= count($getValues) - 1; $i++) {
					if ($i == 0) {
						continue;
					}
					$colVal .= " " . $getColumns[$i] . " = " . "'" . mysqli_real_escape_string($conn, $getValues[$i]) . "',";
				}
				// echo "UPDATE ". $tn ." SET ". rtrim($colVal, ",") ." WHERE ". $getColumns[0] ." = '". $getValues[0] ."'";
				if (count($errorList) <= 0) {
					$updateQry = mysqli_query($conn, "UPDATE " . $tn . " SET " . rtrim($colVal, ",") . " WHERE " . $getColumns[0] . " = '" . $getValues[0] . "'");
					if ($updateQry) {
						if ($tn == "customer_payments" || $tn == "charge_pay_salaries" || $tn == "expenses" || $tn == "charge_pay_contributions") {
							if ($getValues[1] == "0") {
								//Delete this transaction from the financial_transactions Table
								mysqli_query($conn, "DELETE FROM account_transactions WHERE referenceID = '" . mysqli_real_escape_string($conn, $getValues[0]) . "'") or die(mysqli_error($conn));
								$successMsg = $objName . " has been updated successfully";
								$data = json_encode(array('Status' => true, 'Message' => $successMsg));
							}
							$successMsg = $objName . " has been updated successfully";
							$data = json_encode(array('Status' => true, 'Message' => $successMsg));
						} else {
							$successMsg = $objName . " has been updated successfully";
							$data = json_encode(array('Status' => true, 'Message' => $successMsg));
						}
					} else {
						$errorMsg = mysqli_error($conn);
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}
			}
		} else if ($commandType == "delete_command") {
			//Delete Query Section... 
			$cm = kuceliAsalka($cm, $ereyFure);
			if (count($errorList) <= 0) {
				$delQry = mysqli_query($conn, "DELETE FROM " . $tn . " WHERE " . $cm . " = '" . $vl . "'");
				if ($delQry) {
				    if ($tn == "expenses" || $tn == "tenant_receipts" || $tn == "landlord_receipts") {
						//Delete this transaction from the financial_transactions Table
						mysqli_query($conn, "DELETE FROM account_transactions WHERE referenceID = '" . mysqli_real_escape_string($conn, $vl) . "'") or die(mysqli_error($conn));
						$successMsg = $objName . " has been deleted successfully";
						$data = json_encode(array('Status' => true, 'Message' => $successMsg));
					} else {
						$successMsg = $objName . " has been deleted successfully";
						$data = json_encode(array('Status' => true, 'Message' => $successMsg));
					}
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			}
		}
		echo $data;
	}

	// -------------- Fetch parameterized every thing ---------------------------------
	function fetch_parameterized_everything($conn) {
		extract($_POST);
		global $ereyFure;
		$dn = kuceliAsalka($dn, $ereyFure);
		$tn = kuceliAsalka($tn, $ereyFure);
		$cm = kuceliAsalka($cm, $ereyFure);
		$data = array();
		$colNo = mysqli_query($conn, "SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . $dn . "' AND TABLE_NAME = '" . $tn . "'") or die(mysqli_error($conn));
		$col_no = mysqli_fetch_array($colNo);
		$object_ID = mysqli_real_escape_string($conn, $objectID);
		$fetchInfo = mysqli_query($conn, "SELECT * FROM " . $tn . " WHERE " . $cm . " = '" . $object_ID . "'") or die(mysqli_error($conn));
		$all_Info = "";
		if (mysqli_num_rows($fetchInfo) >= 1) {
			$get_info = mysqli_fetch_array($fetchInfo);
			for ($i = 0; $i <= $col_no[0] - 1; $i++) {
				$all_Info .= $get_info[$i] . "###";
			}
			$all_Info = substr($all_Info, 0, -3);
		} else {
			$all_Info = "No Information Found";
		}
		$data = json_encode(array('Status' => true, 'Message' => $all_Info));
		echo $data;
	}

	// Fetch parameterless every thing ------------------------------------------------
	function fetch_parameterless_everything($conn) {
		extract($_POST);
		global $ereyFure;
		$dn = kuceliAsalka($dn, $ereyFure);
		$tn = kuceliAsalka($tn, $ereyFure);
		$data = array();
		$colNo = mysqli_query($conn, "SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . $dn . "' AND TABLE_NAME = '" . $tn . "'") or die(mysqli_error($conn));
		$col_no = mysqli_fetch_array($colNo);
		$fetchInfo = mysqli_query($conn, "SELECT *  FROM " . $tn . "") or die(mysqli_error($conn));
		$all_Info = "";
		if (mysqli_num_rows($fetchInfo) >= 1) {
			while ($get_info = mysqli_fetch_array($fetchInfo)) {
				for ($i = 0; $i <= $col_no[0] - 1; $i++) {
					$all_Info .= $get_info[$i] . "***";
				}
				$all_Info = substr($all_Info, 0, -3) . "###";
			}
			$all_Info = substr($all_Info, 0, -3);
		} else {
			$all_Info = "No information found";
		}
		$data = json_encode(array('Status' => true, 'Message' => $all_Info));
		echo $data;
	}

	// Fill Active Employee Name
	function fill_active_employees($conn) {
		$returned_data = array();
		$data = array();
		$employeeIdd = mysqli_query($conn, "SELECT * FROM employees WHERE employeePosition != 'PS0001'AND employeeStatus = 1") or die(mysqli_error($conn));
		if ($employeeIdd) {
			$num_rows = mysqli_num_rows($employeeIdd);
			if ($num_rows > 0) {
				while ($row = mysqli_fetch_array($employeeIdd)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Employee Not Found"));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// =========================== Fill Gateway Name in Accounts =================
	function fetch_gateway_name_data($conn) {
		$returned_data = array();
		$data = array();
		extract($_POST);
		$gatewayResult = mysqli_query($conn, "SELECT * FROM payment_gateways WHERE gatewayType = '" . mysqli_real_escape_string($conn, $selectedAccountType) . "'");
		if ($gatewayResult) {
			if (mysqli_num_rows($gatewayResult) > 0) {
				while ($row = mysqli_fetch_assoc($gatewayResult)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Payment Gateways Not Found"));
			}
			echo $data;
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
	}

	// =========================== Fill Account Details ==========================
	function fill_account_details($conn) {
		$accounts_data = array();
		$data = array();
		$bankAccountIdd = mysqli_query($conn, "SELECT account_numbers.accountNoID, payment_gateways.gatewayType, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber FROM account_numbers JOIN payment_gateways ON (account_numbers.gatewayID = payment_gateways.gatewayID) ORDER BY payment_gateways.gatewayName ASC") or die(mysqli_error($conn));
		if ($bankAccountIdd) {
			if (mysqli_num_rows($bankAccountIdd) > 0) {
				while ($row = mysqli_fetch_array($bankAccountIdd)) {
					$accounts_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $accounts_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Accounts Not Found"));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// ----------- Fill account number when account name is changed --------------
	function fetch_account_number($conn) {
		$data = array();
		extract($_POST);
		$getAccountNumber = mysqli_query($conn, "SELECT accountNumber FROM account_numbers WHERE accountNoID  = '" . mysqli_real_escape_string($conn, $selectedAccountNo) . "'");
		if ($getAccountNumber) {
			if (mysqli_num_rows($getAccountNumber) > 0) {
				$bank_acc_rs = mysqli_fetch_array($getAccountNumber);
				$account_number = $bank_acc_rs[0];
				$data = json_encode(array('Status' => true, 'Message' => $account_number));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => 'Account Number Not Found'));
			}
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
		echo $data;
	}

	// --------------------------- Check account balance -------------------------
	function check_account_balance($conn) {
		$data = array();
		extract($_POST);
		$checkAccountBalance = mysqli_query($conn, "SELECT IFNULL(SUM(depositedAmount), 0) - IFNULL(SUM(withdrawalAmount), 0) 'AccountBalance' FROM account_transactions WHERE accountNoID = '" . mysqli_real_escape_string($conn, $selectedAccountNo) . "' GROUP BY accountNoID") or die(mysqli_error($conn));
		if ($checkAccountBalance) {
			if (mysqli_num_rows($checkAccountBalance) >= 0) {
				$acc_bal_rs = mysqli_fetch_array($checkAccountBalance);
				$account_balance = $acc_bal_rs[0];
				$data = json_encode(array('Status' => true, 'Message' => $account_balance));
			}
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
		echo $data;
	}

	// =========================== Start of Change Password ===================================================
	function change_password($conn) {
		global $ereyFure;
		global $errorList;

		$data = array();
		extract($_POST);

		if ($newPassChange != $confPassChange) {
			$errorMsg = "Sorry!! Passwords are not matching, please check it...";
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			$getUsernamePassword = mysqli_query($conn, "SELECT * FROM system_users WHERE userID = '" . $_SESSION['userIdd'] . "'");
			if ($getUsernamePassword) {
				if (mysqli_num_rows($getUsernamePassword) > 0) {
					$user_pass_details = mysqli_fetch_array($getUsernamePassword);
					$entered_user_password = $oldPassChange;
					$user_stored_enc_pass = $user_pass_details[4];
					$stored_dec_password = kuceliAsalka($user_stored_enc_pass, $ereyFure);
					if ($entered_user_password === $stored_dec_password) {
						$changePass = mysqli_query($conn, "UPDATE system_users SET password = '" . mysqli_real_escape_string($conn, bedelXogta($newPassChange, $ereyFure)) . "' WHERE userID = '" . $_SESSION['userIdd'] . "'");
						if ($changePass) {
							$data = json_encode(array('Status' => true, 'Message' => 'Password has been changed successfully'));
						} else {
							$errorMsg = mysqli_error($conn);
							$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
						}
					} else {
						$errorMsg = "Old password is wrong, please check and write again";
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				} else {
					$errorMsg = "Sorry, <b>" . $user_name . "</b> does not exist in the system_users list";;
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}

			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		}

		echo $data;
	}
	// =========================== End of Change Password ==============================================================

	// ========================== Start of Enable 2 step verification starts here ======================================

	function enable_disable_2step_verification($conn)
	{

		global $errorList;

		$get2StepVerificationStatus = mysqli_query($conn, "SELECT twoStepVerification FROM system_users WHERE userID = '" . mysqli_real_escape_string($conn, $_SESSION["userIdd"]) . "'");

		if (mysqli_num_rows($get2StepVerificationStatus) > 0) {

			$verificationStatus = mysqli_fetch_array($get2StepVerificationStatus);

			if ($verificationStatus[0] == 1) {

				$update_2step_verification_status = mysqli_query($conn, "UPDATE system_users SET twoStepVerification = 0 WHERE userID = '" . mysqli_real_escape_string($conn, $_SESSION["userIdd"]) . "'") or die(mysqli_error($conn));
				if ($update_2step_verification_status) {
					$data = json_encode(array('Status' => true, 'Message' => '2StepVerificationDisabled'));
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else if ($verificationStatus[0] == 0) {

				$update_2step_verification_status = mysqli_query($conn, "UPDATE system_users SET twoStepVerification = 1 WHERE userID = '" . mysqli_real_escape_string($conn, $_SESSION["userIdd"]) . "'") or die(mysqli_error($conn));
				if ($update_2step_verification_status) {
					$data = json_encode(array('Status' => true, 'Message' => '2StepVerificationEnabled'));
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			}
		} else {

			$errorMsg = "Verification failed, try again";
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}

		echo $data;
	}

	// ========================== End of Enable 2 Step Verification ===========================================

	// =========================== Start of Update Profile ====================================================
	function updateUserProfile($conn)
	{

		$data = array();

		$fullN = mysqli_real_escape_string($conn, $_POST['updateFullName']);
		$alreadyExistPath = mysqli_real_escape_string($conn, $_POST['updateUserPhotoPath']);

		if (!is_uploaded_file($_FILES['updateUserPhoto']['tmp_name'])) {

			$updateProfile = mysqli_query($conn, "UPDATE employees SET empName = '" . $fullN . "', employeePhoto = '" . $alreadyExistPath . "' WHERE empID IN (SELECT empID FROM system_users WHERE userID = '" . $_SESSION['userIdd'] . "')");
			if ($updateProfile) {
				$_SESSION['fullName'] = $fullN;
				$_SESSION['userPhoto'] = $alreadyExistPath;
				$data = json_encode(array('Status' => true, 'Message' => 'Your profile has been updated successfully...'));
			} else {
				$errorMsg = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
			}
		} else {

			$allowedExt = array("jpg", "jpeg", "JPEG", "png", "gif", "JPG", "PNG", "GIF");
			$filename = $_FILES['updateUserPhoto']['name'];
			$mypicExt = pathinfo($filename, PATHINFO_EXTENSION);
			//$tmpExtension = explode(".", $filename);
			//$photoExtension = end($tmpExtension);
			$photoNewName = $_SESSION['userIdd'] . "_UP" . "." . $mypicExt;
			$path = 'uploads/photos/' . $photoNewName;
			$imageSize = $_FILES['updateUserPhoto']['size'];

			if (in_array($mypicExt, $allowedExt)) {

				if ($imageSize < 1000000) {

					move_uploaded_file($_FILES['updateUserPhoto']['tmp_name'], "../" . $path);
					$updateProfile = mysqli_query($conn, "UPDATE employees SET empName = '" . $fullN . "', employeePhoto = '" . mysqli_real_escape_string($conn, $path) . "' WHERE empID IN (SELECT empID FROM system_users WHERE userID = '" . $_SESSION['userIdd'] . "')");
					if ($updateProfile) {
						$_SESSION['fullName'] = $fullN;
						$_SESSION['userPhoto'] = $path;
						$data = json_encode(array('Status' => true, 'Message' => 'Your profile has been updated successfully...'));
					} else {
						$errorMsg = mysqli_error($conn);
						$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
					}
				} else {
					$data = json_encode(array('Status' => false, 'Message' => 'Sorry!! Profile photo size can not be larger than 1 MB'));
				}
			} else {
				$data = json_encode(array('Status' => false, 'Message' => 'Only JPG, PNG, GIF type photos are allowed'));
			}
		}

		echo $data;
	}

	// =========================== End of Update Profile =============================

	// ========================== Start of Salaries Section ==========================
	//Get the list of employees to charge salary for
	function fetch_employee_charge_salary($conn) {
		extract($_POST);
		$getEmpToChargeSalary = mysqli_query($conn, "SELECT empID, empName, titlePosition, salary FROM employees WHERE empID NOT IN (SELECT empID FROM charge_pay_salaries WHERE salaryMonth = '" . $salMonthSalChar . "' AND (transactionType = '0' OR transactionType = '1') AND transactionStatus = '1') AND titlePosition <> 0 AND empStatus <> '0'");
		if ($getEmpToChargeSalary) {
			$num_row_emp = mysqli_num_rows($getEmpToChargeSalary);
			if ($num_row_emp > 0) {	?>
				<div class="tile">
					<div class="tile-body">
						<div class="row" style="margin-left: 0px; margin-right: 0px;" id="chargeSalariesPrintArea">
							<div class="col-md-12">
								<div class="table-responsive">
									<table class="table table-striped table-bordered table-sm" id="chargeEmployeesSalariesTable">
										<thead>
											<tr class="bg-info text-white text-center">
												<th><input type="checkbox" class="form-check-input" name="empChargeCheckAll" id="empChargeCheckAll" /> Check All</th>
												<th>Serial</th>
												<th>Employee Name</th>
												<th>Position</th>
												<th>Salary ($)</th>
												<th>Charged Month</th>
											</tr>
										</thead>
										<tbody class="allEmpCharge">
											<?php
												$i = 1;
												$positions_array = array("0", "Admin", "Finance", "Registrar");
												while ($result = mysqli_fetch_array($getEmpToChargeSalary)) { ?>
													<tr>
														<td align="center"><input type="checkbox" class="form-check-input" name="empChargeCheck"
																id="empChargeCheck" value="<?php echo $result[0]; ?>" /></td>
														<td align="center"><?php echo $i; ?></td>
														<td align="left"><?php echo $result[1]; ?></td>
														<td align="left"><?php echo $positions_array[$result[2]]; ?></td>
														<td align="center"><?php echo "$ " . number_format($result[3], 2); ?></td>
														<td align="center"><?php echo $salMonthSalChar ?></td>
													</tr><?php
													$i++;
												}
											?>
										</tbody>
									</table>
								</div>
								<script type="text/javascript">
								$('#chargeEmployeesSalariesTable').DataTable({
									"pageLength": 100
								});
								</script>
							</div>
						</div>

					</div>
				</div><?php
			} else {
				?><div class="tile">
					<div class="tile-body">
						<br />
						<div class="row">
							<div class="col-md-12" style="margin: 0px;">
								<center>
									<h5 style="font-family: 'Poppins'; color: maroon; font-weight: normal">Employee(s) not found</h5>
								</center>
							</div>
						</div>
						<br />
					</div>
				</div><?php
			}
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<center>
								<h3 style="font-family: 'Poppins'; color: maroon; font-weight: normal">
									<?php echo mysqli_error($conn); ?></h3>
							</center>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// ----------------------- Charge Employee Salaries ------------------------------
	function charge_employee_salaries($conn) {
		$data = array();
		extract($_POST);
		$numOfChargedEmp = 0;
		$selectedEmployees = explode("###", $embToBeCharged);
		foreach ($selectedEmployees as $empl) {
			//Generate New ID for the current inserted row....
			$getMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM charge_pay_salaries") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxID) > 0) {
				$maxID = mysqli_fetch_array($getMaxID);
				$curMaxID = $maxID[0] + 1;
				$generatedID = "CHS" . $curMaxID . "-" . date("Y");
			} else {
				$curMaxID = 1;
				$generatedID = "CHS" . $curMaxID . "-" . date("Y");
			}
			$employee_id = $empl;
			$getEmpSal = mysqli_query($conn, "SELECT salary FROM employees WHERE empID = '" . mysqli_real_escape_string($conn, $employee_id) . "'") or die(mysqli_error($conn));
			$emp_result = mysqli_fetch_array($getEmpSal);
			$salary_description = "Charge of " . $salChargeMonth . ", Ref: " . $generatedID;
			$charged_sal = $emp_result['salary'];
			$regDatee = date("Y-m-d H:i:s");
			mysqli_query($conn, "INSERT INTO charge_pay_salaries VALUES ('', '" . $generatedID . "', '" . $employee_id . "', '" . $salChargeMonth . "', '-', '" . $charged_sal . "', '0', '0', '1', '" . $salary_description . "', '" . $_SESSION['userIdd'] . "',  '" . $regDatee . "', '-', '-')");
			$numOfChargedEmp++;
		}
		if ($numOfChargedEmp == 1) {
			$feedBack = $numOfChargedEmp . " employee salary has been charged for " . $salChargeMonth;
		} else if ($numOfChargedEmp > 1) {
			$feedBack = $numOfChargedEmp . " employee salaries has been charged for " . $salChargeMonth;
		}
		$data = json_encode(array('Status' => true, 'Message' => $feedBack));
		echo $data;
	}

	// ----------------------- Fill employee information in salaries form -----------
	function fetch_employee_data($conn) {
		$fetched_employee_result = array();
		$data = array();
		extract($_POST);
		$empResult = mysqli_query($conn, "SELECT titlePosition FROM `employees` WHERE empID = '" . mysqli_real_escape_string($conn, $thisEmp) . "'");
		if ($empResult) {
			if (mysqli_num_rows($empResult) > 0) {
				while ($row = mysqli_fetch_assoc($empResult)) {
					$fetched_employee_result[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $fetched_employee_result));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Data Not Found"));
			}
			echo $data;
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
	}

	// ------------- Fill employee charged salary and the remaining balance ---------
	function fetch_employee_charged_remain($conn) {
		$charged_amount = 0;
		$total_paid_salary = 0;
		$remaining_salary = 0;
		$data = array();
		extract($_POST);
		$getChargedSalaryAmount = mysqli_query($conn, "SELECT * FROM charge_pay_salaries WHERE empID = '" . mysqli_real_escape_string($conn, $employeeIdddd) . "' AND salaryMonth = '" . mysqli_real_escape_string($conn, $selectedSalaryMonth) . "' AND transactionType = '0' AND transactionStatus  = '1'");
		if ($getChargedSalaryAmount) {
			if (mysqli_num_rows($getChargedSalaryAmount) > 0) {
				$charged_emp_rs = mysqli_fetch_array($getChargedSalaryAmount);
				$employeee_id = $charged_emp_rs[2];
				$charged_salary_month = $charged_emp_rs[3];
				$charged_amount = $charged_emp_rs[5];
				//Check wether this employee has taken the salary of this month or not
				$getTotalPaidSalary = mysqli_query($conn, "SELECT * FROM charge_pay_salaries WHERE empID = '" . mysqli_real_escape_string($conn, $employeee_id) . "' AND salaryMonth = '" . mysqli_real_escape_string($conn, $charged_salary_month) . "' AND transactionType = '1' AND transactionStatus  = '1'");
				if ($getTotalPaidSalary) {
					if (mysqli_num_rows($getTotalPaidSalary) >= 0) {
						//Calculate the total amount of salary taken by the employee (if there are advanced salaries)
						while ($taken_salary_rs = mysqli_fetch_array($getTotalPaidSalary)) {
							$total_paid_salary += $taken_salary_rs[6];
						}
						$remaining_salary = $charged_amount - $total_paid_salary;
						$charged_remain = $charged_amount . "###" . $remaining_salary;
						$data = json_encode(array('Status' => true, 'Message' => $charged_remain));
					}
				} else {
					$erroMsg = mysqli_error($conn);
					$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
				}
			} else {
				$charged_amount = 0;
				$remaining_salary = 0;
				$charged_remain = $charged_amount . "###" . $remaining_salary;
				$data = json_encode(array('Status' => false, 'Message' => $charged_remain));
			}
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
		echo $data;
	}

	// -------------- Pay salary from the employee-salary page ----------------------  
	function pay_employee_salary($conn) {
		$data = array();
		global $errorList;
		$total_paid_salary = 0;
		extract($_POST);
		//Check first if the salary of this month is charged for this employee or not
		$checkChargeExistance = mysqli_query($conn, "SELECT * FROM charge_pay_salaries WHERE empID = '" . mysqli_real_escape_string($conn, $employeeIdd) . "' AND salaryMonth = '" . mysqli_real_escape_string($conn, $salaryMonth) . "' AND transactionType = '0' AND transactionStatus  = '1'");
		if ($checkChargeExistance) {
			if (mysqli_num_rows($checkChargeExistance) > 0) {
				$charged_emp_rs = mysqli_fetch_array($checkChargeExistance);
				$employeee_id = $charged_emp_rs[2];
				$charged_salary_month = $charged_emp_rs[3];
				$charged_amount = $charged_emp_rs[5];
				//Check wether this employee has taken the salary of this month or not
				$checkIfSalaryTaken = mysqli_query($conn, "SELECT * FROM charge_pay_salaries WHERE empID = '" . mysqli_real_escape_string($conn, $employeee_id) . "' AND salaryMonth = '" . mysqli_real_escape_string($conn, $charged_salary_month) . "' AND transactionType = '1' AND transactionStatus  = '1'");
				if ($checkIfSalaryTaken) {
					if (mysqli_num_rows($checkIfSalaryTaken) >= 0) {
						//Calculate the total amount of salary taken by the employee (if there are advanced salaries)
						while ($taken_salary_rs = mysqli_fetch_array($checkIfSalaryTaken)) {
							$total_paid_salary += $taken_salary_rs[6];
						}
						if ($total_paid_salary == 0 && ($total_paid_salary + $paidAmmount) > $charged_amount) {
							$errorMsg = "A total of $" . $charged_amount . " was charged to this employee for salary";
							$errorList[] = $errorMsg;
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						} else if ($total_paid_salary > 0 && ($total_paid_salary + $paidAmmount) > $charged_amount) {
							$actual_remain_amount = $charged_amount - $total_paid_salary;
							$errorMsg = "This employee has  $" . $actual_remain_amount . " remaining salary balance";
							$errorList[] = $errorMsg;
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						} else if (($total_paid_salary + $paidAmmount) <= $charged_amount) {
							//Generate New ID for the current inserted row....
							$getMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM charge_pay_salaries") or die(mysqli_error($conn));
							if (mysqli_num_rows($getMaxID) > 0) {
								$maxID = mysqli_fetch_array($getMaxID);
								$curMaxID = $maxID[0] + 1;
								$generatedID = "SPY" . $curMaxID . "-" . date("Y");
							} else {
								$curMaxID = 1;
								$generatedID = "SPY" . $curMaxID . "-" . date("Y");
							}
							if (count($errorList) <= 0) {
								$registerSalaryPayment = mysqli_query($conn, "INSERT INTO charge_pay_salaries VALUES ('', '" . mysqli_real_escape_string($conn, $generatedID) . "', '" . mysqli_real_escape_string($conn, $employeeIdd) . "', '" . mysqli_real_escape_string($conn, $salaryMonth) . "', '" . mysqli_real_escape_string($conn, $salaryWithdrawalAccount) . "', '0', '" . mysqli_real_escape_string($conn, $paidAmmount) . "', '1', '1', '" . mysqli_real_escape_string($conn, $salDescription) . "', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '" . mysqli_real_escape_string($conn, $salaryPaymentDate) . "', '-', '-')");
								if ($registerSalaryPayment) {
									//Save Salary Payment Transaction into account_transactions Table
									//Generate New ID for the current inserted row....
									$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
									if (mysqli_num_rows($getTransactionMaxID) > 0) {
										$transMaxID = mysqli_fetch_array($getTransactionMaxID);
										$currentMaxID = $transMaxID[0] + 1;
										$generatedTransactionID = "TR" . $currentMaxID . "-" . date("Y");
									} else {
										$currentMaxID = 1;
										$generatedTransactionID = "TR" . $currentMaxID . "-" . date("Y");
									}
									mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . mysqli_real_escape_string($conn, $salaryWithdrawalAccount) . "', '" . mysqli_real_escape_string($conn, $paidAmmount) . "', '0', '" . mysqli_real_escape_string($conn, $generatedID) . "', '" . mysqli_real_escape_string($conn, $salDescription) . "', '1', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '" . mysqli_real_escape_string($conn, $salaryPaymentDate) . "', '-', '-')") or die(mysqli_error($conn));
									$data = json_encode(array('Status' => true, 'Message' => "Salary payment has been registered successfully"));
								} else {
									$errorMsg = mysqli_error($conn);
									$errorList[] = $errorMsg;
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								}
							}
						}
					}
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				$getFeedBack = "The salary of " . $salaryMonth . " has not been charged for this employee";
				$errorList[] = $getFeedBack;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	// ========================== End of Salaries Section ========================

	// ================ Start of System Special Functions ========================================

	// ================ START OF TENANTS MODULE ==================================================
	
	
	// Fetch Tenant Maintenance Request Admin
	function fetch_tenant_maintenance_request_admin_chat_box($conn) {

		extract($_POST);
		$request_tracking_number = mysqli_real_escape_string($conn, $request_tracking_number);
		$_SESSION['maintenanceRequestTrackingIdd'] = $request_tracking_number;
		$reportQuery = mysqli_query($conn, "SELECT * FROM request_messages WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' ORDER BY messageDate ASC");
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				while($report_rs = mysqli_fetch_array($reportQuery)) {
					if (substr($report_rs[5], 0, 2) != "TN") {
					    
					    // Messages from the Admin Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: right;">
									<div class="shadow bg-white text-dark" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
										<span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
									    </span>
									</div>
								</div>
							</div><?php
						} else {
    					    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: right;">
    				                    <div class="shadow bg-white text-dark" style="display: inline-block; max-width: 70%; padding: 7px 10px 0px 10px; border-radius: 15px 0px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
                                            <span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>    							        
    								    </div>
    							    </div>
    						    </div><?php
						    } else {
						        ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
						                <div class="shadow bg-white text-dark" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
						                    <?php echo nl2br($report_rs[2]); ?>
                                            <span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span> 								        
    								    </div>
								    </div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
								        <div class="shadow bg-white text-dark" style="max-width: 70%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
											<script>
												$(document).ready(function () {
													$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
												})
											</script>
											<?php
												$message_photos = explode("###", $report_rs[3]);
												foreach($message_photos as $photo) {
													?><div class="p-1">
														<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
													</div><?php
												}
											?>
                                            <span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span> 								        
    							        </div>
								    </div>
								</div><?php
							} 
				        }
						
					} else {
					    
					    // Messages from the Tenant Buddy
					    
						$getChattingTenantInfo = mysqli_query($conn, "SELECT tenants.tenantPhoto, tenants.tenantName, tenants.tenantLoginStatus
						FROM tenants
						WHERE tenants.tenantID = '". mysqli_real_escape_string($conn, $report_rs[5]) ."'") or die(mysqli_error($conn));
						if (mysqli_num_rows($getChattingTenantInfo) > 0) {
							$chatting_tenant_rs = mysqli_fetch_array($getChattingTenantInfo);
						}
						
						// Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: left;">
									<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								    <div class="align-top bg-success text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
									</div>
								</div>
							</div><?php
						} else {
						    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-success text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
                                ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    									<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
    								    <div class="align-top bg-success text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    										<?php echo nl2br($report_rs[2]); ?>
    									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    									</div>
    								</div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-success text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venoboxx".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
								</div><?php
						    }
						}

					}
				}
				if ($_SESSION['userTypeID'] != 'PS0001') {
				    mysqli_query($conn, "UPDATE request_messages SET messageStatus = '1' WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' AND messageSender <> '". $_SESSION['userIdd'] ."'") or die(mysqli_error($conn));
				}
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}
	
	// Fetch Live Tenant Maintenance Request (Admin)
	function fetch_live_tenant_maintenance_request_admin_chat_box($conn) {

		extract($_POST);
		$reportQuery = mysqli_query($conn, "SELECT * FROM request_messages WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' ORDER BY messageDate ASC");
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				while($report_rs = mysqli_fetch_array($reportQuery)) {
					if (substr($report_rs[5], 0, 2) != "TN") {
					    
					    // Messages from the Admin Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: right;">
									<div class="shadow bg-white text-dark" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
										<span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
									    </span>
									</div>
								</div>
							</div><?php
						} else {
    					    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: right;">
    				                    <div class="shadow bg-white text-dark" style="display: inline-block; max-width: 70%; padding: 7px 10px 0px 10px; border-radius: 15px 0px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
                                            <span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>    							        
    								    </div>
    							    </div>
    						    </div><?php
						    } else {
						        ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
						                <div class="shadow bg-white text-dark" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
						                    <?php echo nl2br($report_rs[2]); ?>
                                            <span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span> 								        
    								    </div>
								    </div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
								        <div class="shadow bg-white text-dark" style="max-width: 70%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
											<script>
												$(document).ready(function () {
													$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
												})
											</script>
											<?php
												$message_photos = explode("###", $report_rs[3]);
												foreach($message_photos as $photo) {
													?><div class="p-1">
														<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
													</div><?php
												}
											?>
                                            <span class="text-primary" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="fa fa-check <?php if ($report_rs[4] == 1) { echo "text-success"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span> 								        
    							        </div>
								    </div>
								</div><?php
							} 
				        }
						
					} else {
					    
					    // Messages from the Tenant Buddy
					    
						$getChattingTenantInfo = mysqli_query($conn, "SELECT tenants.tenantPhoto, tenants.tenantName, tenants.tenantLoginStatus
						FROM tenants
						WHERE tenants.tenantID = '". mysqli_real_escape_string($conn, $report_rs[5]) ."'") or die(mysqli_error($conn));
						if (mysqli_num_rows($getChattingTenantInfo) > 0) {
							$chatting_tenant_rs = mysqli_fetch_array($getChattingTenantInfo);
						}
						
						// Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: left;">
									<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								    <div class="align-top bg-success text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
									</div>
								</div>
							</div><?php
						} else {
						    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-success text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
                                ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    									<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
    								    <div class="align-top bg-success text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    										<?php echo nl2br($report_rs[2]); ?>
    									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    									</div>
    								</div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../admin_panel/". $chatting_tenant_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($chatting_tenant_rs[2] == 0) { echo "text-dark"; } else if ($chatting_tenant_rs[2] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-success text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../admin_panel/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venoboxx".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../admin_panel/".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../admin_panel/".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
								</div><?php
						    }
						}

					}
				}
                if ($_SESSION['userTypeID'] != 'PS0001') {
				    mysqli_query($conn, "UPDATE request_messages SET messageStatus = '1' WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' AND messageSender <> '". $_SESSION['userIdd'] ."'") or die(mysqli_error($conn));
				}
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Send Live Tenant Maintenance Request Live Message (Admin)
	function send_tenant_maintenance_request_live_message_admin($conn) {

		global $errorList;
		$data = array();
		extract($_POST);

		$maintenance_request_body = mysqli_real_escape_string($conn, $maintenance_request_body);

		$uploadedPhotoNames = "";

		if (!isset($_FILES['txtLiveMaintenanceAttachmentPhotosAdmin'])) {
			$uploadedPhotoNames = "NoPhoto###";
		} else {
			// Maintenance Request Photos count, check then upload
			$count_maintenance_request_photos = count($_FILES['txtLiveMaintenanceAttachmentPhotosAdmin']['name']);
			$photos_location = "../tenant/uploads/photos/";

			for($index = 0;$index < $count_maintenance_request_photos; $index++){
				if(isset($_FILES['txtLiveMaintenanceAttachmentPhotosAdmin']['name'][$index]) && $_FILES['txtLiveMaintenanceAttachmentPhotosAdmin']['name'][$index] != ''){
					$filename = $_FILES['txtLiveMaintenanceAttachmentPhotosAdmin']['name'][$index];
					$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
					$valid_ext = array('jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG'); 
					if(in_array($ext, $valid_ext)){
						$new_photo_name = "CRQMT". ($index + 1) ."_" . date("YmdHis") . "." . $ext;
						if(move_uploaded_file($_FILES['txtLiveMaintenanceAttachmentPhotosAdmin']['tmp_name'][$index], $photos_location.$new_photo_name)){
							$uploadedPhotoNames .= substr($photos_location.$new_photo_name, 3). "###";
						}
					} else {
						$errorMsg = "Upload only the allowed photo types";
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}
			}
		}

		//echo rtrim($uploadedPhotoNames, "###");

		$registerRequestMessage = mysqli_query($conn, "INSERT INTO request_messages VALUES (NULL, '". $_SESSION['maintenanceRequestTrackingIdd'] ."', '". $maintenance_request_body ."', '". rtrim($uploadedPhotoNames, "###") ."', 0, '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')");
		if($registerRequestMessage) {
			$data = json_encode(array('Status' => true, 'Message' => 'Message has been sent'));
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}

		echo $data;

	}

	// Search Tenant Short Messages (SMS) (Admin Portal)
	function search_tenant_short_messages_sms_admin($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$selected_message_subject = mysqli_real_escape_string($conn, $selected_message_subject);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
			// $selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}

		$generatedReportQuery = "SELECT bulk_sms.smsID, tenants.tenantName, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, bulk_sms.sentDate
		FROM bulk_sms
		JOIN tenants ON bulk_sms.receiverID = tenants.tenantID ";
		if ($selected_tenant_id != "" || $selected_message_subject != "" || $selected_date_type != 0) { $generatedReportQuery .= "WHERE ";}
		if ($selected_tenant_id != "") { 
			$generatedReportQuery .= "bulk_sms.receiverID = '". $selected_tenant_id ."' "; 
		}
		if ($selected_message_subject != "") {
			if ($selected_tenant_id != "") {
				$generatedReportQuery .= "AND bulk_sms.messageSubject = '". $selected_message_subject ."' "; 
			} else {
				$generatedReportQuery .= "bulk_sms.messageSubject = '". $selected_message_subject ."' "; 
			}
		}
		if ($selected_date_type != 0) {
			if ($selected_tenant_id != "" || $selected_message_subject != "") {
				$generatedReportQuery .= "AND bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}

		$generatedReportQuery .= "ORDER BY bulk_sms.smsID DESC";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="row mt-2 mb-2">
				<?php
					if ($selected_date_type == 0) {
						$date_type_label = "All Date";
						$tenant_sms_start_date = "-";
						$tenant_sms_end_date = "-";
					} else if ($selected_date_type == 1) {
						$date_type_label = "Today";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 2) {
						$date_type_label = "Yesterday";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 3) {
						$date_type_label = "Last 3 Days";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 4) {
						$date_type_label = "This Week";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 5) {
						$date_type_label = "Last 10 Days";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 6) {
						$date_type_label = "This Month";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 7) {
						$date_type_label = "This Year";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 8) {
						$date_type_label = "Customized Date";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					}
				?>
				<div class="col-md-5 pb-2">
					<h6 class="font-weight-bold">Message Subject</h6>
					<p><?php if ($selected_message_subject === "") { echo "-"; } else { echo $selected_message_subject; } ?></p>
				</div>
				<div class="col-md-3 pb-2">
					<h6 class="font-weight-bold">Date Type</h6>
					<p><?php echo $date_type_label; ?></p>
				</div>
				<div class="col-md-2 pb-2">
					<h6 class="font-weight-bold">Start Date</h6>
					<p><?php echo substr($tenant_sms_start_date, 0, 10); ?></p>
				</div>
				<div class="col-md-2 pb-2">
					<h6 class="font-weight-bold">End Date</h6>
					<p><?php echo substr($tenant_sms_end_date, 0, 10); ?></p>
				</div>							
			</div>
			<div class="table-responsive mt-1">
				<table class="table table-bordered table-hover table-sm" id="tenantBulkMessagesTable">
					<thead>
						<tr class="text-white bg-info">
							<th class="text-center">No</th>
							<th class="text-left">Tenant Name</th>
							<th class="text-left">Message Subject</th>
							<th class="text-left">Message Body</th>
							<th class="text-center">Status</th>
							<th class="text-center">Sent Date</th>
						</tr>
					</thead>
					<tbody>
						<?php
							$x = 1;
							while ($request_rs = mysqli_fetch_array($reportQuery)) { ?>
								<tr>
									<td class="text-center" width="5%"><?php echo $x; ?></td>
									<td class="text-left" width="20%"><?php echo $request_rs[1]; ?></td>
									<td class="text-left" width="15%"><?php echo $request_rs[2]; ?></td>
									<td class="text-justify"><a href="#" class="btnOpenTenantShortMessageContentDetailsModalAdmin" data-id="<?php echo $request_rs[0]; ?>" data-toggle="modal" data-target="#tenantShortMessageContentDetailsAdminModal"><?php if (strlen($request_rs[3]) >= 90) { echo substr($request_rs[3], 0, 90). " <strong>Read More...</strong>"; } else { echo $request_rs[3]; } ?></a></td>
									<td class="text-center" width="7%">
										<?php if ($request_rs[4] == 1) { ?><span class="badge text-success p-2"><i class="fa fa-check"></i> Sent</span><?php } ?>
									</td>
									<td class="text-center" width="12%"><?php echo substr($request_rs[5], 0, 16); ?></td>
								</tr><?php
								$x++;
							}
						?>
					</tbody>
				</table>
			</div><?php
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Short Messages (SMS) Not Found</h6>
						</div>
					</div>
				</div>
			</div><?php
		}
	}

	// Read Full Tenant Bulk Short Message Admin
	function fetch_tenant_short_message_content_details_admin($conn) {

		extract($_POST);
		$short_message_id = mysqli_real_escape_string($conn, $short_message_id);
		$generatedReportQuery = "SELECT bulk_sms.smsID, tenants.tenantName, bulk_sms.telephoneSentTo, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, system_users.Username, employees.employeeName, bulk_sms.sentDate
		FROM bulk_sms
		JOIN tenants ON bulk_sms.receiverID = tenants.tenantID
		JOIN system_users ON bulk_sms.senderUser = system_users.userID
		JOIN employees ON system_users.employeeID = employees.employeeID
		WHERE bulk_sms.smsID = '". $short_message_id ."'";
// 		echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				$report_rs = mysqli_fetch_array($reportQuery);
				?>
					<div class="row m-2" style="margin: 0xp;">
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-key"></i> Message ID</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[0]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Receiver</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[1]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-phone"></i> Mobile No</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo "+252 ". $report_rs[2]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-book"></i> Subject</strong></h6></div>
						<div class="col-md-8 pt-2 font-weight-bold"><?php echo $report_rs[3]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-envelope-open"></i> Content</strong></h6></div>
						<div class="col-md-8 pt-2" style="text-align: justify;"><?php echo $report_rs[4]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-info-circle"></i> Status</strong></h6></div>
						<div class="col-md-8 pt-2 text-success" style="text-align: justify;"><?php if ($report_rs[5] == 1) { echo "<i class='fa fa-check'></i> Sent"; } ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Sent By</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[6]. " (<strong>". $report_rs[7]. "</strong>)"; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-calendar"></i> Sent Date</strong></h6></div>
						<div class="col-md-8 p-2"><?php echo substr($report_rs[8], 0, 16); ?></div>
					</div>
				<?php
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Send Bulk Message Management Section 
	function send_manual_tenant_bulk_message($conn) {
		global $errorList;
		$data = array();

		$messageSubject = mysqli_real_escape_string($conn, $_POST['txtMessageSubjectSendTenantBulkShortMessage']);
		$messageBody = mysqli_real_escape_string($conn, $_POST['txtBulkMessageBodySendTenantBulkShortMessage']);
		
		if (count($errorList) <= 0) {
			
			if (count($_POST['cmbTenantNameSendTenantBulkShortMessage']) === 1 && $_POST['cmbTenantNameSendTenantBulkShortMessage'][0] === "All") {

				$getTenantInformation = mysqli_query($conn, "SELECT tenantID, tenantMobile  FROM tenants WHERE tenantStatus = '1'") or die(mysqli_error($conn));
				if (mysqli_num_rows($getTenantInformation) > 0) {
						
					while ($tenant_info_rs = mysqli_fetch_array($getTenantInformation)) {
						$tenant_idd = $tenant_info_rs[0];
						$tenant_tell = $tenant_info_rs[1];
						
						//Send manual message to the customer through mobile
			
						$data = array(
							"refid" => "0", "mobile" => $tenant_tell, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
				
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $tenant_idd . "', '" . $tenant_idd . "', '". $messageSubject ."', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $tenant_tell ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
						
					}
					
				}

			} else {
				
				foreach ($_POST['cmbTenantNameSendTenantBulkShortMessage'] as $tenantt_iddd) {
					
					$getTenantInformation = mysqli_query($conn, "SELECT tenantID, tenantMobile  FROM tenants WHERE tenantID = '". mysqli_real_escape_string($conn, $tenantt_iddd) ."'") or die(mysqli_error($conn));
					if (mysqli_num_rows($getTenantInformation) > 0) {
						
						$tenant_info_rs = mysqli_fetch_array($getTenantInformation);
						$tenant_idd = $tenant_info_rs[0];
						$tenant_tell = $tenant_info_rs[1];
						
						//Send manual message to the tenant through mobile
		
						$data = array(
							"refid" => "0", "mobile" => $tenant_tell, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
				
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $tenant_idd . "', '" . $tenant_idd . "', '". $messageSubject ."', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $tenant_tell ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
					}
				}
			
			}

			$successMsg = "Message has been sent successfully";
			$data = json_encode(array('Status' => true, 'Message' => $successMsg));	
			
		}
		echo $data;
	}
	
	// Search Landlord Short Messages (SMS) (Admin Portal)
	function search_landlord_short_messages_sms_admin($conn) {
		extract($_POST);
		$selected_landlord_id = mysqli_real_escape_string($conn, $selected_landlord_id);
		$selected_message_subject = mysqli_real_escape_string($conn, $selected_message_subject);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
			// $selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}

		$generatedReportQuery = "SELECT bulk_sms.smsID, landlords.landlordName, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, bulk_sms.sentDate
		FROM bulk_sms
		JOIN landlords ON bulk_sms.receiverID = landlords.landlordID ";
		if ($selected_landlord_id != "" || $selected_message_subject != "" || $selected_date_type != 0) { $generatedReportQuery .= "WHERE ";}
		if ($selected_landlord_id != "") { 
			$generatedReportQuery .= "bulk_sms.receiverID = '". $selected_landlord_id ."' "; 
		}
		if ($selected_message_subject != "") {
			if ($selected_landlord_id != "") {
				$generatedReportQuery .= "AND bulk_sms.messageSubject = '". $selected_message_subject ."' "; 
			} else {
				$generatedReportQuery .= "bulk_sms.messageSubject = '". $selected_message_subject ."' "; 
			}
		}
		if ($selected_date_type != 0) {
			if ($selected_landlord_id != "" || $selected_message_subject != "") {
				$generatedReportQuery .= "AND bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}

		$generatedReportQuery .= "ORDER BY bulk_sms.smsID DESC";
// 		echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="row mt-2 mb-2">
				<?php
					if ($selected_date_type == 0) {
						$date_type_label = "All Date";
						$tenant_sms_start_date = "-";
						$tenant_sms_end_date = "-";
					} else if ($selected_date_type == 1) {
						$date_type_label = "Today";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 2) {
						$date_type_label = "Yesterday";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 3) {
						$date_type_label = "Last 3 Days";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 4) {
						$date_type_label = "This Week";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 5) {
						$date_type_label = "Last 10 Days";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 6) {
						$date_type_label = "This Month";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 7) {
						$date_type_label = "This Year";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					} else if ($selected_date_type == 8) {
						$date_type_label = "Customized Date";
						$tenant_sms_start_date = $selected_start_date;
						$tenant_sms_end_date = $selected_end_date;
					}
				?>
				<div class="col-md-5 pb-2">
					<h6 class="font-weight-bold">Message Subject</h6>
					<p><?php if ($selected_message_subject === "") { echo "-"; } else { echo $selected_message_subject; } ?></p>
				</div>
				<div class="col-md-3 pb-2">
					<h6 class="font-weight-bold">Date Type</h6>
					<p><?php echo $date_type_label; ?></p>
				</div>
				<div class="col-md-2 pb-2">
					<h6 class="font-weight-bold">Start Date</h6>
					<p><?php echo substr($tenant_sms_start_date, 0, 10); ?></p>
				</div>
				<div class="col-md-2 pb-2">
					<h6 class="font-weight-bold">End Date</h6>
					<p><?php echo substr($tenant_sms_end_date, 0, 10); ?></p>
				</div>							
			</div>
			<div class="table-responsive mt-1">
				<table class="table table-bordered table-hover table-sm" id="landlordBulkMessagesTable">
					<thead>
						<tr class="text-white bg-info">
							<th class="text-center">No</th>
							<th class="text-left">Landlord Name</th>
							<th class="text-left">Message Subject</th>
							<th class="text-left">Message Body</th>
							<th class="text-center">Status</th>
							<th class="text-center">Sent Date</th>
						</tr>
					</thead>
					<tbody>
						<?php
							$x = 1;
							while ($request_rs = mysqli_fetch_array($reportQuery)) { ?>
								<tr>
									<td class="text-center" width="5%"><?php echo $x; ?></td>
									<td class="text-left" width="20%"><?php echo $request_rs[1]; ?></td>
									<td class="text-left" width="15%"><?php echo $request_rs[2]; ?></td>
									<td class="text-justify"><a href="#" class="btnOpenLandlordShortMessageContentDetailsModalAdmin" data-id="<?php echo $request_rs[0]; ?>" data-toggle="modal" data-target="#landlordShortMessageContentDetailsAdminModal"><?php if (strlen($request_rs[3]) >= 90) { echo substr($request_rs[3], 0, 90). " <strong>Read More...</strong>"; } else { echo $request_rs[3]; } ?></a></td>
									<td class="text-center" width="7%">
										<?php if ($request_rs[4] == 1) { ?><span class="badge text-success p-2"><i class="fa fa-check"></i> Sent</span><?php } ?>
									</td>
									<td class="text-center" width="12%"><?php echo substr($request_rs[5], 0, 16); ?></td>
								</tr><?php
								$x++;
							}
						?>
					</tbody>
				</table>
			</div><?php
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Short Messages (SMS) Not Found</h6>
						</div>
					</div>
				</div>
			</div><?php
		}
	}

	// Read Full Landlord Bulk Short Message Admin
	function fetch_landlord_short_message_content_details_admin($conn) {

		extract($_POST);
		$short_message_id = mysqli_real_escape_string($conn, $short_message_id);
		$generatedReportQuery = "SELECT bulk_sms.smsID, landlords.landlordName, bulk_sms.telephoneSentTo, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, system_users.Username, employees.employeeName, bulk_sms.sentDate
		FROM bulk_sms
		JOIN landlords ON bulk_sms.receiverID = landlords.landlordID
		JOIN system_users ON bulk_sms.senderUser = system_users.userID
		JOIN employees ON system_users.employeeID = employees.employeeID
		WHERE bulk_sms.smsID = '". $short_message_id ."'";
// 		echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				$report_rs = mysqli_fetch_array($reportQuery);
				?>
					<div class="row m-2" style="margin: 0xp;">
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-key"></i> Message ID</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[0]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Receiver</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[1]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-phone"></i> Mobile No</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo "+252 ". $report_rs[2]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-book"></i> Subject</strong></h6></div>
						<div class="col-md-8 pt-2 font-weight-bold"><?php echo $report_rs[3]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-envelope-open"></i> Content</strong></h6></div>
						<div class="col-md-8 pt-2" style="text-align: justify;"><?php echo $report_rs[4]; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-info-circle"></i> Status</strong></h6></div>
						<div class="col-md-8 pt-2 text-success" style="text-align: justify;"><?php if ($report_rs[5] == 1) { echo "<i class='fa fa-check'></i> Sent"; } ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Sent By</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[6]. " (<strong>". $report_rs[7]. "</strong>)"; ?></div>
						<div class="col-md-4 pt-2 text-primary"><strong><h6><i class="fa fa-calendar"></i> Sent Date</strong></h6></div>
						<div class="col-md-8 p-2"><?php echo substr($report_rs[8], 0, 16); ?></div>
					</div>
				<?php
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Send Landlord Bulk Message Management Section 
	function send_manual_landlord_bulk_message($conn) {
		global $errorList;
		$data = array();

		$messageSubject = mysqli_real_escape_string($conn, $_POST['txtMessageSubjectSendLandlordBulkShortMessage']);
		$messageBody = mysqli_real_escape_string($conn, $_POST['txtBulkMessageBodySendLandlordBulkShortMessage']);
		
		if (count($errorList) <= 0) {
			
			if (count($_POST['cmbLandlordNameSendLandlordBulkShortMessage']) === 1 && $_POST['cmbLandlordNameSendLandlordBulkShortMessage'][0] === "All") {

				$getLandlordInformation = mysqli_query($conn, "SELECT landlordID, landlordMobile  FROM landlords WHERE landlordStatus = '1'") or die(mysqli_error($conn));
				if (mysqli_num_rows($getLandlordInformation) > 0) {
						
					while ($landlord_info_rs = mysqli_fetch_array($getLandlordInformation)) {
						$landlord_idd = $landlord_info_rs[0];
						$landlord_tell = $landlord_info_rs[1];
						
						//Send manual message to the landlords through mobile
			
						$data = array(
							"refid" => "0", "mobile" => $landlord_tell, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
				
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $landlord_idd . "', '" . $landlord_idd . "', '". $messageSubject ."', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $landlord_tell ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
						
					}
					
				}

			} else {
				
				foreach ($_POST['cmbLandlordNameSendLandlordBulkShortMessage'] as $landlordd_iddd) {
					
				    $getLandlordInformation = mysqli_query($conn, "SELECT landlordID, landlordMobile  FROM landlords WHERE landlordID = '". mysqli_real_escape_string($conn, $landlordd_iddd) ."' AND landlordStatus = '1'") or die(mysqli_error($conn));
					if (mysqli_num_rows($getLandlordInformation) > 0) {
						
						$landlord_info_rs = mysqli_fetch_array($getLandlordInformation);
						$landlord_idd = $landlord_info_rs[0];
						$landlord_tell = $landlord_info_rs[1];
						
						//Send manual message to the tenant through mobile
		
						$data = array(
							"refid" => "0", "mobile" => $landlord_tell, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
				
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $landlord_idd . "', '" . $landlord_idd . "', '". $messageSubject ."', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $landlord_tell ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
					}
				}
			
			}

			$successMsg = "Message has been sent successfully";
			$data = json_encode(array('Status' => true, 'Message' => $successMsg));	
			
		}
		echo $data;
	}
	
	// Send General Bulk Message
	function send_general_bulk_message($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		if (count($errorList) <= 0) {
		    
		    $getGeneralInformation = mysqli_query($conn, "SELECT employeeID, employeeName, employeeMobileNo FROM employees WHERE employeeStatus = '1' AND employeePosition != 'PS0001'
            UNION
            SELECT tenantID, tenantName, tenantMobile FROM tenants WHERE tenantStatus = '1'
            UNION
            SELECT landlordID, landlordName, landlordMobile FROM landlords WHERE landlordStatus = '1'") or die(mysqli_error($conn));
            if (mysqli_num_rows($getGeneralInformation) > 0) {
                while ($general_info_rs = mysqli_fetch_array($getGeneralInformation)) {
                    $data = array(
        				"refid" => "0", "mobile" => $general_info_rs[2], "message" => mysqli_real_escape_string($conn, $_POST['message_body']), "senderid" => "TEST", "validity" => 5, "delivery" => 6,
        			);
        			$data1 = json_encode($data);
        			$username = 'lighthouse1';
        			$password = 'Sja3wj5EhSr4tggVLJmcCw==';
        			$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
        			$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
        			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        			curl_setopt($ch, CURLOPT_HEADER, 1);
        			curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
        			curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
        			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        			$return = curl_exec($ch);
        			$return = explode(':', $return);
        	
        			// for ($i=0; $i < count($return) ; $i++) {
        			//     echo $i. ':' . $return[$i];
        			// }
        			$stat = explode('"', $return[17]);
        			$msg1 = explode(',', $return[20]);
        			$msg = explode('"', $msg1[0]);
        			// print_r($msg[1]);
        			
        			if ($stat[1] != 'Failed.') {
        				$registerBulkSMS = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '". mysqli_real_escape_string($conn, $general_info_rs[0]) ."', '". mysqli_real_escape_string($conn, $general_info_rs[0]) ."', '". mysqli_real_escape_string($conn, $_POST['message_subject']) ."', '" . mysqli_real_escape_string($conn, $_POST['message_body']) . "', '1', '". mysqli_real_escape_string($conn, $general_info_rs[2]) ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
        			    if ($registerBulkSMS) {
        			        $successMsg = "Messages has been sent successfully";
                            $data = json_encode(array('Status' => true, 'Message' => $successMsg));
        			    } else {
        			         $errorList[] = mysqli_error($conn);
                            $data = json_encode(array('Status' => false, 'Message' => $errorList));
        			    }
        			} else {
        				$errorList[] = $msg[1];
        				$data = json_encode(array('Status' => false, 'Message' => $errorList));
        			}
                }
            } else {
                $data = json_encode(array('Status' => false, 'Message' => 'Nobody To Send Message'));
            }


    	}
		echo $data;
	}
	
	// Send Administration Staff Bulk Message Management Section 
	function send_administration_staff_bulk_message($conn) {
		global $errorList;
		$data = array();
		$messageSubject = mysqli_real_escape_string($conn, $_POST['txtMessageSubjectSendAdministrationStaffBulkShortMessage']);
		$messageBody = mysqli_real_escape_string($conn, $_POST['txtBulkMessageBodySendAdministrationStaffBulkShortMessage']);
		if (count($errorList) <= 0) {
			if (count($_POST['cmbEmployeeIddNameSendAdministrationStaffBulkShortMessage']) === 1 && $_POST['cmbEmployeeIddNameSendAdministrationStaffBulkShortMessage'][0] === "All") {
				$getEmployeeInformation = mysqli_query($conn, "SELECT employeeID, employeeMobileNo FROM employees WHERE employeePosition != 'PS0001' AND employeeStatus = '1'") or die(mysqli_error($conn));
				if (mysqli_num_rows($getEmployeeInformation) > 0) {
					while ($employee_info_rs = mysqli_fetch_array($getEmployeeInformation)) {
						$employee_idd = $employee_info_rs[0];
						$employee_tell = $employee_info_rs[1];
						//Send manual message to the customer through mobile
						$data = array(
							"refid" => "0", "mobile" => $employee_tell, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $employee_idd . "', '" . $employee_idd . "', '". $messageSubject ."', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $employee_tell ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
						    $successMsg = "Message has been sent successfully";
			                $data = json_encode(array('Status' => true, 'Message' => $successMsg));
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
						
					}
					
				}

			} else {
				
				foreach ($_POST['cmbEmployeeIddNameSendAdministrationStaffBulkShortMessage'] as $employee_iddd) {
					$getEmployeeInformation = mysqli_query($conn, "SELECT employeeID, employeeMobileNo FROM employees WHERE employeeID = '". mysqli_real_escape_string($conn, $employee_iddd) ."'") or die(mysqli_error($conn));
					if (mysqli_num_rows($getEmployeeInformation) > 0) {
						$employee_info_rs = mysqli_fetch_array($getEmployeeInformation);
						$employee_idd = $employee_info_rs[0];
						$employee_tell = $employee_info_rs[1];
						//Send manual message to the customer through mobile
						$data = array(
							"refid" => "0", "mobile" => $employee_tell, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $employee_idd . "', '" . $employee_idd . "', '". $messageSubject ."', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $employee_tell ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
							$successMsg = "Message has been sent successfully";
			                $data = json_encode(array('Status' => true, 'Message' => $successMsg));	
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
					}
				}
			
			}
			
		}
		echo $data;
	}
	
	// Send Same Building Tenants Bulk Message
	function send_same_building_tenants_bulk_message($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		if (count($errorList) <= 0) {
		    $getBuidlingtenants = mysqli_query($conn, "SELECT rented_properties.tenantID
            FROM rental_properties
            JOIN buildings ON rental_properties.buildingID = buildings.buildingID
            JOIN rented_properties ON rental_properties.rentalPropertyID = rented_properties.rentalPropertyID
            WHERE buildings.buildingID = '". mysqli_real_escape_string($conn, $_POST['selected_building_id']) ."' AND rental_properties.propertyStatus = 2") or die(mysqli_error());
            if ($getBuidlingtenants) {
                if (mysqli_num_rows($getBuidlingtenants) > 0) {
                    while ($tenants_rs = mysqli_fetch_array($getBuidlingtenants)) {
                        // echo "SELECT tenantID, tenantMobile  FROM tenants WHERE tenantID = '". $tenants_rs[0] ."'";
                        $getTenantInformation = mysqli_query($conn, "SELECT tenantID, tenantMobile  FROM tenants WHERE tenantID = '". $tenants_rs[0] ."'") or die(mysqli_error($conn));
    					if (mysqli_num_rows($getTenantInformation) > 0) {
    						$tenant_info_rs = mysqli_fetch_array($getTenantInformation);
    						$tenant_idd = $tenant_info_rs[0];
    						$tenant_tell = $tenant_info_rs[1];
    						//Send manual message to the tenant through mobile
    						$data = array(
    							"refid" => "0", "mobile" => $tenant_tell, "message" => mysqli_real_escape_string($conn, $_POST['message_body']), "senderid" => "TEST", "validity" => 5, "delivery" => 6,
    						);
    						$data1 = json_encode($data);
    						$username = 'lighthouse1';
    						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
    						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
    						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
    						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    						curl_setopt($ch, CURLOPT_HEADER, 1);
    						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
    						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    						$return = curl_exec($ch);
    						$return = explode(':', $return);
    				
    						// for ($i=0; $i < count($return) ; $i++) {
    						//     echo $i. ':' . $return[$i];
    						// }
    						$stat = explode('"', $return[17]);
    						$msg1 = explode(',', $return[20]);
    						$msg = explode('"', $msg1[0]);
    						// print_r($msg[1]);
    						
    						if ($stat[1] != 'Failed.') {
    							mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . $tenant_idd . "', '" . $tenant_idd . "', '". mysqli_real_escape_string($conn, $_POST['message_subject']) ."', '" . mysqli_real_escape_string($conn, $_POST['message_body']) . "', '1', '". $tenant_tell ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
    						} else {
    							$errorList[] = $msg[1];
    							$data = json_encode(array('Status' => false, 'Message' => $errorList));
    						}
    					}
                    }
                    $successMsg = "Message has been sent successfully";
			        $data = json_encode(array('Status' => true, 'Message' => $successMsg));	
                } else {
                    $errorList[] = "Tenants Not Found";
				    $data = json_encode(array('Status' => false, 'Message' => $errorList));
                }
            } else {
                $errorList[] = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
            }
		}
		echo $data;
	}
	
	// Send External Buddies Bulk Message
	function send_external_buddies_bulk_message($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		if (count($errorList) <= 0) {

			//Send manual message to the tenant through mobile
			$data = array(
				"refid" => "0", "mobile" => mysqli_real_escape_string($conn, $_POST['to_mobile_number']), "message" => mysqli_real_escape_string($conn, $_POST['message_body']), "senderid" => "TEST", "validity" => 5, "delivery" => 6,
			);
			$data1 = json_encode($data);
			$username = 'lighthouse1';
			$password = 'Sja3wj5EhSr4tggVLJmcCw==';
			$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
			$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_HEADER, 1);
			curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$return = curl_exec($ch);
			$return = explode(':', $return);
	
			// for ($i=0; $i < count($return) ; $i++) {
			//     echo $i. ':' . $return[$i];
			// }
			$stat = explode('"', $return[17]);
			$msg1 = explode(',', $return[20]);
			$msg = explode('"', $msg1[0]);
			// print_r($msg[1]);
			
			if ($stat[1] != 'Failed.') {
				$registerBulkSMS = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '". mysqli_real_escape_string($conn, $_POST['to_mobile_number']) ."', '". mysqli_real_escape_string($conn, $_POST['to_mobile_number']) ."', '". mysqli_real_escape_string($conn, $_POST['message_subject']) ."', '" . mysqli_real_escape_string($conn, $_POST['message_body']) . "', '1', '". mysqli_real_escape_string($conn, $_POST['to_mobile_number']) ."', '" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
			    if ($registerBulkSMS) {
			        $successMsg = "Message has been sent successfully";
                    $data = json_encode(array('Status' => true, 'Message' => $successMsg));
			    } else {
			         $errorList[] = mysqli_error($conn);
                    $data = json_encode(array('Status' => false, 'Message' => $errorList));
			    }
			} else {
				$errorList[] = $msg[1];
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
    	}
		echo $data;
	}

	// Fetch tenant privileges -----------------------------------
	function fetch_tenant_privileges($conn) {
		extract($_POST);
		?>
			<div class="row">
				<div class="col-md-12">
					<h5><i class="fa fa-list-ul"></i> Tenant Privileges List</h5>
					<hr />
				</div>
			</div>
			<div class="table-responsive"> 
				<table class="table table-bordered table-hover table-sm">
					<?php
						
						$getTenantMenus = mysqli_query($conn, "SELECT DISTINCT tenant_menus.tenantMenuID, tenant_menus.mainMenuText, tenant_menus.mainMenuIcon, tenant_menus.mainMenuURL, tenant_privileges.tenantID, tenant_privileges.mainMenuMode FROM tenant_privileges JOIN tenant_menus ON (tenant_privileges.tenantMenuID = tenant_menus.tenantMenuID AND tenant_privileges.tenantID = '". mysqli_real_escape_string($conn, $selected_tenant_id) ."')") or die(mysqli_error($conn));
						if ($getTenantMenus) {
							if (mysqli_num_rows($getTenantMenus) > 0) {
								while ($main_rs = mysqli_fetch_array($getTenantMenus)) { ?>
									<tr>
										<td style="padding: 20px 0px 20px 20px;">
											<?php if ($main_rs[5] == "1") { ?>
												<input type="checkbox" checked="checked" class="form-control" style="height: 20px; width: 20px; display: inline;" name="cbxEnableDisableTenantMenu" id="cbxEnableDisableTenantMenu" data-id="<?php echo $main_rs[0]; ?>" data-src="<?php echo $selected_tenant_id; ?>"> &nbsp;&nbsp;
											<?php } else {?>
												<input type="checkbox" class="form-control" style="height: 20px; width: 20px; display: inline;" name="cbxEnableDisableTenantMenu" id="cbxEnableDisableTenantMenu" data-id="<?php echo $main_rs[0]; ?>" data-src="<?php echo $selected_tenant_id; ?>"> &nbsp;&nbsp;
											<?php } ?>											
											<i class="<?php echo $main_rs[2]; ?>"></i> &nbsp;&nbsp;<a href="<?php echo $main_rs[3]; ?>"><b><?php echo $main_rs[1]; ?></b></a>
										</td>
									</tr>
									<?php
								}
							} else {
								echo "<h6 class='mt-3 text-center text-danger'>Privileges Not Found</h6>";
							}
						} else {
							echo mysqli_error($conn);
						}									
					?>
				</table>
			</div>
		<?php
	}

	// Update tenant menu mode set enabled 
	function set_tenant_menu_enabled($conn) {
		$data = array();
		extract($_POST);
		$updateTenantMainMenu = mysqli_query($conn, "UPDATE tenant_privileges SET mainMenuMode = '1' WHERE tenantMenuID = '". mysqli_real_escape_string($conn, $selected_role_id) ."' AND tenantID = '". mysqli_real_escape_string($conn, $selected_tenant_id) ."'");
		if ($updateTenantMainMenu) {
			$data = json_encode(array('Status' => true, 'Message' => 'This menu is set to <b>enabled</b> mode'));
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Update tenant menu mode set disabled
	function set_tenant_menu_disabled($conn) {
		$data = array();
		extract($_POST);
		$updateTenantMainMenu = mysqli_query($conn, "UPDATE tenant_privileges SET mainMenuMode = '0' WHERE tenantMenuID = '". mysqli_real_escape_string($conn, $selected_role_id) ."' AND tenantID = '". mysqli_real_escape_string($conn, $selected_tenant_id) ."'");
		if ($updateTenantMainMenu) {
			$data = json_encode(array('Status' => true, 'Message' => 'This menu is set to <b>disabled</b> mode'));
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

		

	// ================ END OF TENANTS MODULE ====================================================
	
	// ================ START OF LANDLORDS MODULE ================================================
	// Landlord Properties Report
	function landlord_properties_report($conn) {
		extract($_POST);
		$selected_landlord_id = mysqli_real_escape_string($conn, $selected_landlord_id);
		$selected_status_id = mysqli_real_escape_string($conn, $selected_status_id);

		$generatedReportQuery = "SELECT rental_properties.propertyName, buildings.buildingName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, rental_properties.depositAmount, rental_properties.rentalPrice, rental_properties.registerDate, rental_property_statuses.propertyStatusDescription
        FROM rental_properties
        JOIN buildings ON rental_properties.buildingID = buildings.buildingID
        JOIN property_locations ON buildings.locationID = property_locations.locationID
        JOIN rental_property_statuses ON rental_properties.propertyStatus = rental_property_statuses.propertyStatusID ";
		if ($selected_landlord_id != "" || $selected_status_id != 0) { $generatedReportQuery .= "WHERE "; }
		if ($selected_landlord_id != "") { 
			$generatedReportQuery .= "rental_properties.landlordID = '". $selected_landlord_id ."' "; 
		}
		if ($selected_status_id != 0) {
			if ($selected_landlord_id != "") {
				$generatedReportQuery .= "AND rental_properties.propertyStatus = '". $selected_status_id ."' "; 
			} else {
				$generatedReportQuery .= "rental_properties.propertyStatus = '". $selected_status_id ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY buildings.buildingName ASC";
// 		echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printLandlordPropertiesReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="landlordPropertiesReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Landlord Properties Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<div class="col-md-6 pb-2">
											<h5 class="font-weight-bold">Property Type</h5>
											<h6 class="font-weight-normal">
												<?php 
													$getLandlordInformation = mysqli_query($conn, "SELECT landlordName, landlordMobile FROM landlords WHERE landlordID = '". $selected_landlord_id ."' ") or die(mysqli_error($conn));
													if (mysqli_num_rows($getLandlordInformation) > 0) {
														$landlord_info_rs = mysqli_fetch_array($getLandlordInformation);
														echo $landlord_info_rs[0]. " (". $landlord_info_rs[1]. ")";
													}
												?>
											</h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Property Status</h5>
											<h6 class="font-weight-normal">
											    <?php 
											        if ($selected_status_id == "") {
											            echo "-";
											        } else {
											            $getStatusDescriptions = mysqli_query($conn, "SELECT propertyStatusDescription FROM rental_property_statuses WHERE propertyStatusID = '". $selected_status_id ."' ") or die(mysqli_error($conn));
    													if (mysqli_num_rows($getStatusDescriptions) > 0) {
    														$status_info_rs = mysqli_fetch_array($getStatusDescriptions);
    														echo $status_info_rs[0];
    													}
											        }
											    ?>
										    </h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm" id="rentedPropertiesTable">
											<thead>
												<tr class="text-center">
													<th>No</th>
													<th>Property Name</th>
													<th>Property Location</th>
													<th>Deposit Amount</th>
													<th>Rental Fee</th>
													<th>Register Date</th>
													<th>Status</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$x = 1;
													while ($rs = mysqli_fetch_array($reportQuery)) {?>
														<tr>
															<td class="text-center"><?php echo $x; ?></td>
															<td class="text-left"><?php echo $rs[0]. ", ". $rs[1]; ?></td>
															<td class="text-left"><?php echo $rs[2] .", ". $rs[3] ."-". $rs[4]; ?></td>
															<td class="text-center"><?php echo "$ ". number_format($rs[5], 2); ?></td>
															<td class="text-center"><?php echo "$ ". number_format($rs[6], 2); ?></td>
															<td class="text-center"><?php echo substr($rs[7], 0, 10); ?></td>
														    <td class="text-left font-weight-bold"><?php echo $rs[8]; ?></td>
														</tr><?php
														$x++;
													}
												?>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// ================ END OF LANDLORDS MODULE ==================================================

	// ================ START OF RENTAL PROPERTIES MODULE ========================================

	// Register new rental property
	function register_new_rental_property($conn) {
		
		global $errorList;
		$data = array();
		extract($_POST);

		//Generate New ID for the current inserted row....
		$getMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM rental_properties") or die(mysqli_error($conn));
		if (mysqli_num_rows($getMaxID) > 0) {
			$maxID = mysqli_fetch_array($getMaxID);
			$curMaxID = $maxID[0] + 1;
			$generatedID = "RPR". "". sprintf("%04d", $curMaxID);
		} else {
			$curMaxID = 1;
			$generatedID = "RPR". "". sprintf("%04d", $curMaxID);
		}

		$property_name = mysqli_real_escape_string($conn, $property_name);
		$property_type = mysqli_real_escape_string($conn, $property_type);
		$building_id = mysqli_real_escape_string($conn, $building_id);
		$property_size = mysqli_real_escape_string($conn, $property_size);
		$number_of_rooms = mysqli_real_escape_string($conn, $number_of_rooms);
		$number_of_toilets = mysqli_real_escape_string($conn, $number_of_toilets);
		$floor_number = mysqli_real_escape_string($conn, $floor_number);
		$property_price = mysqli_real_escape_string($conn, $property_price);
		$payment_type = mysqli_real_escape_string($conn, $payment_type);
		$deposit_amount = mysqli_real_escape_string($conn, $deposit_amount);
		$property_owner = mysqli_real_escape_string($conn, $property_owner);
		$property_remarks = mysqli_real_escape_string($conn, $property_remarks);
		$property_status = mysqli_real_escape_string($conn, $property_status);
		$registered_by = mysqli_real_escape_string($conn, $registered_by);
		$register_date = mysqli_real_escape_string($conn, $register_date);

		// Rental Property Photos count, check then upload
		$count_photos = count($_FILES['txtPropertyPhotosNewRentalProperty']['name']);
		$photos_location = "../uploads/photos/";
		$uploadedPhotoNames = "";

		for($index = 0;$index < $count_photos;$index++){
		
			if(isset($_FILES['txtPropertyPhotosNewRentalProperty']['name'][$index]) && $_FILES['txtPropertyPhotosNewRentalProperty']['name'][$index] != ''){
		
				$filename = $_FILES['txtPropertyPhotosNewRentalProperty']['name'][$index];
				$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
				$valid_ext = array('jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG'); 

				if(in_array($ext, $valid_ext)){
					
					$new_photo_name = "RENTALPROP". ($index + 1) ."_" . date("YmdHis") . "." . $ext;

					if(move_uploaded_file($_FILES['txtPropertyPhotosNewRentalProperty']['tmp_name'][$index], $photos_location.$new_photo_name)){
						$uploadedPhotoNames .= substr($photos_location.$new_photo_name, 3). "###";
					}
				} else {
					$errorMsg = "Upload only the allowed photo types";
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			}
						
		}
		
		//echo rtrim($uploadedPhotoNames, "###");
		
		$registerRentalProperty = mysqli_query($conn, "INSERT INTO rental_properties VALUES (NULL, '". $generatedID ."', '". $property_name ."', '". $property_type ."', '". $building_id ."', '". $property_size ."', '". $number_of_rooms ."', '". $number_of_toilets ."', '". $floor_number ."', '". $property_price ."', '". $payment_type ."', '". $deposit_amount ."', '". $property_owner ."', '". $property_remarks ."', '". $property_status ."', '". $registered_by ."', '". $register_date ."', '-', '-', '". rtrim($uploadedPhotoNames, "###") ."')"); 
		if ($registerRentalProperty) { 
			$data = json_encode(array('Status' => true, 'Message' => 'Rental property has been registered successfully'));
		} else { 
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} 
		
		echo $data;

	}

	// ================ END OF RENTAL PROPERTIES MODULE ==========================================

	// ================ START OF RENT A PROPERTYT MODULE =========================================

	//Search for the availbale rental properties
	function search_available_rental_properties($conn) {
		extract($_POST);
		$selected_building_id = mysqli_real_escape_string($conn, $selected_building_id);
		$selected_property_location = mysqli_real_escape_string($conn, $selected_property_location);
		$selected_property_type = mysqli_real_escape_string($conn, $selected_property_type);
		$selected_bedrooms = mysqli_real_escape_string($conn, $selected_bedrooms);
		$selected_property_price_range = mysqli_real_escape_string($conn, $selected_property_price_range);
		$selected_property_status = mysqli_real_escape_string($conn, $selected_property_status);

		$generatedReportQuery = "SELECT rental_properties.rentalPropertyID, rental_properties.propertyPhotos, buildings.buildingID, buildings.buildingName, rental_properties.propertyName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, property_types.propertyTypeDescription, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_properties.rentalPrice, rental_properties.depositAmount, rental_property_statuses.propertyStatusDescription, rental_property_statuses.propertyStatusID 
		FROM rental_properties 
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID 
		JOIN property_locations ON buildings.locationID = property_locations.locationID 
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID 
		JOIN floors ON rental_properties.floorID = floors.floorID 
		JOIN rental_property_statuses ON rental_properties.propertyStatus = rental_property_statuses.propertyStatusID ";

		if ($selected_building_id != "" || $selected_property_location != "" || $selected_property_type != "" || $selected_property_price_range != "" || $selected_bedrooms != "" || $selected_property_status != "") { $generatedReportQuery .= "WHERE "; }
		if ($selected_building_id != "") { $generatedReportQuery .= "rental_properties.buildingID = '". $selected_building_id ."' "; }
		if ($selected_property_location != "") {
			if ($selected_building_id != "") { $generatedReportQuery .= "AND buildings.locationID = '". $selected_property_location ."' ";
			} else { $generatedReportQuery .= "buildings.locationID = '". $selected_property_location ."' "; }
		}
		if ($selected_property_type != "") {
			if ($selected_building_id != "" || $selected_property_location != "") { 
				$generatedReportQuery .= "AND rental_properties.propertyType = '". $selected_property_type ."' ";
			} else { 
				$generatedReportQuery .= "rental_properties.propertyType = '". $selected_property_type ."' "; 
			}
		}
		if ($selected_bedrooms != "") {
			if ($selected_building_id != "" || $selected_property_location != "" || $selected_property_type != "") { 
				$generatedReportQuery .= "AND rental_properties.noOfBedrooms = '". $selected_bedrooms ."' ";
			} else { 
				$generatedReportQuery .= "rental_properties.noOfBedrooms = '". $selected_bedrooms ."' "; 
			}
		}
		if ($selected_property_price_range != "") {
			if ($selected_building_id != "" || $selected_property_location != "" || $selected_property_type != "" || $selected_bedrooms != "") { 
				$generatedReportQuery .= "AND rental_properties.rentalPrice <= '". $selected_property_price_range ."' ";
			} else { 
				$generatedReportQuery .= "rental_properties.rentalPrice <= '". $selected_property_price_range ."' "; 
			}
		}
		if ($selected_property_status != "") {
			if ($selected_building_id != "" || $selected_property_location != "" || $selected_property_type != "" || $selected_bedrooms != "" || $selected_property_price_range != "") { 
				$generatedReportQuery .= "AND rental_properties.propertyStatus = '". $selected_property_status ."' ";
			} else { 
				$generatedReportQuery .= "rental_properties.propertyStatus = '". $selected_property_status ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY rental_properties.rentalPrice DESC";
		// echo $generatedReportQuery;
		$searchAvailableProperties = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));

		if ($searchAvailableProperties) {
			if (mysqli_num_rows($searchAvailableProperties) > 0) { ?>
				<div class="tile">
					<div class="tile-body">
						<div class="row">
							<div class="col-md-12 pb-1" data-aos="fade-up" >
								<h4 class="font-weight-normal text-primary">Available <b>Rental Properties</b></h4>
							</div>
						</div>
						
						<div class="row">
							<?php
								$i = 1;
								while ($rental_property_rs = mysqli_fetch_array($searchAvailableProperties)) { ?>
									<div class="col-md-4 mb-4">
										<div class="bs-component">
											<div class="card">
												<?php $property_photos = explode("###", $rental_property_rs[1]); ?>
												<img style="height: 240px; width: 100%; display: block;" src="<?php echo $property_photos[0]; ?>" alt="Card image">
												<div class="card-body">
													<div class="row">
														<div class="col-md-12"><h5 style="text-transform: capitalize;"><?php echo $rental_property_rs[4]. ", ". $rental_property_rs[3]; ?></h5></div>
													</div>
													<div class="row pt-2">
														<div class="col-md-1"><i class="fa fa-map-marker fa-lg text-info"></i></div>
														<div class="col-md-11"><h6 class="font-weight-bold"><?php echo $rental_property_rs[5]. ", ". $rental_property_rs[6] . " - ". $rental_property_rs[7]; ?></h6></div>
													</div>
													<div class="row pt-2">
														<div class="col-md-1"><i class="fa fa-home fa-lg text-info"></i></div>
														<div class="col-md-5"><?php echo $rental_property_rs[8]; ?></div>
														<div class="col-md-1"><i class="fa fa-building fa-lg text-info"></i></div>
														<div class="col-md-5"><?php echo $rental_property_rs[9]; ?></div>
													</div>
													<div class="row pt-2">
														<div class="col-md-1"><i class="fa fa-hotel fa-lg text-info"></i></div>
														<div class="col-md-5"><?php echo $rental_property_rs[10]. " Bedrooms"; ?></div>
														<div class="col-md-1"><i class="fa fa-bath fa-lg text-info"></i></div>
														<div class="col-md-5"><?php echo $rental_property_rs[11]. " Bathrooms"; ?></div>
													</div>
													<div class="row pt-2">
														<div class="col-md-1"><i class="fa fa-dollar fa-lg text-info"></i></div>
														<div class="col-md-5"><?php echo "Price: <b>$". number_format($rental_property_rs[12], 2). "</b>"; ?></div>
														<div class="col-md-1"><i class="fa fa-money fa-lg text-info"></i></div>
														<div class="col-md-5"><?php echo "Deposit: <b>$". number_format($rental_property_rs[13], 2). "</b>"; ?></div>
													</div>
													<div class="row pt-2">
														<div class="col-md-6">
															<span class='btn btn-sm btn-success col-sm-12'> <i class='fa fa-check'> </i> <?php echo $rental_property_rs[14]; ?></span>
														</div>
														<div class="col-md-6">
															<button type="button" class="btn btn-warning btn-sm col-md-12 btnSeeRentalPropertyPhotos" data-id="<?php echo $rental_property_rs[0]; ?>" data-toggle="modal" data-target="#seeRentalPropertyPhotosModal"><i class="fa fa-eye"></i> See Photos</button>
														</div>
													</div>
													<?php
														if ($rental_property_rs[15] == 1) {
															?><span class="btn btn-info col-sm-12 mt-3 btnRentPropertyNow" id="<?php echo "Update". $rental_property_rs[0]; ?>" data-id="<?php echo $rental_property_rs[0]; ?>" data-toggle="modal" data-target="#propertyRentingModal"> <i class="fa fa-bookmark"> </i> Rent Now</span><?php
														}
													?>
												</div>

											</div>
										</div>
									</div><?php
									$i++;
								}
							?>
						</div>
						<?php
							if ($i == 2) { ?>
								<div class="row mt-3">
									<div class="col-md-12 text-right">
										<hr class="bg-primary">
										<h5 class="font-weight-normal text-primary">Only <b>one</b> rental property has been found</h5>
									</div>
								</div><?php
							} else if ($i > 2) { ?>
								<div class="row mt-3">
									<div class="col-md-12 text-right">
										<hr class="bg-primary">
										<h5 class="font-weight-normal text-primary">A total of <b><?php echo ($i-1); ?></b> rental properties have been found</h5>
									</div>
								</div><?php
							}
						?>
					</div>
				</div><?php
			} else {
				?><div class="tile">
					<div class="tile-body">
						<br />
						<div class="row">
							<div class="col-md-12" style="margin: 0px;">
								<h6 class="text-center text-danger font-weight-normal">Rental Properties Not Found</h6>
							</div>
						</div>
						<br />
					</div>
				</div><?php			
			}
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php			
		}
			
	}

	// View Rental Property Photos
	function view_rental_property_photos($conn) {
		extract($_POST);
		$rental_property_id = mysqli_real_escape_string($conn, $rentalPropertyID); 
		
		?><div class="row">
			<div class="col-md-12">
				<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
					<ol class="carousel-indicators">
						<?php
							$getRentalPropertyNumbers = mysqli_query($conn, "SELECT propertyPhotos FROM rental_properties WHERE rentalPropertyID = '". mysqli_real_escape_string($conn, $rental_property_id) ."'") or die(mysqli_error($conn));
							if (mysqli_num_rows($getRentalPropertyNumbers) > 0) {
								$rental_property_photos_rs = mysqli_fetch_array($getRentalPropertyNumbers);
								$all_rental_property_images = explode("###", $rental_property_photos_rs[0]);
								$count_carousel = 1;
								foreach($all_rental_property_images as $rental_property_image) {
									if ($count_carousel == 1) {
										?><li data-target="#carouselExampleIndicators" data-slide-to="<?php echo $rental_property_image; ?>" class="active"></li><?php
									} else {
										?><li data-target="#carouselExampleIndicators" data-slide-to="<?php echo $rental_property_image; ?>"></li><?php
									}
									$count_carousel++;
								}
							} else {
								?><p class="text-center">No rental property photos found</p><?php 
							}
						?>
					</ol>
					<div class="carousel-inner">
						<?php
							$getRentalPropertyPhotos = mysqli_query($conn, "SELECT propertyPhotos FROM rental_properties WHERE rentalPropertyID = '". mysqli_real_escape_string($conn, $rental_property_id) ."'") or die(mysqli_error($conn));
							if (mysqli_num_rows($getRentalPropertyPhotos) > 0) {
								$carousel_i = 1;
								while ($rental_property_photos_carousel_rs = mysqli_fetch_array($getRentalPropertyPhotos)) {
									$all_rental_property_photos = explode("###", $rental_property_photos_carousel_rs[0]);
									foreach ($all_rental_property_photos as $rental_property_photo) {
										if ($carousel_i == 1) { 
											?><div class="carousel-item active">
												<img class="d-block w-100" src="<?php echo $rental_property_photo;?>" height="550px">
											</div><?php
										} else {
											?><div class="carousel-item">
												<img class="d-block w-100" src="<?php echo $rental_property_photo;?>" height="550px">
											</div><?php                            
										}
										$carousel_i++;
									}
									
								}
							} else {
								?><p class="text-center">No rental property photos found</p><?php 
							}
						?>
					</div>
					<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
						<span class="carousel-control-prev-icon" aria-hidden="true"></span>
						<span class="sr-only">Previous</span>
					</a>
					<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
						<span class="carousel-control-next-icon" aria-hidden="true"></span>
						<span class="sr-only">Next</span>
					</a>
				</div> 
			</div>
		</div><?php
	}

	// Fetch Rental Property Information
	function fetch_rental_property_information($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		$selected_property_id = mysqli_real_escape_string($conn, $selected_property_id);
		$getRentalPropertyInformation = mysqli_query($conn, "SELECT rental_properties.rentalPropertyID, rental_properties.propertyName, buildings.buildingID, buildings.buildingName, property_types.propertyTypeDescription, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_properties.rentalPrice, rental_properties.depositAmount, landlords.landlordPhoto, landlords.landlordName, landlords.landlordMobile
		FROM rental_properties
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_locations ON buildings.locationID = property_locations.locationID 
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID 
		JOIN floors ON rental_properties.floorID = floors.floorID 
		JOIN landlords ON rental_properties.landlordID = landlords.landlordID 
		WHERE rental_properties.rentalPropertyID = '". $selected_property_id ."'") or die(mysqli_error($conn));
		if ($getRentalPropertyInformation) {
			if (mysqli_num_rows($getRentalPropertyInformation) > 0) {
				while ($row = mysqli_fetch_array($getRentalPropertyInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Rental Property Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// ================ END OF RENT A PROPERTYT MODULE ===========================================

	//Print Individual Rented Property Details Report
	function individual_rented_property_report($conn) {
		extract($_POST);
		$selected_rent_id = mysqli_real_escape_string($conn, $selected_rent_id);
		$searchRentInformation = mysqli_query($conn, "SELECT rented_properties.rentingID, tenants.tenantID, tenants.tenantPhoto, tenants.tenantName, tenants.placeOfBirth, tenants.dateOfBirth, tenants.tenantGender, tenants.tenantMaritalStatus, tenants.tenantMobile, rental_properties.propertyName, buildings.buildingName, property_types.propertyTypeDescription, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_property_payment_types.paymentTypeDescription, rental_properties.rentalPrice, rental_properties.depositAmount, landlords.landlordName, landlords.landlordMobile, rented_properties.rentStartDate, rented_properties.rentEndDate, rented_properties.rentChargeDay, rented_properties.rentPaymentDay, system_users.Username, employees.employeeName, employees.titlePosition, rented_properties.registerDate
		FROM rented_properties
		JOIN tenants ON rented_properties.tenantID = tenants.tenantID
		JOIN rental_properties ON rented_properties.rentalPropertyID = rental_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID
		JOIN floors ON rental_properties.floorID = floors.floorID
		JOIN property_locations ON buildings.locationID = property_locations.locationID
		JOIN landlords ON rental_properties.landlordID = landlords.landlordID
		JOIN rental_property_payment_types ON rental_properties.paymentTypeID = rental_property_payment_types.paymentTypeID
		JOIN system_users ON rented_properties.registeredBy = system_users.userID
		JOIN employees ON system_users.employeeID = employees.employeeID
		WHERE rented_properties.rentingID = '". $selected_rent_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($searchRentInformation) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printIndividualRentedPropertyReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="individualRentedPropertyReportArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="160px" /><br />
									<center><h2 style="color: #010132;">Rental Contract Report</h2></center>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<?php $tenant_result = mysqli_fetch_array($searchRentInformation); ?>
									<div class="row pt-3" style="margin: 0px;">
										<div class="col-md-12">
											<h5><i class="fa fa-vcard"></i> Tenant Information</h5><hr />
										</div>
									</div>
									<div class="row" style="margin: 0px;">
										<div class="col-md-2">
											<div class="row">
												<div class="col-md-12">
													<img class="img-fluid" src="<?php echo $tenant_result[2]; ?>" width="100%" height="150px" />
												</div>
											</div>
										</div>
										<div class="col-md-10">
											<div class="row">
												<div class="col-md-3">
													<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Tenant ID</h5>
													<h6 class="font-weight-normal"><?php echo $tenant_result[1]; ?></h6>
												</div>
												<div class="col-md-6">
													<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Tenant Name</h5>
													<h6 class="font-weight-normal"><?php echo $tenant_result[3]; ?></h6>
												</div>	
												<div class="col-md-3">
													<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Place of Birth</h5>
													<h6 class="font-weight-normal"><?php echo $tenant_result[4]; ?></h6>
												</div>
											</div>
											<div class="row">
												<div class="col-md-3">
													<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Date of Birth</h5>
													<h6 class="font-weight-normal"><?php echo $tenant_result[5]; ?></h6>
												</div>
												<div class="col-md-3">
													<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Gender</h5>
													<h6 class="font-weight-normal"><?php echo $tenant_result[6]; ?></h6>
												</div>	
												<div class="col-md-3">
													<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Marital Status</h5>
													<h6 class="font-weight-normal"><?php echo $tenant_result[7]; ?></h6>
												</div>
												<div class="col-md-3">
													<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Mobile No</h5>
													<h6 class="font-weight-normal"><?php echo $tenant_result[8]; ?></h6>
												</div>
											</div>
										</div>
									</div>
									<div class="row pt-4" style="margin: 0px;">
										<div class="col-md-12">
											<h5><i class="fa fa-building"></i> Property Information </h5><hr />
										</div>
									</div>
									<div class="row" style="margin: 0px;">
										<div class="col-md-4">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Property Name</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[9]. ", ". $tenant_result[10]; ?></h6>
										</div>
										<div class="col-md-2">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Property Type</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[11]; ?></h6>
										</div>
										<div class="col-md-4">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Location (Address)</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[12]. ", ". $tenant_result[13]. "-". $tenant_result[14]; ?></h6>
										</div>	
										<div class="col-md-2">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Floor</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[15]; ?></h6>
										</div>
										<div class="col-md-2">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Bedrooms</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[16]. " Bedrooms"; ?></h6>
										</div>
										<div class="col-md-2">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Bathrooms</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[17]. " Bathrooms"; ?></h6>
										</div>
										<div class="col-md-3">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Payment Type</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[18]; ?></h6>
										</div>
										<div class="col-md-3">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rental Price</h5>
											<h6 class="font-weight-normal"><?php echo "$ ". number_format($tenant_result[19], 2). " (Monthly)"; ?></h6>
										</div>
										<div class="col-md-2">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Deposit</h5>
											<h6 class="font-weight-normal"><?php echo "$ ". number_format($tenant_result[20], 2); ?></h6>
										</div>
										<div class="col-md-4">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Landlord Name</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[21]. " - ". $tenant_result[22]; ?></h6>
										</div>
									</div>
									<div class="row pt-4" style="margin: 0px;">
										<div class="col-md-12">
											<h5><i class="fa fa-file-text-o"></i> Rent Information </h5><hr />
										</div>
									</div>
									<div class="row" style="margin: 0px;">
										<div class="col-md-3">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent Start Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($tenant_result[23], 0, 10); ?></h6>
										</div>
										<div class="col-md-3">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent End Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($tenant_result[24], 0, 10); ?></h6>
										</div>
										<div class="col-md-3">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Charge Day</h5>
											<h6 class="font-weight-normal">
												<?php
													if ($tenant_result[25] == 1) {
														echo $tenant_result[25]. "<sup>st</sup> of Every Month";
													} else if ($tenant_result[25] == 2) {
														echo $tenant_result[25]. "<sup>nd</sup> of Every Month";
													} else if ($tenant_result[25] == 3) {
														echo $tenant_result[25]. "<sup>rd</sup> of Every Month";
													} else {
														echo $tenant_result[25]. "<sup>th</sup> of Every Month";
													}
												?>
											</h6>
										</div>
										<div class="col-md-3">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Payment Day</h5>
											<h6 class="font-weight-normal">
												<?php
													if ($tenant_result[26] == 1) {
														echo $tenant_result[26]. "<sup>st</sup> of Every Month";
													} else if ($tenant_result[26] == 2) {
														echo $tenant_result[26]. "<sup>nd</sup> of Every Month";
													} else if ($tenant_result[26] == 3) {
														echo $tenant_result[26]. "<sup>rd</sup> of Every Month";
													} else {
														echo $tenant_result[26]. "<sup>th</sup> of Every Month";
													}
												?>
											</h6>										
										</div>	
										<div class="col-md-6">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Company Representive</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_result[28]. " (<strong>" .$tenant_result[27]. "</strong>)"; ?></h6>
										</div>
										<div class="col-md-3">
											<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Agreement Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($tenant_result[30], 0, 10); ?></h6>
										</div>
									</div>
									<div class="row pt-4" style="margin: 0px;">
										<div class="col-md-12">
											<h5><i class="fa fa-list-ul"></i> Declaration</h5><hr />
										</div>
									</div>
									<div class="row" style="margin: 0px;">
										<?php
											$rent_start_date = strtotime(substr($tenant_result[23], 0, 10));
											$rent_end_date = strtotime(substr($tenant_result[24], 0, 10));
											$duration_in_months = ceil(($rent_end_date - $rent_start_date) / 2592000);
										?>
										<div class="col-md-12">
											<h6 class="text-justify">
											I have read the terms and conditions and I hereby accept and agree to the terms and conditions as stated below:
											</h6>
											<h6 class="font-weight-normal">
												<ol style="line-height: 1.3;">
													<li>I have to pay <strong><?php echo "$ ". number_format($tenant_result[19], 2); ?></strong> (in words) as monthly rent, which does not include electricity and water charges.</li>
													<li>I shall not lease the property to a subtenant under any circumstances without the consent of the company.</li>
													<li>I shall follow all the rules and regulations, by-laws set by the company in respect of the leased property and will not get involved in illegal activities and will not keep any offensive, dangerous or explosive articles in the premises.</li>
													<li>This contract is granted for a period of <strong><?php if ($duration_in_months == 1) { echo $duration_in_months. " Month"; } else if ($duration_in_months > 1) { echo $duration_in_months. " Months"; } ?></strong> starting from <strong><?php echo substr($tenant_result[23], 0, 10); ?></strong> until <strong><?php echo substr($tenant_result[24], 0, 10); ?></strong>, and this contract can be extended further with the mutual consent of both the parties as per the current rental value in the market.</li>
													<li>I shall not be permitted to do a construction in the rented premises or make any alteration in the rented property without seeking the permission of the company.</li>
													<li>I shall have to allow the authorized agents of the company to enter in to the rented premises for its inspection or general checking for any repair work, if needed.</li>
													<li>I shall keep the premises clean and shall not involve in any activity that causes problems to neighbors.</li>
												</ol>
											</h6>

											<h6 class="text-justify">Hereby, I confirm again that I have read and understood terms and conditions stated above in this agreement and have agreed to sign it without any pressure from any side.</h6>

										</div>
									</div>

								</div>
							</div>

							<div class="row" style="margin-top: 40px;">
								<div class="col-md-4">
									<h6 class="text-center font-weight-normal">Tenant Name</h6>
									<h5 class="text-black text-center font-weight-bold"><?php echo $tenant_result[3]; ?></h5>
									<h6 class="text-center font-weight-normal">Signature</h6>									
									<h5 class="text-center font-weight-normal"><hr style="border-top: 1px solid black; width: 50%;"></h5>
								</div>
								<div class="col-md-2">&nbsp;</div>									
								<div class="col-md-6">
									<h6 class="text-center font-weight-normal">Company Representive</h6>
									<div class="col-md-12 p-2" style="height: 120px; background-image: url('img/stamp.png'); background-size : 50% 100%; background-repeat : no-repeat; background-position: center;">
										<h5 class="text-black text-center font-weight-bold"><?php echo $tenant_result[28]; ?></h5>
										<h6 class="text-center font-weight-normal">Signature</h6>
										<h5 class="text-center font-weight-normal"><hr style="border-top: 1px solid black; width: 50%;"></h5>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<center>
								<h3 style="font-family: 'Poppins'; color: maroon; font-weight: normal">Rent Report Not Found</h3></center>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// ================ START OF RENTAL BOOKING MODULE ===========================================
	// Change Booking Status into Complete/Cancel
	function change_rental_booking_status($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$selected_booking_id = mysqli_real_escape_string($conn, $selected_booking_id);
		$booking_status = mysqli_real_escape_string($conn, $booking_status);
		$makeBookingStatus = mysqli_query($conn, "UPDATE booked_properties SET bookingStatus = '". $booking_status ."' WHERE bookingID = '" . $selected_booking_id . "'");
		if ($makeBookingStatus) {
			$data = json_encode(array('Status' => true, 'Message' => 'Booking has been updated successfully'));
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	// ================ END OF RENTAL BOOKING MODULE =============================================

	// ================ START OF EXTEND RENT CONTRACT MODULE =====================================

	// Fetch Rent Information To Extend Rent Contract
	function fetch_rent_information_to_extend_contract($conn) {
		extract($_POST);
		$selected_rent_id = mysqli_real_escape_string($conn, $selected_rent_id);
		$searchRentInformation = mysqli_query($conn, "SELECT rented_properties.rentingID, tenants.tenantPhoto, rental_properties.propertyName, buildings.buildingName, property_types.propertyTypeDescription, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, tenants.tenantName, tenants.tenantMobile, rental_properties.rentalPrice, rented_properties.rentStartDate, rented_properties.rentEndDate
		FROM rented_properties
		JOIN rental_properties ON rented_properties.rentalPropertyID = rental_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID
		JOIN floors ON rental_properties.floorID = floors.floorID
		JOIN property_locations ON buildings.locationID = property_locations.locationID
		JOIN tenants ON rented_properties.tenantID = tenants.tenantID
		WHERE rented_properties.rentingID = '". $selected_rent_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($searchRentInformation) > 0) {
			$rent_result = mysqli_fetch_array($searchRentInformation); ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row pt-3" style="margin: 0px;">
						<div class="col-md-12">
							<h5><i class="fa fa-vcard"></i> Rent Information</h5><hr />
						</div>
					</div>
					<div class="row" style="margin: 0px;">
						<div class="col-md-2">
							<div class="row text-center ">
								<div class="col-md-12 pb-3">
									<img class="img-fluid img-thumbnail rounded" src="<?php echo $rent_result[1]; ?>" width="100%" height="100px" /><br />
									<h6>Tenant Photo</h6>
								</div>
							</div>
						</div>
						<div class="col-md-10">
							<div class="row">
								<div class="col-md-2">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent ID</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[0]; ?></h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Property Name</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[2]; ?></h6>
								</div>	
								<div class="col-md-4">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Building Name</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[3]; ?></h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Property Type</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[4]; ?></h6>
								</div>
							</div>
							<div class="row">
								<div class="col-md-5">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Location</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[5]. ", ". $rent_result[6]. "-". $rent_result[7]; ?></h6>
								</div>
								<div class="col-md-2">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Floor</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[8]; ?></h6>
								</div>
								<div class="col-md-2">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Bedrooms</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[9]. " Bedroom(s)"; ?></h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Bathrooms</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[10]. " Bathroom(s)"; ?></h6>
								</div>								
							</div>
							<div class="row">
								<div class="col-md-4">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Tenant Name</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[11]; ?></h6>
								</div>	
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Tenant Phone</h5>
									<h6 class="font-weight-normal"><?php echo "+ 252 ". $rent_result[12]; ?></h6>
								</div>
								<div class="col-md-2">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rental Price</h5>
									<h6 class="font-weight-normal"><?php echo "$". number_format($rent_result[13], 2); ?></h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent Start Date</h5>
									<h6 class="font-weight-normal"><?php echo substr($rent_result[14], 0, 10); ?></h6>
								</div>	
							</div>
							<div class="row">
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent End Date</h5>
									<h6 class="font-weight-normal">
										<?php echo substr($rent_result[15], 0, 10); ?>
										<input type="hidden" id="txtExtendRentContractOldEndDate" name="txtExtendRentContractOldEndDate" value="<?php echo $rent_result[15]; ?>" />
									</h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Extend To Date</h5>
									<!-- Start the extension date to the current end date plus 1 day -->
									<input type="date" class="form-control" name="txtExtendRentContractNewEndDate" id="txtExtendRentContractNewEndDate" min="<?php echo date("Y-m-d", strtotime("+1 day", strtotime(substr($rent_result[15], 0, 10)))); ?>" value="<?php echo date("Y-m-d", strtotime("+1 day", strtotime(substr($rent_result[15], 0, 10)))); ?>" />							
								</div>
								<div class="col-md-6">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Remarks</h5>
									<textarea name="txtExtendRentContractRemarks" id="txtExtendRentContractRemarks" rows="1" class="form-control" placeholder="Enter extension remarks" required></textarea>
								</div>

							</div>
						</div>
					</div>
					<div class="row" style="margin: 0px;">
						<div class="col-md-10">&nbsp;</div>
						<div class="col-md-2 text-right mt-4">
							<span class="btn btn-success btnExtendRentContractNow col-md-12" name="btnExtendRentContractNow" data-id="<?php echo $rent_result[0]; ?>"><i class="fa fa-save"></i> Extend Contract</span>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal mt-2">Rent Record Not Found</h6>
						</div>
					</div>
				</div>
			</div><?php
		}
	}

	// Extend Rent End Date of a Contract
	function extend_rent_end_date_now($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$updateExtendRentEndDate = mysqli_query($conn, "UPDATE rented_properties SET rentEndDate = '". mysqli_real_escape_string($conn, $new_end_date) ."' WHERE rentingID = '". mysqli_real_escape_string($conn, $renting_id) ."'");
		if ($updateExtendRentEndDate) {
			// Generate New ID for the current inserted row....
			$getMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM extended_rent_contracts") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxID) > 0) {
				$maxID = mysqli_fetch_array($getMaxID);
				$curMaxID = $maxID[0] + 1;
				$generatedID = "EXTD". sprintf("%04d", $curMaxID);
			} else {
				$curMaxID = 1;
				$generatedID = "EXTD". sprintf("%04d", $curMaxID);
			}
			$registerExtendRentEndDate = mysqli_query($conn, "INSERT INTO extended_rent_contracts VALUES (NULL, '". $generatedID ."', '". mysqli_real_escape_string($conn, $renting_id) ."', '". mysqli_real_escape_string($conn, $old_end_date) ."', '". mysqli_real_escape_string($conn, $new_end_date) ."', '". mysqli_real_escape_string($conn, $extension_remarks) ."', '". $_SESSION['userIdd'] ."',  '". date("Y-m-d H:i") ."', '-', '-')");
			if ($registerExtendRentEndDate) {
				$data = json_encode(array('Status' => true, 'Message' => 'Contract end date has been extended successfully'));
			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}

	// ================ END OF EXTEND RENT CONTRACT MODULE =======================================
	
	// ================ START OF CANCEL RENT CONTRACT MODULE =====================================

	// Fetch Rent Information To Cancel Rent Contract
	function fetch_rent_information_to_cancel_contract($conn) {
		extract($_POST);
		$selected_rent_id = mysqli_real_escape_string($conn, $selected_rent_id);
		$searchRentInformation = mysqli_query($conn, "SELECT rented_properties.rentingID, rental_properties.rentalPropertyID, tenants.tenantPhoto, rental_properties.propertyName, buildings.buildingName, property_types.propertyTypeDescription, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, tenants.tenantName, tenants.tenantMobile, rental_properties.rentalPrice, rented_properties.rentStartDate, rented_properties.rentEndDate
		FROM rented_properties
		JOIN rental_properties ON rented_properties.rentalPropertyID = rental_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID
		JOIN floors ON rental_properties.floorID = floors.floorID
		JOIN property_locations ON buildings.locationID = property_locations.locationID
		JOIN tenants ON rented_properties.tenantID = tenants.tenantID
		WHERE rented_properties.rentingID = '". $selected_rent_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($searchRentInformation) > 0) {
			$rent_result = mysqli_fetch_array($searchRentInformation); ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row pt-3" style="margin: 0px;">
						<div class="col-md-12">
							<h5><i class="fa fa-vcard"></i> Rent Information</h5><hr />
						</div>
					</div>
					<div class="row" style="margin: 0px;">
						<div class="col-md-2">
							<div class="row text-center ">
								<div class="col-md-12 pb-3">
									<img class="img-fluid img-thumbnail rounded" src="<?php echo $rent_result[2]; ?>" width="100%" height="100px" /><br />
									<h6>Tenant Photo</h6>
								</div>
							</div>
						</div>
						<div class="col-md-10">
							<div class="row">
								<!--<div class="col-md-3">-->
								<!--	<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent ID</h5>-->
								<!--	<h6 class="font-weight-normal"><?php echo $rent_result[0]; ?></h6>-->
								<!--</div>-->
								<div class="col-md-5">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Property Name</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[3]; ?></h6>
								</div>	
								<div class="col-md-4">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Building Name</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[4]; ?></h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Property Type</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[5]; ?></h6>
								</div>
							</div>
							<div class="row">
								<div class="col-md-5">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Location</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[6]. ", ". $rent_result[7]. "-". $rent_result[8]; ?></h6>
								</div>
								<div class="col-md-4">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Floor</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[9]; ?></h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Bedrooms</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[10]. " Bedroom(s)"; ?></h6>
								</div>
							</div>
							<div class="row">
								<div class="col-md-5">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Tenant Name</h5>
									<h6 class="font-weight-normal"><?php echo $rent_result[12]; ?></h6>
								</div>	
								<div class="col-md-4">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Tenant Phone</h5>
									<h6 class="font-weight-normal"><?php echo "+ 252 ". $rent_result[13]; ?></h6>
								</div>
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rental Price</h5>
									<h6 class="font-weight-normal"><?php echo "$". number_format($rent_result[14], 2); ?></h6>
								</div>
							</div>
							<div class="row">
							    <div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent Start Date</h5>
									<h6 class="font-weight-normal"><?php echo substr($rent_result[15], 0, 10); ?></h6>
								</div>	
								<div class="col-md-3">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Rent End Date</h5>
									<h6 class="font-weight-normal">
										<?php echo substr($rent_result[16], 0, 10); ?>
									</h6>
								</div>
								<div class="col-md-6">
									<h5 class="pt-1 pr-2 pb-1 pl-0 border-bottom border-secondary">Remarks</h5>
									<textarea name="txtCancelRentContractRemarks" id="txtCancelRentContractRemarks" rows="3" class="form-control" placeholder="Enter cancel remarks" required></textarea>
								</div>

							</div>
						</div>
					</div>
					<div class="row" style="margin: 0px;">
						<div class="col-md-9">&nbsp;</div>
						<div class="col-md-3 text-right mt-4">
							<span class="btn btn-danger btnCancelRentContractNow col-md-12" name="btnCancelRentContractNow" data-id="<?php echo $rent_result[0]; ?>" property-id="<?php echo $rent_result[1]; ?>"><i class="fa fa-times"></i> Cancel Contract</span>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal mt-2">Rent Record Not Found</h6>
						</div>
					</div>
				</div>
			</div><?php
		}
	}

	// Cancel Rent Conrtact
	function cancel_rent_contract($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$updateRentStatus = mysqli_query($conn, "UPDATE rented_properties SET rentStatus = '0' WHERE rentingID = '". mysqli_real_escape_string($conn, $renting_id) ."'") or die(mysqli_error($conn));
		if ($updateRentStatus) {
			// Generate New ID for the current inserted row....
			$getMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM cancel_rent_contracts") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxID) > 0) {
				$maxID = mysqli_fetch_array($getMaxID);
				$curMaxID = $maxID[0] + 1;
				$generatedID = "CNCL". sprintf("%04d", $curMaxID);
			} else {
				$curMaxID = 1;
				$generatedID = "CNCL". sprintf("%04d", $curMaxID);
			}
			$cancelRentContract = mysqli_query($conn, "INSERT INTO cancel_rent_contracts VALUES (NULL, '". $generatedID ."', '". mysqli_real_escape_string($conn, $renting_id) ."', '". mysqli_real_escape_string($conn, $cancel_remarks) ."', '". $_SESSION['userIdd'] ."',  '". date("Y-m-d H:i") ."')");
			if ($cancelRentContract) {
			    mysqli_query($conn, "UPDATE rental_properties SET propertyStatus = '1' WHERE rentalPropertyID = '". mysqli_real_escape_string($conn, $property_id) ."'") or die(mysqli_error($conn));
				$data = json_encode(array('Status' => true, 'Message' => 'Contract has been cancelled successfully'));
			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}
	
	// Make Rent Conrtact Expire Automatically when Rent End Date is Reached
	function expire_rent_contract_automatically($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		//Get Active Rents in the System
		$getExpiredRentDates = mysqli_query($conn, "SELECT * FROM rented_properties WHERE rentEndDate <= '". date("Y-m-d H:i") ."'") or die(mysqli_error($conn));
		if ($getExpiredRentDates) {
			if (mysqli_num_rows($getExpiredRentDates) > 0) {
				while ($expired_rent_dates_rs = mysqli_fetch_array($getExpiredRentDates)) {
					// Expire this booking
					// First update the rent contrcat status to 2 = Expired
					mysqli_query($conn, "UPDATE rented_properties SET rentStatus = '2' WHERE rentingID = '". mysqli_real_escape_string($conn, $expired_rent_dates_rs[1]) ."'") or die(mysqli_error($conn));
			        // Second, update the associated property status to 1 = Available, to be available to rent again
                    mysqli_query($conn, "UPDATE rental_properties SET propertyStatus = '1' WHERE rentalPropertyID = '". mysqli_real_escape_string($conn, $expired_rent_dates_rs[2]) ."'") or die(mysqli_error($conn));
				}
				$data = json_encode(array('Status' => true, 'Message' => 'Rent contract has been set to expired'));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Expiring Rent Contracts Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// ================ END OF CANCEL RENT CONTRACT MODULE =======================================

	// ================ START OF FINANCE MODULE ==================================================

	// Charge Monthly Rental Fees
	function charge_rent_fees_automatically($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		//Get Active Rents in the System
		$getActiveRents = mysqli_query($conn, "SELECT * FROM rented_properties WHERE rentEndDate >= '". mysqli_real_escape_string($conn, date("Y-m-d")) ."' AND rented_properties.rentStatus = '1' AND rentChargeDay = '". mysqli_real_escape_string($conn, date("d")) ."'") or die(mysqli_error($conn));
		if ($getActiveRents) {
			if (mysqli_num_rows($getActiveRents) > 0) {
				while ($active_rents_rs = mysqli_fetch_array($getActiveRents)) {
					//Get Uncharged Properties this Month, CHT0001 is code for (Monthly Rent Charges) charge type 
					$checkChargeExistance = mysqli_query($conn, "SELECT rented_properties.rentingID, rented_properties.tenantID, rented_properties.rentalPropertyID, rental_properties.rentalPrice FROM rental_properties JOIN rented_properties ON rental_properties.rentalPropertyID = rented_properties.rentalPropertyID WHERE rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM tenant_charges WHERE chargeMonth = '". date("F-Y") ."' AND chargeTypeID = 'CHT0001') AND rented_properties.rentEndDate >= '". mysqli_real_escape_string($conn, date("Y-m-d")) ."'") or die (mysqli_error($conn));
					if ($checkChargeExistance) {
						if (mysqli_num_rows($checkChargeExistance) > 0) {
							while ($charge_rs = mysqli_fetch_array($checkChargeExistance)) {
								//Generate Charge ID for the current inserted row....
								$getChargeMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenant_charges") or die(mysqli_error($conn));
								if (mysqli_num_rows($getChargeMaxID) > 0) {
									$maxChargeID = mysqli_fetch_array($getChargeMaxID);
									$curChargeMaxID = $maxChargeID[0] + 1;
									$generatedChargeID = "CH" . sprintf("%04d", $curChargeMaxID);
								} else {
									$curChargeMaxID = 1;
									$generatedChargeID = "CH" . sprintf("%04d", $curChargeMaxID);
								}
								//Charge Current Property
								mysqli_query($conn, "INSERT INTO tenant_charges VALUES (NULL, '". $generatedChargeID ."', '". $charge_rs[0] ."', '". $charge_rs[1] ."', '". $charge_rs[2] ."', 'CHT0001', '". $charge_rs[3] ."', '". date("F-Y") ."', '". date("F-Y") ." Rent Charge', '" . $_SESSION['userIdd'] . "',  '" . date("Y-m-d H:i") . "', '-', '-')") or die(mysqli_error($conn));
							}
						}
					} else {
						$data = json_encode(array('Status' => false, 'Message' => mysqli_error($conn)));
					}
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Rental Property Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fetch Tenant Charges
	function fetch_tenant_charges($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		$tenantCharges = mysqli_query($conn, "SELECT tenant_charges.chargeID, tenant_charges.chargeRemarks, rental_properties.propertyName, ROUND(IFNULL(tenant_charges.chargedAmount, 0), 2) 'TotalDept', ROUND(IFNULL(tenant_charges.chargedAmount, 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0), 2) 'Remaining' FROM tenant_charges LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID JOIN rental_properties ON tenant_charges.rentalPropertyID = rental_properties.rentalPropertyID WHERE tenant_charges.tenantID = '". mysqli_real_escape_string($conn, $selected_tenant_id) ."' GROUP BY tenant_charges.chargeID HAVING Remaining > 0 ORDER BY LENGTH(tenant_charges.chargeID), tenant_charges.chargeID ASC") or die(mysqli_error($conn));
		if ($tenantCharges) {
			if (mysqli_num_rows($tenantCharges) > 0) {
				while ($row = mysqli_fetch_array($tenantCharges)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Data Not Found"));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Calculate Tenant Balance
	function calculate_tenant_charge_balance($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$selected_charge_id = mysqli_real_escape_string($conn, $selected_charge_id);
		$data = array();
		if ($selected_charge_id == "SinglePayment") {
			$total_depts = mysqli_query($conn, "SELECT tenant_charges.rentingID, ROUND(IFNULL(SUM(tenant_charges.chargedAmount), 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0), 2) 'Remaining' FROM tenant_charges LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID WHERE tenant_charges.tenantID = '". $selected_tenant_id ."' GROUP BY tenant_charges.tenantID HAVING Remaining > 0") or die(mysqli_error($conn));
		} else {
			$total_depts = mysqli_query($conn, "SELECT tenant_charges.rentingID, ROUND(IFNULL(SUM(tenant_charges.chargedAmount), 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0), 2) 'Remaining' FROM tenant_charges LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID WHERE tenant_charges.chargeID = '". $selected_charge_id ."' GROUP BY tenant_charges.chargeID HAVING Remaining > 0") or die(mysqli_error($conn));	
		}
		if (mysqli_num_rows($total_depts) > 0) {
			$total_dept_rs = mysqli_fetch_array($total_depts);
			$total_dept_amount = $total_dept_rs[1];
		} else { $total_dept_amount = 0; }

		$feedBackMsg = $total_dept_rs[0]. "###". $total_dept_amount;

		$data = json_encode(array('Status' => true, 'Message' => $feedBackMsg));

		echo $data;
		
	}
	
	// Register New Tenant Receipt
	function register_new_receipt($conn) {
		global $errorList;
		extract($_POST);
		$data = array();
		$selected_renting_id = mysqli_real_escape_string($conn, $selected_renting_id);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$selected_charge_id = mysqli_real_escape_string($conn, $selected_charge_id);
		$total_dept_amount = mysqli_real_escape_string($conn, $total_dept_amount);
		$total_paid_amount = mysqli_real_escape_string($conn, $total_paid_amount);
		$remaining_balance = mysqli_real_escape_string($conn, $remaining_balance);
		$deposit_account = mysqli_real_escape_string($conn, $deposit_account);
		$payment_remarks = mysqli_real_escape_string($conn, $payment_remarks);
		$getTenantInfo = mysqli_query($conn, "SELECT * FROM tenants WHERE tenantID = '". $selected_tenant_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($getTenantInfo) > 0) {
			$tenent_rs = mysqli_fetch_array($getTenantInfo);
			$tenant_mobile = $tenent_rs[8];
		}
		if ($selected_charge_id == "SinglePayment") {
			$getUnpaidStudentCharges = mysqli_query($conn, "SELECT tenant_charges.chargeID, ROUND(IFNULL(tenant_charges.chargedAmount, 0), 2) 'TotalDept', ROUND(IFNULL(tenant_charges.chargedAmount, 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0), 2) 'Remaining' FROM tenant_charges LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID WHERE tenant_charges.tenantID = '". mysqli_real_escape_string($conn, $selected_tenant_id) ."' GROUP BY tenant_charges.chargeID HAVING Remaining > 0 ORDER BY LENGTH(tenant_charges.chargeID), tenant_charges.chargeID ASC");
			if($getUnpaidStudentCharges) {
				if (mysqli_num_rows($getUnpaidStudentCharges) > 0) {
					$temp_total_paid = $total_paid_amount;
					while($unpaid_charge_rs = mysqli_fetch_row($getUnpaidStudentCharges)) {
						$cur_charge_id = $unpaid_charge_rs[0];
						$charge_amount = $unpaid_charge_rs[1];
						if ($temp_total_paid >= $charge_amount && $temp_total_paid > 0) {
							//Generate New ID for the current inserted receipt ....
							$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenant_receipts") or die(mysqli_error($conn));
							if (mysqli_num_rows($getMaxReceiptID) > 0) {
								$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
								$curMaxReceiptID = $maxReceiptID[0] + 1;
								$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
							} else {
								$curMaxReceiptID = 1;
								$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
							}
							$register_receipt = mysqli_query($conn, "INSERT INTO tenant_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_renting_id ."', '". $selected_tenant_id ."', '". $cur_charge_id  ."', '". $charge_amount ."', '". $deposit_account ."', '". $payment_remarks ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')");
							if ($register_receipt) {
								//Save receipts into account_transactions Table
								//Generate New ID for the current inserted row....
								$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
								if (mysqli_num_rows($getTransactionMaxID) > 0) {
									$transMaxID = mysqli_fetch_array($getTransactionMaxID);
									$currentMaxID = $transMaxID[0] + 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								} else {
									$currentMaxID = 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								}
								mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $charge_amount) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $payment_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));

							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
							$temp_total_paid -= $charge_amount;
						} else if ($temp_total_paid < $charge_amount && $temp_total_paid > 0) {
							//Generate New ID for the current inserted receipt ....
							$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenant_receipts") or die(mysqli_error($conn));
							if (mysqli_num_rows($getMaxReceiptID) > 0) {
								$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
								$curMaxReceiptID = $maxReceiptID[0] + 1;
								$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
							} else {
								$curMaxReceiptID = 1;
								$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
							}
							$register_receipt = mysqli_query($conn, "INSERT INTO tenant_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_renting_id ."', '". $selected_tenant_id ."', '". $cur_charge_id  ."', '". $temp_total_paid ."', '". $deposit_account ."', '". $payment_remarks ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')");
							if ($register_receipt) {
								//Save receipts into account_transactions Table
								//Generate New ID for the current inserted row....
								$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
								if (mysqli_num_rows($getTransactionMaxID) > 0) {
									$transMaxID = mysqli_fetch_array($getTransactionMaxID);
									$currentMaxID = $transMaxID[0] + 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								} else {
									$currentMaxID = 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								}
								mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $temp_total_paid) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $payment_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));

							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
							$temp_total_paid = 0;
						}
					}
					$data = json_encode(array('Status' => true, 'Message' => 'Tenant receipt has been registered successfully'));
				} else {
					$errorMsg = "No Data Found";
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		} else {

			//Generate New ID for the current inserted receipt ....
			$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenant_receipts") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxReceiptID) > 0) {
				$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
				$curMaxReceiptID = $maxReceiptID[0] + 1;
				$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
			} else {
				$curMaxReceiptID = 1;
				$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
			}
			$register_receipt = mysqli_query($conn, "INSERT INTO tenant_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_renting_id ."', '". $selected_tenant_id ."', '". $selected_charge_id  ."', '". $total_paid_amount ."', '". $deposit_account ."', '". $payment_remarks ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')");
			if ($register_receipt) {
				//Save receipts into account_transactions Table
				//Generate New ID for the current inserted row....
				$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
				if (mysqli_num_rows($getTransactionMaxID) > 0) {
					$transMaxID = mysqli_fetch_array($getTransactionMaxID);
					$currentMaxID = $transMaxID[0] + 1;
					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
				} else {
					$currentMaxID = 1;
					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
				}
				
				$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $total_paid_amount) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $payment_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."', '-', '-')");
				if ($registerTransaction) {
					$data = json_encode(array('Status' => true, 'Message' => 'Tenant receipt has been registered successfully'));
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}

			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		}
		
		echo $data;
	}
	
	// View Individual Tenant Receipt Report
	function view_individual_tenant_receipt($conn) {
		extract($_POST);
		$selected_receipt_id = mysqli_real_escape_string($conn, $selected_receipt_id);
		$reportQuery = mysqli_query($conn, "SELECT tenant_receipts.receiptID, tenants.tenantName, tenants.tenantMobile, tenant_receipts.paidAmount, payment_gateways.gatewayType, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber, tenant_receipts.receiptDescription, tenant_receipts.registerDate 
        FROM tenant_receipts
        JOIN tenants ON tenant_receipts.tenantID = tenants.tenantID
        JOIN account_numbers ON tenant_receipts.accountNoID = account_numbers.accountNoID 
        JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID
        WHERE tenant_receipts.receiptID = '". $selected_receipt_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
                    <div class="row">
                        <div class="col-sm-12 text-right">
                            <button class="btn btn-success btn-sm" id="printIndividualTenantReceipt"> <i class="fa fa-2x fa-print"></i> Print </button>
                        </div>
                    </div>      
                    <div class="row" id="individualTenantReceiptPrintArea">
                        <?php $tenant_receipt_rs = mysqli_fetch_array($reportQuery); ?>
                        <div class="col-sm-12 pb-4">
                            <div class="row">
                                <div class="col-sm-12">
							        <img src="img/reportHeader.png" width="70%" height="120px" /><br />
                                    <h2 class="text-center">Finance Office</h2>
                                    <h4 class="text-center">Tell: +252614273333 / Email: info@lighthousecore.so</h4>
                                    <h5 class="text-center">Receipt Voucher</h5>
                                </div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-1 pb-1"><h5>Receipt ID</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[0]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Tenant Name</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[1]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Mobile Number</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[2]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Paid Amount</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo "$ ". number_format($tenant_receipt_rs[3], 2); ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Deposit Name</h5></div>
            					<div class="col-sm-10 pt-1 pb-1">
            					    <h5 style="font-weight: normal;">
                					    <?php
                                            if ($tenant_receipt_rs[4] === "1") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "2") {
                                                echo $tenant_receipt_rs[5] . " " . $tenant_receipt_rs[6] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "3") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            }
                                        ?>
            					    </h5>
            			        </div>
            			    </div>
            			    <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Description</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[8]; ?></h5></div>
            				</div>
            				<div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Payment Date</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo substr($tenant_receipt_rs[9], 0, 16); ?></h5></div>
                            </div>
                            <div class="row mt-5">
								<div class="col-sm-8">&nbsp;</div>
								<div class="col-sm-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
                        </div>
                        
                        <div class="col-sm-12 pt-4">
                            <div class="row">
                                <div class="col-sm-12">
							        <img src="img/reportHeader.png" width="70%" height="110px" /><br />
                                    <h2 class="text-center">Finance Office</h2>
                                    <h4 class="text-center">Tell: +252614273333 / Email: info@lighthousecore.so</h4>
                                    <h5 class="text-center">Receipt Voucher</h5>
                                </div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-1 pb-1"><h5>Receipt ID</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[0]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Tenant Name</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[1]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Mobile Number</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[2]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Paid Amount</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo "$ ". number_format($tenant_receipt_rs[3], 2); ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Deposit Name</h5></div>
            					<div class="col-sm-10 pt-1 pb-1">
            					    <h5 style="font-weight: normal;">
                					    <?php
                                            if ($tenant_receipt_rs[4] === "1") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "2") {
                                                echo $tenant_receipt_rs[5] . " " . $tenant_receipt_rs[6] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "3") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            }
                                        ?>
            					    </h5>
            			        </div>
            			    </div>
            			    <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Description</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[8]; ?></h5></div>
            				</div>
            				<div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Payment Date</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo substr($tenant_receipt_rs[9], 0, 16); ?></h5></div>
                            </div>
                            <div class="row mt-5">
								<div class="col-sm-8">&nbsp;</div>
								<div class="col-sm-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
                        </div>

					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Receipt Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Tenant Statement
	function tenant_statement_report($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
		$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		if ($selected_start_date == " 00:00") {
			$generatedReportQuery = mysqli_query($conn, "CALL tenant_statement('". $selected_tenant_id ."', '0000-00-00', '0000-00-00')") or die("Error is this one kkkkk : ". mysqli_error($conn));
		} else {
			$generatedReportQuery = mysqli_query($conn, "CALL tenant_statement('". $selected_tenant_id ."', '". $selected_start_date ."', '". $selected_end_date ."')") or die(mysqli_error($conn));
		}
		if (mysqli_num_rows($generatedReportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printTenantStatementReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="tenantStatementReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="150px" /><br />
									<center><h2 style="color: #010132;">Tenant Statement</h2></center>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
										    $conn2 = mysqli_connect("localhost", "lighthq2_user", "Lighthouse9414", "lighthq2_lighthouse_db");
								// 			$conn2 = mysqli_connect("localhost", "root", "", "lighthq2_lighthouse_db");
											$selected_tenant_info = mysqli_query($conn2, "SELECT tenantID, tenantName, tenantMobile  FROM tenants WHERE tenantID = '" . $selected_tenant_id . "'") or mysqli_error($conn);
											$tenant_rs = mysqli_fetch_array($selected_tenant_info);
										?>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Tenant ID</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[0]; ?></h6>
										</div>
										<div class="col-md-3 pb-4">
											<h5 class="font-weight-bold">Tenant Name</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[1]; ?></h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Mobile Number</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[2]; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">From Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">To Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
									</div>	

									<div class="table-responsive">
										<table class="table table-bordered table-sm">
											<thead>
												<tr class="bg-light text-center">
													<th>Date</th>
													<th>Type</th>
													<th>Description</th>
													<th>Charge</th>
													<th>Receipt</th>
													<th>Balance</th>
												</tr>
											</thead>
											<tbody>

												<?php
													$counter = 1;
													$count_statement = mysqli_num_rows($generatedReportQuery);
													while ($result = mysqli_fetch_array($generatedReportQuery)) {
														if ($counter == 1) {?>
															<tr>
																<td class="text-right" colspan="5">Previous Balance</td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2)."</b>"; ?></td>													
															</tr> <?php
														} else if ($counter == $count_statement - 1) {?>
															<tr class="bg-light font-weight-bold">
																<td class="text-right" colspan="3"> Total</td>
																<td class="text-center"> <?php echo "$ ". number_format($result[5], 2); ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[6], 2); ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														} else if ($counter == $count_statement) {?>
															<tr class="font-weight-normal">
																<td class="text-right" colspan="5">Current Balance</td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2). "</b>"; ?></td>
															</tr> <?php
														} else { ?>
															<tr>
																<td class="text-center"> <?php echo substr($result[0], 0, 10); ?></td>
																<td class="text-center"> <?php echo $result[1]; ?></td>
																<td> <?php echo $result[2]; ?></td>
																<td class="text-center"><?php if ($result[5] != 0) { echo "$ ". number_format($result[5], 2); } ?></td>
																<td class="text-center"><?php if ($result[6] != 0) { echo "$ ". number_format($result[6], 2); } ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														}
														$counter++;
													}
												?>

											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Fetch Landlord Charges
	function fetch_landlord_charges($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		$landlordCharges = mysqli_query($conn, "SELECT landlord_charges.chargeID, charge_types.chargeTypeName, landlord_charges.chargeRemarks, ROUND(IFNULL(landlord_charges.chargedAmount, 0), 2) 'TotalDept', ROUND(IFNULL(landlord_charges.chargedAmount, 0) - IFNULL(SUM(landlord_receipts.paidAmount), 0), 2) 'Remaining'
		FROM landlord_charges 
		LEFT JOIN landlord_receipts ON landlord_charges.chargeID = landlord_receipts.chargeID 
		JOIN charge_types ON landlord_charges.chargeTypeID = charge_types.chargeTypeID
		WHERE landlord_charges.landlordID = '". mysqli_real_escape_string($conn, $selected_landlord_id) ."'
		GROUP BY landlord_charges.chargeID 
		HAVING Remaining > 0 
		ORDER BY LENGTH(landlord_charges.chargeID), landlord_charges.chargeID ASC") or die(mysqli_error($conn));
		if ($landlordCharges) {
			if (mysqli_num_rows($landlordCharges) > 0) {
				while ($row = mysqli_fetch_array($landlordCharges)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Data Not Found"));
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Calculate Landlord Balance
	function calculate_landlord_charge_balance($conn) {
		extract($_POST);
		$selected_landlord_id = mysqli_real_escape_string($conn, $selected_landlord_id);
		$selected_charge_id = mysqli_real_escape_string($conn, $selected_charge_id);
		$data = array();
		if ($selected_charge_id == "SinglePayment") {
			$total_depts = mysqli_query($conn, "SELECT landlord_charges.chargeID, ROUND(IFNULL(SUM(landlord_charges.chargedAmount), 0) - IFNULL(SUM(landlord_receipts.paidAmount), 0), 2) 'Remaining' FROM landlord_charges LEFT JOIN landlord_receipts ON landlord_charges.chargeID = landlord_receipts.chargeID WHERE landlord_charges.landlordID = '". $selected_landlord_id ."' GROUP BY landlord_charges.landlordID HAVING Remaining > 0") or die(mysqli_error($conn));
		} else {
			$total_depts = mysqli_query($conn, "SELECT landlord_charges.chargeID, ROUND(IFNULL(SUM(landlord_charges.chargedAmount), 0) - IFNULL(SUM(landlord_receipts.paidAmount), 0), 2) 'Remaining' FROM landlord_charges LEFT JOIN landlord_receipts ON landlord_charges.chargeID = landlord_receipts.chargeID WHERE landlord_charges.chargeID = '". $selected_charge_id ."' GROUP BY landlord_charges.chargeID HAVING Remaining > 0") or die(mysqli_error($conn));	
		}
		if (mysqli_num_rows($total_depts) > 0) {
			$total_dept_rs = mysqli_fetch_array($total_depts);
			$total_dept_amount = $total_dept_rs[1];
		} else { $total_dept_amount = 0; }

		$feedBackMsg = $total_dept_rs[0]. "###". $total_dept_amount;

		$data = json_encode(array('Status' => true, 'Message' => $feedBackMsg));

		echo $data;
		
	}
	
	// Register New Landlord Receipt
	function register_new_landlord_receipt($conn) {
		global $errorList;
		extract($_POST);
		$data = array();
		$selected_landlord_id = mysqli_real_escape_string($conn, $selected_landlord_id);
		$selected_charge_id = mysqli_real_escape_string($conn, $selected_charge_id);
		$total_dept_amount = mysqli_real_escape_string($conn, $total_dept_amount);
		$total_paid_amount = mysqli_real_escape_string($conn, $total_paid_amount);
		$remaining_balance = mysqli_real_escape_string($conn, $remaining_balance);
		$deposit_account = mysqli_real_escape_string($conn, $deposit_account);
		$payment_remarks = mysqli_real_escape_string($conn, $payment_remarks);
		$getLandlordInfo = mysqli_query($conn, "SELECT * FROM landlords WHERE landlordID = '". $selected_landlord_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($getLandlordInfo) > 0) {
			$landlord_rs = mysqli_fetch_array($getLandlordInfo);
			$landlord_mobile = $landlord_rs[8];
		}
		if ($selected_charge_id == "SinglePayment") {
			$getUnpaidLandlordCharges = mysqli_query($conn, "SELECT landlord_charges.chargeID, ROUND(IFNULL(landlord_charges.chargedAmount, 0), 2) 'TotalDept', ROUND(IFNULL(landlord_charges.chargedAmount, 0) - IFNULL(SUM(landlord_receipts.paidAmount), 0), 2) 'Remaining' FROM landlord_charges LEFT JOIN landlord_receipts ON landlord_charges.chargeID = landlord_receipts.chargeID WHERE landlord_charges.landlordID = '". mysqli_real_escape_string($conn, $selected_landlord_id) ."' GROUP BY landlord_charges.chargeID HAVING Remaining > 0 ORDER BY LENGTH(landlord_charges.chargeID), landlord_charges.chargeID ASC");
			if($getUnpaidLandlordCharges) {
				if (mysqli_num_rows($getUnpaidLandlordCharges) > 0) {
					$temp_total_paid = $total_paid_amount;
					while($unpaid_charge_rs = mysqli_fetch_row($getUnpaidLandlordCharges)) {
						$cur_charge_id = $unpaid_charge_rs[0];
						$charge_amount = $unpaid_charge_rs[1];
						if ($temp_total_paid >= $charge_amount && $temp_total_paid > 0) {
							//Generate New ID for the current inserted receipt ....
							$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM landlord_receipts") or die(mysqli_error($conn));
							if (mysqli_num_rows($getMaxReceiptID) > 0) {
								$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
								$curMaxReceiptID = $maxReceiptID[0] + 1;
								$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
							} else {
								$curMaxReceiptID = 1;
								$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
							}
							$register_receipt = mysqli_query($conn, "INSERT INTO landlord_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_landlord_id ."', '". $cur_charge_id  ."', '". $charge_amount ."', '". $deposit_account ."', '". $payment_remarks ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')");
							if ($register_receipt) {
								//Save receipts into account_transactions Table
								//Generate New ID for the current inserted row....
								$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
								if (mysqli_num_rows($getTransactionMaxID) > 0) {
									$transMaxID = mysqli_fetch_array($getTransactionMaxID);
									$currentMaxID = $transMaxID[0] + 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								} else {
									$currentMaxID = 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								}
								mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $charge_amount) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $payment_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));

							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
							$temp_total_paid -= $charge_amount;
						} else if ($temp_total_paid < $charge_amount && $temp_total_paid > 0) {
							//Generate New ID for the current inserted receipt ....
							$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM landlord_receipts") or die(mysqli_error($conn));
							if (mysqli_num_rows($getMaxReceiptID) > 0) {
								$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
								$curMaxReceiptID = $maxReceiptID[0] + 1;
								$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
							} else {
								$curMaxReceiptID = 1;
								$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
							}
							$register_receipt = mysqli_query($conn, "INSERT INTO landlord_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_landlord_id ."', '". $cur_charge_id  ."', '". $temp_total_paid ."', '". $deposit_account ."', '". $payment_remarks ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')");
							if ($register_receipt) {
								//Save receipts into account_transactions Table
								//Generate New ID for the current inserted row....
								$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
								if (mysqli_num_rows($getTransactionMaxID) > 0) {
									$transMaxID = mysqli_fetch_array($getTransactionMaxID);
									$currentMaxID = $transMaxID[0] + 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								} else {
									$currentMaxID = 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								}
								mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $temp_total_paid) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $payment_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));

							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
							$temp_total_paid = 0;
						}
					}
					$data = json_encode(array('Status' => true, 'Message' => 'Landlord receipt has been registered successfully'));
				} else {
					$errorMsg = "No Data Found";
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		} else {

			//Generate New ID for the current inserted receipt ....
			$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM landlord_receipts") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxReceiptID) > 0) {
				$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
				$curMaxReceiptID = $maxReceiptID[0] + 1;
				$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
			} else {
				$curMaxReceiptID = 1;
				$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
			}
			$register_receipt = mysqli_query($conn, "INSERT INTO landlord_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_landlord_id ."', '". $selected_charge_id  ."', '". $total_paid_amount ."', '". $deposit_account ."', '". $payment_remarks ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')");
			if ($register_receipt) {
				//Save receipts into account_transactions Table
				//Generate New ID for the current inserted row....
				$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
				if (mysqli_num_rows($getTransactionMaxID) > 0) {
					$transMaxID = mysqli_fetch_array($getTransactionMaxID);
					$currentMaxID = $transMaxID[0] + 1;
					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
				} else {
					$currentMaxID = 1;
					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
				}
				
				$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $total_paid_amount) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $payment_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."', '-', '-')");
				if ($registerTransaction) {
					$data = json_encode(array('Status' => true, 'Message' => 'Landlord receipt has been registered successfully'));
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}

			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		}
		
		echo $data;
	}
	
	// View Individual Landlord Receipt Report
	function view_individual_landlord_receipt($conn) {
		extract($_POST);
		$selected_receipt_id = mysqli_real_escape_string($conn, $selected_receipt_id);
		$reportQuery = mysqli_query($conn, "SELECT landlord_receipts.receiptID, tenants.tenantName, tenants.tenantMobile, landlord_receipts.paidAmount, payment_gateways.gatewayType, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber, landlord_receipts.receiptDescription, landlord_receipts.registerDate 
        FROM landlord_receipts
        JOIN tenants ON landlord_receipts.tenantID = tenants.tenantID
        JOIN account_numbers ON landlord_receipts.accountNoID = account_numbers.accountNoID 
        JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID
        WHERE landlord_receipts.receiptID = '". $selected_receipt_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
                    <div class="row">
                        <div class="col-sm-12 text-right">
                            <button class="btn btn-success btn-sm" id="printIndividualTenantReceipt"> <i class="fa fa-2x fa-print"></i> Print </button>
                        </div>
                    </div>      
                    <div class="row" id="individualTenantReceiptPrintArea">
                        <?php $tenant_receipt_rs = mysqli_fetch_array($reportQuery); ?>
                        <div class="col-sm-12 pb-4">
                            <div class="row">
                                <div class="col-sm-12">
							        <img src="img/reportHeader.png" width="70%" height="120px" /><br />
                                    <h2 class="text-center">Finance Office</h2>
                                    <h4 class="text-center">Tell: +252614273333 / Email: info@lighthousecore.so</h4>
                                    <h5 class="text-center">Receipt Voucher</h5>
                                </div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-1 pb-1"><h5>Receipt ID</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[0]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Tenant Name</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[1]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Mobile Number</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[2]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Paid Amount</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo "$ ". number_format($tenant_receipt_rs[3], 2); ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Deposit Name</h5></div>
            					<div class="col-sm-10 pt-1 pb-1">
            					    <h5 style="font-weight: normal;">
                					    <?php
                                            if ($tenant_receipt_rs[4] === "1") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "2") {
                                                echo $tenant_receipt_rs[5] . " " . $tenant_receipt_rs[6] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "3") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            }
                                        ?>
            					    </h5>
            			        </div>
            			    </div>
            			    <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Description</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[8]; ?></h5></div>
            				</div>
            				<div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Payment Date</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo substr($tenant_receipt_rs[9], 0, 16); ?></h5></div>
                            </div>
                            <div class="row mt-5">
								<div class="col-sm-8">&nbsp;</div>
								<div class="col-sm-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
                        </div>
                        
                        <div class="col-sm-12 pt-4">
                            <div class="row">
                                <div class="col-sm-12">
							        <img src="img/reportHeader.png" width="70%" height="110px" /><br />
                                    <h2 class="text-center">Finance Office</h2>
                                    <h4 class="text-center">Tell: +252614273333 / Email: info@lighthousecore.so</h4>
                                    <h5 class="text-center">Receipt Voucher</h5>
                                </div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-1 pb-1"><h5>Receipt ID</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[0]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Tenant Name</h5></div>
                                <div class="col-sm-10 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[1]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Mobile Number</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[2]; ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
                                <div class="col-sm-2 pt-2 pb-1"><h5>Paid Amount</h5></div>
                                <div class="col-sm-4 pt-1 pb-1"><h5 style="font-weight: normal;"><?php echo "$ ". number_format($tenant_receipt_rs[3], 2); ?></h5></div>
                            </div>
                            <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Deposit Name</h5></div>
            					<div class="col-sm-10 pt-1 pb-1">
            					    <h5 style="font-weight: normal;">
                					    <?php
                                            if ($tenant_receipt_rs[4] === "1") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "2") {
                                                echo $tenant_receipt_rs[5] . " " . $tenant_receipt_rs[6] . " (" . $tenant_receipt_rs[7] . ") ";
                                            } else if ($tenant_receipt_rs[4] === "3") {
                                                echo $tenant_receipt_rs[5] . " (" . $tenant_receipt_rs[7] . ") ";
                                            }
                                        ?>
            					    </h5>
            			        </div>
            			    </div>
            			    <div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Description</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo $tenant_receipt_rs[8]; ?></h5></div>
            				</div>
            				<div class="row pt-1 pb-1 border-bottom border-dark">
            					<div class="col-sm-2 pt-2 pb-1"><h5>Payment Date</h5></div>
            					<div class="col-sm-10 pt-2 pb-1"><h5 style="font-weight: normal;"><?php echo substr($tenant_receipt_rs[9], 0, 16); ?></h5></div>
                            </div>
                            <div class="row mt-5">
								<div class="col-sm-8">&nbsp;</div>
								<div class="col-sm-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
                        </div>

					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Receipt Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Landlord Statement
	function landlord_statement_report($conn) {
		extract($_POST);
		$selected_landlord_id = mysqli_real_escape_string($conn, $selected_landlord_id);
		$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
		$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		if ($selected_start_date == " 00:00") {
			$generatedReportQuery = mysqli_query($conn, "CALL landlord_statement('". $selected_landlord_id ."', '0000-00-00', '0000-00-00')") or die("Error is this one kkkkk : ". mysqli_error($conn));
		} else {
			$generatedReportQuery = mysqli_query($conn, "CALL landlord_statement('". $selected_landlord_id ."', '". $selected_landlord_id ."', '". $selected_end_date ."')") or die(mysqli_error($conn));
		}
		if (mysqli_num_rows($generatedReportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printTenantStatementReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="tenantStatementReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="150px" /><br />
									<center><h2 style="color: #010132;">Landlord Statement</h2></center>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
										    $conn2 = mysqli_connect("localhost", "lighthq2_user", "Lighthouse9414", "lighthq2_lighthouse_db");
								// 			$conn2 = mysqli_connect("localhost", "root", "", "lighthq2_lighthouse_db");
											$selected_tenant_info = mysqli_query($conn2, "SELECT landlordID, landlordName, landlordMobile  FROM landlords WHERE landlordID = '" . $selected_landlord_id . "'") or mysqli_error($conn);
											$tenant_rs = mysqli_fetch_array($selected_tenant_info);
										?>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Landlord ID</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[0]; ?></h6>
										</div>
										<div class="col-md-3 pb-4">
											<h5 class="font-weight-bold">Landlord Name</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[1]; ?></h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Landlord Number</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[2]; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">From Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">To Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
									</div>	

									<div class="table-responsive">
										<table class="table table-bordered table-sm">
											<thead>
												<tr class="bg-light text-center">
													<th>Date</th>
													<th>Type</th>
													<th>Description</th>
													<th>Charge</th>
													<th>Receipt</th>
													<th>Balance</th>
												</tr>
											</thead>
											<tbody>

												<?php
													$counter = 1;
													$count_statement = mysqli_num_rows($generatedReportQuery);
													while ($result = mysqli_fetch_array($generatedReportQuery)) {
														if ($counter == 1) {?>
															<tr>
																<td class="text-right" colspan="5">Previous Balance</td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2)."</b>"; ?></td>													
															</tr> <?php
														} else if ($counter == $count_statement - 1) {?>
															<tr class="bg-light font-weight-bold">
																<td class="text-right" colspan="3"> Total</td>
																<td class="text-center"> <?php echo "$ ". number_format($result[5], 2); ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[6], 2); ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														} else if ($counter == $count_statement) {?>
															<tr class="font-weight-normal">
																<td class="text-right" colspan="5">Current Balance</td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2). "</b>"; ?></td>
															</tr> <?php
														} else { ?>
															<tr>
																<td class="text-center"> <?php echo substr($result[0], 0, 10); ?></td>
																<td class="text-center"> <?php echo $result[1]; ?></td>
																<td> <?php echo $result[2]; ?></td>
																<td class="text-center"><?php if ($result[5] != 0) { echo "$ ". number_format($result[5], 2); } ?></td>
																<td class="text-center"><?php if ($result[6] != 0) { echo "$ ". number_format($result[6], 2); } ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														}
														$counter++;
													}
												?>

											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}


    // Register New Expense
    function register_new_expense($conn) {
    	global $errorList;
    	extract($_POST);
    	$data = array();
    	//Generate New ID for the current inserted expense ....
    	$getMaxExpenseID = mysqli_query($conn, "SELECT MAX(rowNo) FROM expenses") or die(mysqli_error($conn));
    	if (mysqli_num_rows($getMaxExpenseID) > 0) {
    		$maxExpenseID = mysqli_fetch_array($getMaxExpenseID);
    		$curExpenseID = $maxExpenseID[0] + 1;
    		$generatedExpenseID = "EXP" . sprintf("%04d", $curExpenseID);
    	} else {
    		$curExpenseID = 1;
    		$generatedExpenseID = "EXP" . sprintf("%04d", $curExpenseID);
    	}
    	$expense_type_name = mysqli_real_escape_string($conn, $expense_type_name);
    	$expense_amount = mysqli_real_escape_string($conn, $expense_amount);
    	$selectedAccountNo = mysqli_real_escape_string($conn, $selectedAccountNo);
    	$expense_remarks = mysqli_real_escape_string($conn, $expense_remarks);
    	$selected_payment_date = mysqli_real_escape_string($conn, $selected_payment_date. " ". date("H:i:s"));
    	$user_type = $_SESSION['userTypeID'];	
    	if ($expense_amount <= 300) {
    		if ($user_type == 'PS0001' || $user_type == 'PS0002' || $user_type == 'PS0008') {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseType, expenseAmount, accountNoID, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $expense_remarks ."', '2', '". $_SESSION['userIdd'] ."', '". $selected_payment_date ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
    			if ($register_expense) {
    				//Generate New ID for the current inserted transaction....
    				$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
    				if (mysqli_num_rows($getTransactionMaxID) > 0) {
    					$transMaxID = mysqli_fetch_array($getTransactionMaxID);
    					$currentMaxID = $transMaxID[0] + 1;
    					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    				} else {
    					$currentMaxID = 1;
    					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    				}
    				mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $selectedAccountNo . "', '" . $expense_amount . "', '0', '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '" . $expense_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
    				$data = json_encode(array('Status' => true, 'Message' => 'Expense has been registered successfully'));
    			} else {
    				$errorMsg = mysqli_error($conn);
    				$errorList[] = $errorMsg;
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}
    		} else {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseType, expenseAmount, accountNoID, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $expense_remarks ."', '1', '". $_SESSION['userIdd'] ."', '". $selected_payment_date ."', -', '-', '-', '-')") or die(mysqli_error($conn));
    			if ($register_expense) {
    				$data = json_encode(array('Status' => true, 'Message' => 'Expense has been registered successfully'));
    			} else {
    				$errorMsg = mysqli_error($conn);
    				$errorList[] = $errorMsg;
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}
    		}
    	} else if ($expense_amount > 300) {
    		if ($user_type == 'PS0001' || $user_type == 'PS0002') {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseType, expenseAmount, accountNoID, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $expense_remarks ."', '2', '". $_SESSION['userIdd'] ."', '". $selected_payment_date ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
    			if ($register_expense) {
    				//Generate New ID for the current inserted transaction....
    				$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
    				if (mysqli_num_rows($getTransactionMaxID) > 0) {
    					$transMaxID = mysqli_fetch_array($getTransactionMaxID);
    					$currentMaxID = $transMaxID[0] + 1;
    					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    				} else {
    					$currentMaxID = 1;
    					$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    				}
    				mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $selectedAccountNo . "', '" . $expense_amount . "', '0', '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '" . $expense_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
    				$data = json_encode(array('Status' => true, 'Message' => 'Expense has been registered successfully'));
    			} else {
    				$errorMsg = mysqli_error($conn);
    				$errorList[] = $errorMsg;
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}
    		} else {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseType, expenseAmount, accountNoID, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $expense_remarks ."', '1', '". $_SESSION['userIdd'] ."', '". $selected_payment_date ."', '-', '-', '-', '-')") or die(mysqli_error($conn));
    			if ($register_expense) {
    				$data = json_encode(array('Status' => true, 'Message' => 'Expense has been registered successfully'));
    			} else {
    				$errorMsg = mysqli_error($conn);
    				$errorList[] = $errorMsg;
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}
    		}
    	}
    	echo $data;
    }

    // Approve Expense
    function approve_expense($conn) {
    	global $errorList;
    	$data = array();
    	extract($_POST);
    	$getExpenseDetails = mysqli_query($conn, "SELECT * FROM expenses WHERE expenseID = '". mysqli_real_escape_string($conn, $expense_id_to_approve) ."'") or die(mysqli_error($conn));
    	if (mysqli_num_rows($getExpenseDetails) > 0) {
    		$expense_result = mysqli_fetch_array($getExpenseDetails);
    		$selectedAccountNo = $expense_result[4];
    		$expense_amount = $expense_result[3];
    		$expense_remarks = $expense_result[5];
    		$checkAccountBalance = mysqli_query($conn, "SELECT IFNULL(SUM(depositedAmount), 0) - IFNULL(SUM(withdrawalAmount), 0) 'AccountBalance' FROM account_transactions WHERE accountNoID = '" . mysqli_real_escape_string($conn, $selectedAccountNo) . "' GROUP BY accountNoID") or die(mysqli_error($conn));
    		if ($checkAccountBalance) {
    			if (mysqli_num_rows($checkAccountBalance) >= 0) {
    				$acc_bal_rs = mysqli_fetch_array($checkAccountBalance);
    				$account_balance = $acc_bal_rs[0];
    				if ($account_balance >= $expense_amount) {
    					$updateMainMenu = mysqli_query($conn, "UPDATE expenses SET expenseStatus = '2', approvedBy = '". $_SESSION['userIdd'] ."', approvedDate = '". date("Y-m-d H:i") ."' WHERE expenseID = '" . mysqli_real_escape_string($conn, $expense_id_to_approve) . "'");
    					if ($updateMainMenu) {
    						//Generate New ID for the current inserted transaction....
    						$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
    						if (mysqli_num_rows($getTransactionMaxID) > 0) {
    							$transMaxID = mysqli_fetch_array($getTransactionMaxID);
    							$currentMaxID = $transMaxID[0] + 1;
    							$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    						} else {
    							$currentMaxID = 1;
    							$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    						}
    						mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $selectedAccountNo . "', '" . $expense_amount . "', '0', '" . mysqli_real_escape_string($conn, $expense_id_to_approve) . "', '" . $expense_remarks . "', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
    						$data = json_encode(array('Status' => true, 'Message' => 'Expense has been approved successfully'));
    					} else {
    						$errorMsg = mysqli_error($conn);
    						$errorList[] = $errorMsg;
    						$data = json_encode(array('Status' => false, 'Message' => $errorList));
    					}
    				} else {
    					$balance_not_enough_msg = "Sorry, you have only $". number_format($account_balance, 2). " in your bank";
    					$data = json_encode(array('Status' => false, 'Message' => $balance_not_enough_msg));
    				}
    			}
    		} else {
    			$erroMsg = mysqli_error($conn);
    			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
    		}
    	}
    	echo $data;
    }

	// ================ END OF FINANCE MODULE ====================================================

	// ================ START OF LANDLORD PORTAL MODULE ==========================================
	
	// View Rent Payment (Landlord Portal)
	function view_rent_payment_landlord_portal($conn) {
		extract($_POST);
		$renting_id = mysqli_real_escape_string($conn, $renting_id);
		
		$generatedReportQuery = mysqli_query($conn, "SELECT tenant_charges.registerDate, charge_types.chargeTypeName, tenant_charges.chargeMonth, ROUND(IFNULL(SUM(tenant_charges.chargedAmount), 0), 2) 'ChargedAmount', ROUND(IFNULL(SUM(tenant_receipts.paidAmount), 0), 2) 'PaidAmount', ROUND(IFNULL(SUM(tenant_charges.chargedAmount), 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0), 2) 'Remaining'
        FROM tenant_charges
        JOIN charge_types ON tenant_charges.chargeTypeID = charge_types.chargeTypeID
        LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID
        WHERE tenant_charges.rentingID = '". $renting_id ."'
        GROUP BY tenant_charges.chargeMonth") or die(mysqli_error($conn));
		
		if (mysqli_num_rows($generatedReportQuery) > 0) { ?>
			<div class="card">
				<div class="card-body">
					<div class="row mt-3" id="activeRentPaymentReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="../img/reportHeader.png" width="100%" height="180px" /><br />
									<h2 class="mt-2 mb-2 text-center" style="font-weight: 700">Rent Payment Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
								 			$get_renting_info = mysqli_query($conn, "SELECT rented_properties.rentingID, CONCAT(rental_properties.propertyName, ', ', buildings.buildingName) 'PropertyName', CONCAT(property_locations.locationVillage, ', ', property_locations.locationDistrict, '-', property_locations.locationCity) 'PropertyLocation', CONCAT(landlords.landlordName, ' - ', landlords.landlordMobile) 'LandlordInformation', rented_properties.rentStartDate 'RentStartDate', rented_properties.rentEndDate 'RentEndDate'
                                            FROM rental_properties
                                            JOIN rented_properties ON rental_properties.rentalPropertyID = rented_properties.rentalPropertyID
                                            JOIN buildings ON rental_properties.buildingID = buildings.buildingID
                                            JOIN property_locations ON buildings.locationID = property_locations.locationID
                                            JOIN landlords ON rental_properties.landlordID = landlords.landlordID
                                            WHERE rented_properties.rentingID = '". $renting_id ."'") or mysqli_error($conn);
											$renting_rs = mysqli_fetch_array($get_renting_info);
										?>
										<div class="col-md-1 pb-2">
											<h5 class="font-weight-bold">Ref ID</h5>
											<h6 class="font-weight-normal"><?php echo $renting_rs[0]; ?></h6>
										</div>
										<div class="col-md-2 pb-3">
											<h5 class="font-weight-bold">Property Name</h5>
											<h6 class="font-weight-normal"><?php echo $renting_rs[1]; ?></h6>
										</div>
										<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Property Location</h5>
											<h6 class="font-weight-normal"><?php echo $renting_rs[2]; ?></h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Landlord Information</h5>
											<h6 class="font-weight-normal"><?php echo $renting_rs[3]; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Rent Start - End Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($renting_rs[4], 0, 10). " - ". substr($renting_rs[5], 0, 10); ?></h6>
										</div>
									</div>	

									<div class="table-responsive">
										<table class="table table-bordered">
											<thead>
												<tr class="bg-primary text-white text-center">
													<th>Date</th>
													<th>Type</th>
													<th>Charge Month</th>
													<th>Charged</th>
													<th>Paid</th>
													<th>Due</th>
												</tr>
											</thead>
											<tbody>

												<?php
													$counter = 1;
													$total_charged = 0;
													$total_paid = 0;
													$total_remaining = 0;
													while ($result = mysqli_fetch_array($generatedReportQuery)) {?>
														<tr>
															<td class="text-center"> <?php echo substr($result[0], 0, 10); ?></td>
															<td> <?php echo $result[1]; ?></td>
															<td> <?php echo $result[2]; ?></td>
															<td class="text-center"><?php echo "$". number_format($result[3], 2); ?></td>
															<td class="text-center"><?php echo "$". number_format($result[4], 2); ?></td>
															<td class="text-center"><?php if (($result[3] - $result[4]) > 0) { echo "<span class='text-danger'>$". number_format($result[3]-$result[4], 2). "</span>"; } else { echo "$". number_format($result[3]-$result[4], 2); } ?></td>
														</tr> <?php
    													$total_charged += $result[3];
    													$total_paid += $result[4];
    													$total_remaining += $result[3] - $result[4];
    													$counter++;
													}
													
													
													
												?>

											</tbody>
											<tfooter>
											    <tr>
													<th class="mr-3" style="text-align: right" colspan="3"> Total</th>
													<th class="text-center"><?php echo "$". number_format($total_charged, 2); ?></th>
													<th class="text-center"><?php echo "$". number_format($total_paid, 2); ?></th>
													<th class="text-center"><?php if ($total_remaining > 0) { echo "<span class='text-danger'>$". number_format($total_remaining, 2). "</span>"; } else { echo "$". number_format($total_remaining, 2); } ?></th>
												</tr>
											</tfooter>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;">Rent Payment Statement<br /><span style="font-weight: normal;"> System Generated</span></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Register New Landlord Receipt Online (Landlord Portal)
	function register_landlord_payment_receipt_online($conn) {
		global $errorList;
		extract($_POST);
		$data = array();
		$selected_charge_id = mysqli_real_escape_string($conn, $charge_idddd);
		$selected_landlord_id = mysqli_real_escape_string($conn, $landlord_idddd);
		$selected_landlord_name = mysqli_real_escape_string($conn, $landlord_namee);
		$landlord_phone_number = mysqli_real_escape_string($conn, $landlord_phone);
		$sending_phone_number = mysqli_real_escape_string($conn, $sending_number);
		$total_paid_amount = mysqli_real_escape_string($conn, $paid_amountt);
		$deposit_account = mysqli_real_escape_string($conn, $merchant_idd);
		$charge_typee = mysqli_real_escape_string($conn, $charge_typee);
		
		//Generate New ID for the current inserted receipt ....
		$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM landlord_receipts") or die(mysqli_error($conn));
		if (mysqli_num_rows($getMaxReceiptID) > 0) {
			$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
			$curMaxReceiptID = $maxReceiptID[0] + 1;
			$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
		} else {
			$curMaxReceiptID = 1;
			$generatedReceiptID = "LRV" . sprintf("%04d", $curMaxReceiptID);
		}
		
		if ($deposit_account == "ACC0001") {
			$body = array(
				'schemaVersion' => '1.0',
				'requestId' => '10111331033',
				'timestamp' => date('Y-m-d H:i'),
				'channelName' => 'WEB',
				'serviceName' => 'API_PURCHASE',
				'serviceParams' => array(
					'merchantUid' => 'M0913227',
					'apiUserId' => '1007082',
					'apiKey' => 'API-2039520938AHX',
					'paymentMethod' => 'mwallet_account',
					'payerInfo' => array(
						'accountNo' => '252' . $sending_phone_number,
					),
					'transactionInfo' => array(
						'referenceId' => '12334',
						'invoiceId' => $generatedReceiptID,
						'amount' => $total_paid_amount,
						'currency' => 'USD',
						'description' => $charged_monthh . ' Rent Payment - Online',
					),
				),
			);
	
			// Update the API endpoint URL
			$apiEndpoint = 'https://api.waafipay.net/asm';
			
			// responseMsg:
			$ch = curl_init($apiEndpoint);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
			
			$response = curl_exec($ch);
			curl_close($ch);
			
			// echo $response;
			
			// Decode the JSON response
			$checkout_response = json_decode($response, true);
			
			// Check if responseMsg is "RCS_SUCCESS"
			if (isset($checkout_response['responseMsg']) && $checkout_response['responseMsg'] == "RCS_SUCCESS") {
				
				$register_receipt = mysqli_query($conn, "INSERT INTO landlord_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_landlord_id ."', '". $selected_charge_id  ."', '". $total_paid_amount ."', '". $deposit_account ."', '". $charge_typee ." Payment - Online#". $sending_phone_number ."', 'US2100002', '". date("Y-m-d H:i") ."', '-', '-')");
				if ($register_receipt) {
					//Save receipts into account_transactions Table
					//Generate New ID for the current inserted row....
					$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
					if (mysqli_num_rows($getTransactionMaxID) > 0) {
						$transMaxID = mysqli_fetch_array($getTransactionMaxID);
						$currentMaxID = $transMaxID[0] + 1;
						$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
					} else {
						$currentMaxID = 1;
						$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
					}
					
					$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $total_paid_amount) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $charge_typee . " Payment - Online#". $sending_phone_number ."', '1', 'US2100002', '". date("Y-m-d H:i:s") ."', '-', '-')");
					if ($registerTransaction) {
						// Send payment receipt notification through tenant's mobile number
						
						$messageBody = "Walaal ". $selected_landlord_name . ", waxaan kugu wargelinaynaa in lacag dhan $". number_format($total_paid_amount, 2) ." laga qabtay telefoon number: ". $sending_phone_number ." lana dhigay Hormuud Merchant Account: 667839. Tixraaca lacag bixintaadu waa: ". $generatedReceiptID .". Wixii talo iyo tusaalooyiin ah, Fadlan naga soo wac +252614273333 ama noogu soo dir info@lighthousecore.com";

						$data = array(
							"refid" => "0", "mobile" => $landlord_phone_number, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
				
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $selected_landlord_id . "', 'Landlord Receipt Voucher', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $landlord_phone_number ."', 'US2100002', '". date("Y-m-d H:i:s") ."')");
							if ($saveSms) {
								//$success_arr = array('message' => $msg[1]);
								$successMsg = "Tenant has been registered successfully";
								$data = json_encode(array('Status' => true, 'Message' => $successMsg));
							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
					} else {
						$successMsg = $objName . " has been registered successfully";
						$data = json_encode(array('Status' => true, 'Message' => $successMsg));
					}
						$data = json_encode(array('Status' => true, 'Message' => 'Payment has been received successfully'));
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				// Handle other cases or errors
				$errorMsg = $checkout_response['responseMsg'];
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		} else if ($deposit_account == "ACC0002") {

			$request_param = array("apiKey" => "HTmlhukw8bdFgrCwIOTB1BO19Qt74pCDfNnkFcFmz", "edahabNumber" => $sending_phone_number, "amount" => $total_paid_amount, "agentCode" => "099414", "returnUrl" => "http://lighthousecore.com/admin_panel/landlord/my-overdue-charges");

			/* Encode it into a JSON string. */
			$json = json_encode($request_param, JSON_UNESCAPED_SLASHES);

			$hashed = hash('SHA256', $json."cPbek0aR9tbklSKKbziaug7ou5XC9VHBFGlWMQ");

			$url = "https://edahab.net/api/api/IssueInvoice?hash=".$hashed;

			$curl = curl_init($url);
			// Tell cURL to send a POST request.
			curl_setopt($curl, CURLOPT_POST, TRUE);

			// Set the JSON object as the POST content.
			curl_setopt($curl, CURLOPT_POSTFIELDS, $json);

			// Set the JSON content-type: application/json.
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

			// Transfer the options -- Added by MC Hamouda
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

			// Send the request.
			$result = curl_exec($curl);

			$checkout_response = json_decode($result, true);

			if (isset($checkout_response['StatusCode']) && $checkout_response['StatusCode'] == 0) {
				$saveInvoiceIdd = mysqli_query($conn, "INSERT INTO check_edahab_payments VALUES (NULL, '". mysqli_real_escape_string($conn, $checkout_response['InvoiceId']) ."', '". $selected_charge_id ."', 'Landlord', 'LandlordCharge', '". $sending_phone_number ."', 0, '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
				if ($saveInvoiceIdd) {
					$successMsg = "https://edahab.net/api/payment?invoiceId=".$checkout_response['InvoiceId'];
					$data = json_encode(array('Status' => true, 'Message' => $successMsg));	
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				$errorList[] = 'There is an error from the request response';
				$data = json_encode(array('Status' => false, 'Message' => $errorList));			
			}

		} else if ($deposit_account == "ACC0003") {

		}

		echo $data;
	}

	// Landlord Statement Online (Landlord Portal)
	function landlord_statement_report_online($conn) {
		extract($_POST);
		$selected_landlord_id = mysqli_real_escape_string($conn, $_SESSION['landlordIdd']);
		$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
		$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		if ($selected_start_date == " 00:00") {
			$generatedReportQuery = mysqli_query($conn, "CALL landlord_statement_online('". $selected_landlord_id ."', '0000-00-00', '0000-00-00')") or die("Error is this one kkkkk : ". mysqli_error($conn));
		} else {
			$generatedReportQuery = mysqli_query($conn, "CALL landlord_statement_online('". $selected_landlord_id ."', '". $selected_start_date ."', '". $selected_end_date ."')") or die(mysqli_error($conn));
		}
		if (mysqli_num_rows($generatedReportQuery) > 0) { ?>
			<div class="card">
				<div class="card-body">
					<div class="row mt-3" id="tenantStatementReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="../img/reportHeader.png" width="100%" height="180px" /><br />
									<h2 class="mt-2 mb-2 text-center" style="font-weight: 700">Tenant Statement Online</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
											$conn2 = mysqli_connect("localhost", "lighthq2_user", "Lighthouse9414", "lighthq2_lighthouse_db");
								// 			$conn2 = mysqli_connect("localhost", "root", "", "lighthq2_lighthouse_db");
											$selected_landlord_info = mysqli_query($conn2, "SELECT landlordID, landlordName, landlordMobile  FROM landlords WHERE landlordID = '" . $selected_landlord_id . "'") or mysqli_error($conn);
											$landlord_rs = mysqli_fetch_array($selected_landlord_info);
										?>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Tenant ID</h5>
											<h6 class="font-weight-normal"><?php echo $landlord_rs[0]; ?></h6>
										</div>
										<div class="col-md-3 pb-4">
											<h5 class="font-weight-bold">Tenant Name</h5>
											<h6 class="font-weight-normal"><?php echo $landlord_rs[1]; ?></h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Mobile Number</h5>
											<h6 class="font-weight-normal"><?php echo $landlord_rs[2]; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">From Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">To Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
									</div>	

									<div class="table-responsive">
										<table class="table table-bordered">
											<thead>
												<tr class="bg-primary text-white text-center">
													<th>Date</th>
													<th>Type</th>
													<th>Description</th>
													<th>Charge</th>
													<th>Receipt</th>
													<th>Balance</th>
												</tr>
											</thead>
											<tbody>

												<?php
													$counter = 1;
													$count_statement = mysqli_num_rows($generatedReportQuery);
													while ($result = mysqli_fetch_array($generatedReportQuery)) {
														if ($counter == 1) {?>
															<tr>
																<td colspan="5" style="text-align: right">Previous Balance &nbsp; </td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2)."</b>"; ?></td>													
															</tr> <?php
														} else if ($counter == $count_statement - 1) {?>
															<tr class="bg-light font-weight-bold">
																<td colspan="3" style="text-align: right"> Total</td>
																<td class="text-center" style="font-weight: 600"> <?php echo "$ ". number_format($result[5], 2); ?></td>
																<td class="text-center" style="font-weight: 600"> <?php echo "$ ". number_format($result[6], 2); ?></td>
																<td class="text-center" style="font-weight: 600"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														} else if ($counter == $count_statement) {?>
															<tr class="font-weight-normal">
																<td colspan="5" style="text-align: right">Current Balance &nbsp; </td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2). "</b>"; ?></td>
															</tr> <?php
														} else { ?>
															<tr>
																<td class="text-center"> <?php echo substr($result[0], 0, 10); ?></td>
																<td class="text-center"> <?php echo $result[1]; ?></td>
																<td> <?php echo $result[2]; ?></td>
																<td class="text-center"><?php if ($result[5] != 0) { echo "$ ". number_format($result[5], 2); } ?></td>
																<td class="text-center"><?php if ($result[6] != 0) { echo "$ ". number_format($result[6], 2); } ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														}
														$counter++;
													}
												?>

											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;">Generated Statement<br /><span style="font-weight: normal;"> Online Statement</span></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Fetch Tenant Maintenance Request (Landlord Portal)
	function fetch_tenant_portal_maintenance_request_chat_box_landlord_portal($conn) {

		extract($_POST);
		$request_tracking_number = mysqli_real_escape_string($conn, $request_tracking_number);
		$_SESSION['maintenanceRequestTrackingIdd'] = $request_tracking_number;
		$reportQuery = mysqli_query($conn, "SELECT * FROM request_messages WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' ORDER BY messageDate ASC");
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				while($report_rs = mysqli_fetch_array($reportQuery)) {
					if ($report_rs[5] == $_SESSION['tenantIdd']) {
					    
					    // Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: right;">
									<div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
										<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
									    </span>
									</div>
								</div>
							</div><?php
						} else {
    					    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: right;">
    				                    <div class="bg-success text-white" style="display: inline-block; max-width: 70%; padding: 7px 10px 0px 10px; border-radius: 15px 0px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
                                            <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
						        ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
						                <div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
						                    <?php echo nl2br($report_rs[2]); ?>
                                            <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>
								        </div>
								    </div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
								        <div class="bg-success text-white" style="max-width: 70%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
                                            <script src="../tenant/assets/js/venobox.js"></script>
											<script>
												$(document).ready(function () {
													$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
												})
											</script>
											<?php
												$message_photos = explode("###", $report_rs[3]);
												foreach($message_photos as $photo) {
													?><div class="p-1">
														<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
													</div><?php
												}
											?>
                                            <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>
								        </div>
								    </div>
								</div><?php
							} 
				        }
						
					} else {
					    
					    // Messages from the Admin Buddy

						$getRespondingEmployeeInfo = mysqli_query($conn, "SELECT employees.employeePhoto, employees.employeeName, employee_positions.positionName, system_users.loginStatus
						FROM system_users
						JOIN employees ON system_users.employeeID = employees.employeeID
						JOIN employee_positions ON employees.employeePosition = employee_positions.positionID
						WHERE system_users.userID = '". mysqli_real_escape_string($conn, $report_rs[5]) ."'") or die(mysqli_error($conn));
						if (mysqli_num_rows($getRespondingEmployeeInfo) > 0) {
							$responding_emp_rs = mysqli_fetch_array($getRespondingEmployeeInfo);
						}
						
						// Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: left;">
									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
									</div>
								</div>
							</div><?php
						} else {
						    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
                                ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
    								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    										<?php echo nl2br($report_rs[2]); ?>
    									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    									</div>
    								</div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
								</div><?php
						    }
						}

					}
				}
				mysqli_query($conn, "UPDATE request_messages SET messageStatus = '1' WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' AND messageSender <> '". $_SESSION['tenantIdd'] ."'") or die(mysqli_error($conn));
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

    // Fetch Live Landlord Maintenance Request (Landlord Portal)
	function fetch_live_landlord_portal_maintenance_request_chat_box_landlord_portal($conn) {

		extract($_POST);
		$reportQuery = mysqli_query($conn, "SELECT * FROM request_messages WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' ORDER BY messageDate ASC");
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				while($report_rs = mysqli_fetch_array($reportQuery)) {
					if ($report_rs[5] == $_SESSION['tenantIdd']) {
					    
					    // Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: right;">
									<div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
										<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
									    </span>
									</div>
								</div>
							</div><?php
						} else {
    					    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: right;">
    				                    <div class="bg-success text-white" style="display: inline-block; max-width: 70%; padding: 7px 10px 0px 10px; border-radius: 15px 0px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
    										<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?> <i class="bi bi-check2-all fa-lg text-info"></i></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
						        ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
						                <div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
						                    <?php echo nl2br($report_rs[2]); ?>
						                    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?> <i class="bi bi-check2-all fa-lg text-info"></i></span>
								        </div>
								    </div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
								        <div class="bg-success text-white" style="max-width: 70%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
                                            <script src="../tenant/assets/js/venobox.js"></script>
											<script>
												$(document).ready(function () {
													$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
												})
											</script>
											<?php
												$message_photos = explode("###", $report_rs[3]);
												foreach($message_photos as $photo) {
													?><div class="p-1">
														<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
													</div><?php
												}
											?>
											<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?> <i class="bi bi-check2-all fa-lg text-info"></i></span>
								        </div>
								    </div>
								</div><?php
							} 
				        }
						
					} else {
					    
					    // Messages from the Admin Buddy

						$getRespondingEmployeeInfo = mysqli_query($conn, "SELECT employees.employeePhoto, employees.employeeName, employee_positions.positionName, system_users.loginStatus
						FROM system_users
						JOIN employees ON system_users.employeeID = employees.employeeID
						JOIN employee_positions ON employees.employeePosition = employee_positions.positionID
						WHERE system_users.userID = '". mysqli_real_escape_string($conn, $report_rs[5]) ."'") or die(mysqli_error($conn));
						if (mysqli_num_rows($getRespondingEmployeeInfo) > 0) {
							$responding_emp_rs = mysqli_fetch_array($getRespondingEmployeeInfo);
						}
						
						// Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: left;">
									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
									</div>
								</div>
							</div><?php
						} else {
						    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
                                ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
    								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    										<?php echo nl2br($report_rs[2]); ?>
    									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    									</div>
    								</div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
								</div><?php
						    }
						}

					}
				}
				mysqli_query($conn, "UPDATE request_messages SET messageStatus = '1' WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' AND messageSender <> '". $_SESSION['tenantIdd'] ."'") or die(mysqli_error($conn));
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Search Landlord Short Messages (SMS) (Landlord Portal)
	function search_landlord_short_messages_sms($conn) {
		extract($_POST);
		$selected_message_subject = mysqli_real_escape_string($conn, $selected_message_subject);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
			// $selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}

		$generatedReportQuery = "SELECT bulk_sms.smsID, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, bulk_sms.sentDate
		FROM bulk_sms WHERE bulk_sms.receiverID = '". $_SESSION['landlordIdd'] ."' ";
		if ($selected_message_subject != "") { 
			$generatedReportQuery .= "AND bulk_sms.messageSubject = '". $selected_message_subject ."' "; 
		}

		if ($selected_date_type != 0) {
			if ($selected_message_subject != "") {
				$generatedReportQuery .= "AND bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "AND bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY bulk_sms.smsID DESC";
// 		echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="col-lg-12">
				<div class="card">
					<div class="card-body">
						<div class="row mt-3 mb-3">
							<?php
								if ($selected_date_type == 0) {
									$date_type_label = "All Date";
									$tenant_sms_start_date = "-";
									$tenant_sms_end_date = "-";
								} else if ($selected_date_type == 1) {
									$date_type_label = "Today";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 2) {
									$date_type_label = "Yesterday";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 3) {
									$date_type_label = "Last 3 Days";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 4) {
									$date_type_label = "This Week";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 5) {
									$date_type_label = "Last 10 Days";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 6) {
									$date_type_label = "This Month";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 7) {
									$date_type_label = "This Year";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 8) {
									$date_type_label = "Customized Date";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								}
							?>
							<div class="col-md-5 pb-2">
								<h6 class="font-weight-bold">Message Subject</h6>
								<p><?php if ($selected_message_subject === "") { echo "-"; } else { echo $selected_message_subject; } ?></p>
							</div>
							<div class="col-md-3 pb-2">
								<h6 class="font-weight-bold">Date Type</h6>
								<p><?php echo $date_type_label; ?></p>
							</div>
							<div class="col-md-2 pb-2">
								<h6 class="font-weight-bold">Start Date</h6>
								<p><?php echo substr($tenant_sms_start_date, 0, 10); ?></p>
							</div>
							<div class="col-md-2 pb-2">
								<h6 class="font-weight-bold">End Date</h6>
								<p><?php echo substr($tenant_sms_end_date, 0, 10); ?></p>
							</div>							
						</div>
						<div class="table-responsive mt-3">
							<table class="table table-stripe" id="tenantShortMessagesTable">
								<thead>
									<tr class="text-white bg-info">
										<th class="text-center">SMS ID</th>
										<th class="text-left">Subject</th>
										<th class="text-left">Body</th>
										<th class="text-center">Status</th>
										<th class="text-center">Sent Date</th>
									</tr>
								</thead>
								<tbody>
									<?php
										$x = 1;
										while ($request_rs = mysqli_fetch_array($reportQuery)) { ?>
											<tr>
												<td class="text-center" width="8%"><?php echo $request_rs[0]; ?></td>
												<td class="text-left" width="20%"><?php echo $request_rs[1]; ?></td>
												<td class="text-justify"><a href="#" class="btnOpenLandlordShortMessageContentDetailsModalLandlordPortal" data-id="<?php echo $request_rs[0]; ?>" data-bs-toggle="modal" data-bs-target="#landlordShortMessageContentDetailsModal"><?php echo substr($request_rs[2], 0, 100). " ..."; ?></a></td>
												<td class="text-center" width="7%">
													<?php if ($request_rs[3] == 1) { ?><span class="badge text-success p-2"><i class="bi bi-check2-all"></i> Sent</span><?php } ?>
												</td>
												<td class="text-center" width="15%"><?php echo substr($request_rs[4], 0, 16); ?></td>
											</tr><?php
											$x++;
										}
									?>
								</tbody>
							</table>
						</div>

					</div>
				</div>

			</div><?php
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Short Messages (SMS) Not Found</h6>
						</div>
					</div>
				</div>
			</div><?php
		}
	}

	// Read Full Landlord Short Messages (SMS) (Landlord Portal)
	function fetch_landlord_short_message_content_details_landlord_portal($conn) {

		extract($_POST);
		$short_message_id = mysqli_real_escape_string($conn, $short_message_id);
		$generatedReportQuery = "SELECT bulk_sms.smsID, landlords.landlordName, bulk_sms.telephoneSentTo, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, system_users.Username, employees.employeeName, bulk_sms.sentDate
		FROM bulk_sms
		JOIN landlords ON bulk_sms.receiverID = landlords.landlordID
		JOIN system_users ON bulk_sms.senderUser = system_users.userID
		JOIN employees ON system_users.employeeID = employees.employeeID
		WHERE bulk_sms.smsID = '". $short_message_id ."'";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				$report_rs = mysqli_fetch_array($reportQuery);
				?>
					<div class="row m-2" style="margin: 0xp;">
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-key"></i> Message ID</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[0]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Receiver Name</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[1]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-phone"></i> Mobile No</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo "+252 ". $report_rs[2]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-book"></i> Message Subject</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[3]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-envelope-open"></i> Message Body</strong></h6></div>
						<div class="col-md-8 pt-2" style="text-align: justify;"><?php echo $report_rs[4]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-info-circle"></i> Message Status</strong></h6></div>
						<div class="col-md-8 pt-2 text-success" style="text-align: justify;"><?php if ($report_rs[5] == 1) { echo "<i class='bi bi-check2-all'></i> Sent"; } ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Sender User</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[6]. " (<strong>". $report_rs[7]. "</strong>)"; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-calendar"></i> Sent Date</strong></h6></div>
						<div class="col-md-8 p-2"><?php echo substr($report_rs[8], 0, 16); ?></div>
					</div>
				<?php
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Change Passcode (Landlord Portal)
	function change_landlord_passcode_landlord_poretal($conn) {
		global $ereyFure;
		global $errorList;

		$data = array();
		extract($_POST);

		$landlord_current_passcode = mysqli_real_escape_string($conn, $landlord_current_passcode);
		$landlord_new_passcode = mysqli_real_escape_string($conn, $landlord_new_passcode);
		$landlord_confirm_passcode = mysqli_real_escape_string($conn, $landlord_new_passcode);

		if ($landlord_new_passcode != $landlord_confirm_passcode) {
			$errorMsg = "Sorry!! Passwords are not matching, please check it...";
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			$getUsernamePassword = mysqli_query($conn, "SELECT * FROM landlords WHERE landlordID = '" . $_SESSION['landlordIdd'] . "' AND landlordPasscode = '". $landlord_current_passcode ."'");
			if ($getUsernamePassword) {
				if (mysqli_num_rows($getUsernamePassword) > 0) {
					$changePass = mysqli_query($conn, "UPDATE landlords SET landlordPasscode = '" . mysqli_real_escape_string($conn, $landlord_new_passcode) . "' WHERE landlordID = '" . $_SESSION['landlordIdd'] . "'");
					if ($changePass) {
						$data = json_encode(array('Status' => true, 'Message' => 'Your passcode has been changed successfully'));
					} else {
						$errorMsg = mysqli_error($conn);
						$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
					}
				} else {
					$errorMsg = "Current passcode is wrong, please check again";
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}

			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		}

		echo $data;
	}	
	
	// ================ END OF LANDLORD PORTAL MODULE ============================================
	
	
	// ================ START OF TENANT PORTAL MODULE ============================================

	// Register New Tenant Receipt Online (Tenant Portal)
	function register_tenant_payment_receipt_online($conn) {
		global $errorList;
		extract($_POST);
		$data = array();
		$selected_renting_id = mysqli_real_escape_string($conn, $renting_iddd);
		$selected_tenant_id = mysqli_real_escape_string($conn, $tenant_idddd);
		$selected_tenant_name = mysqli_real_escape_string($conn, $tenant_namee);
		$tenant_gender_type = mysqli_real_escape_string($conn, $tenant_genderr);
		$tenant_phone_number = mysqli_real_escape_string($conn, $tenant_phone);
		$sending_phone_number = mysqli_real_escape_string($conn, $sending_number);
		$selected_charge_id = mysqli_real_escape_string($conn, $charge_idddd);
		$total_paid_amount = mysqli_real_escape_string($conn, $paid_amountt);
		$deposit_account = mysqli_real_escape_string($conn, $merchant_idd);
		$charged_monthh = mysqli_real_escape_string($conn, $charged_monthh);
		
		//Generate New ID for the current inserted receipt ....
		$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenant_receipts") or die(mysqli_error($conn));
		if (mysqli_num_rows($getMaxReceiptID) > 0) {
			$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
			$curMaxReceiptID = $maxReceiptID[0] + 1;
			$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
		} else {
			$curMaxReceiptID = 1;
			$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
		}
		
		if ($deposit_account == "ACC0001") {
			$body = array(
				'schemaVersion' => '1.0',
				'requestId' => '10111331033',
				'timestamp' => date('Y-m-d H:i'),
				'channelName' => 'WEB',
				'serviceName' => 'API_PURCHASE',
				'serviceParams' => array(
					'merchantUid' => 'M0913227',
					'apiUserId' => '1007082',
					'apiKey' => 'API-2039520938AHX',
					'paymentMethod' => 'mwallet_account',
					'payerInfo' => array(
						'accountNo' => '252' . $sending_phone_number,
					),
					'transactionInfo' => array(
						'referenceId' => '12334',
						'invoiceId' => $generatedReceiptID,
						'amount' => $total_paid_amount,
						'currency' => 'USD',
						'description' => $charged_monthh . ' Rent Payment - Online',
					),
				),
			);
	
			// Update the API endpoint URL
			$apiEndpoint = 'https://api.waafipay.net/asm';
			
			// responseMsg:
			$ch = curl_init($apiEndpoint);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
			
			$response = curl_exec($ch);
			curl_close($ch);
			
			// echo $response;
			
			// Decode the JSON response
			$checkout_response = json_decode($response, true);
			
			// Check if responseMsg is "RCS_SUCCESS"
			if (isset($checkout_response['responseMsg']) && $checkout_response['responseMsg'] == "RCS_SUCCESS") {
				
				$register_receipt = mysqli_query($conn, "INSERT INTO tenant_receipts VALUES (NULL, '". $generatedReceiptID ."', '". $selected_renting_id ."', '". $selected_tenant_id ."', '". $selected_charge_id  ."', '". $total_paid_amount ."', '". $deposit_account ."', '". $charged_monthh ." Rent Payment - Online#". $sending_phone_number. "', 'US2100002', '". date("Y-m-d H:i") ."', '-', '-')");
				if ($register_receipt) {
					//Save receipts into account_transactions Table
					//Generate New ID for the current inserted row....
					$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
					if (mysqli_num_rows($getTransactionMaxID) > 0) {
						$transMaxID = mysqli_fetch_array($getTransactionMaxID);
						$currentMaxID = $transMaxID[0] + 1;
						$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
					} else {
						$currentMaxID = 1;
						$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
					}
					
					$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $total_paid_amount) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $charged_monthh . " Rent Payment - Online#". $sending_phone_number. "', '1', 'US2100002', '". date("Y-m-d H:i:s") ."', '-', '-')");
					if ($registerTransaction) {
						// Send payment receipt notification through tenant's mobile number
						if ($tenant_gender_type == "Male") {
						    $cutomer_information = "Mudane ". $selected_tenant_name;
						} else if ($tenant_gender_type == "Female") {
						    $cutomer_information = "Marwo ". $selected_tenant_name;
						}
						
						$messageBody = $cutomer_information. ", waxaan kugu wargelinaynaa in lacag dhan $". number_format($total_paid_amount, 2) ." laga qabtay telefoon number: ". $sending_phone_number ." lana dhigay Hormuud Merchant Account: 667839. Tixraaca lacag bixintaadu waa: ". $generatedReceiptID .". Wixii talo iyo tusaalooyiin ah, Fadlan naga soo wac +252614273333 ama noogu soo dir info@lighthousecore.com";

						$data = array(
							"refid" => "0", "mobile" => $tenant_phone_number, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
						);
						$data1 = json_encode($data);
						$username = 'lighthouse1';
						$password = 'Sja3wj5EhSr4tggVLJmcCw==';
				
						$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
						$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
						curl_setopt($ch, CURLOPT_HEADER, 1);
						curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$return = curl_exec($ch);
						$return = explode(':', $return);
				
						// for ($i=0; $i < count($return) ; $i++) {
						//     echo $i. ':' . $return[$i];
						// }
						$stat = explode('"', $return[17]);
						$msg1 = explode(',', $return[20]);
						$msg = explode('"', $msg1[0]);
						// print_r($msg[1]);
						
						if ($stat[1] != 'Failed.') {
							$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . $selected_tenant_id . "', 'Tenant Receipt Voucher', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $tenant_phone_number ."', 'US2100002', '". date("Y-m-d H:i:s") ."')");
							if ($saveSms) {
								//$success_arr = array('message' => $msg[1]);
								$successMsg = "Tenant has been registered successfully";
								$data = json_encode(array('Status' => true, 'Message' => $successMsg));
							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
						} else {
							$errorList[] = $msg[1];
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
					} else {
						$successMsg = $objName . " has been registered successfully";
						$data = json_encode(array('Status' => true, 'Message' => $successMsg));
					}
						$data = json_encode(array('Status' => true, 'Message' => 'Payment has been received successfully'));
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				// Handle other cases or errors
				$errorMsg = $checkout_response['responseMsg'];
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		} else if ($deposit_account == "ACC0002") {

			$request_param = array("apiKey" => "HTmlhukw8bdFgrCwIOTB1BO19Qt74pCDfNnkFcFmz", "edahabNumber" => $sending_phone_number, "amount" => $total_paid_amount, "agentCode" => "099414", "returnUrl" => "http://lighthousecore.com/admin_panel/tenant/my-online-payment");

			/* Encode it into a JSON string. */
			$json = json_encode($request_param, JSON_UNESCAPED_SLASHES);

			$hashed = hash('SHA256', $json."cPbek0aR9tbklSKKbziaug7ou5XC9VHBFGlWMQ");

			$url = "https://edahab.net/api/api/IssueInvoice?hash=".$hashed;

			$curl = curl_init($url);
			// Tell cURL to send a POST request.
			curl_setopt($curl, CURLOPT_POST, TRUE);

			// Set the JSON object as the POST content.
			curl_setopt($curl, CURLOPT_POSTFIELDS, $json);

			// Set the JSON content-type: application/json.
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

			// Transfer the options -- Added by MC Hamouda
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

			// Send the request.
			$result = curl_exec($curl);

			$checkout_response = json_decode($result, true);

			if (isset($checkout_response['StatusCode']) && $checkout_response['StatusCode'] == 0) {
				$saveInvoiceIdd = mysqli_query($conn, "INSERT INTO check_edahab_payments VALUES (NULL, '". mysqli_real_escape_string($conn, $checkout_response['InvoiceId']) ."', '". $selected_charge_id ."', 'MonthlyRentCharge', '". $sending_phone_number ."', 0, '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
				if ($saveInvoiceIdd) {
					$successMsg = "https://edahab.net/api/payment?invoiceId=".$checkout_response['InvoiceId'];
					$data = json_encode(array('Status' => true, 'Message' => $successMsg));	
				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			} else {
				$errorList[] = 'There is an error from the request response';
				$data = json_encode(array('Status' => false, 'Message' => $errorList));			
			}

		} else if ($deposit_account == "ACC0003") {

		}

		echo $data;
	}

	function check_invoice_payment_with_edahab($conn) {
		global $errorList;
		extract($_POST);
		$checked_invoices = array();
		$data = array();
		
		// Fetch all unchecked invoices list
		$getUncheckedInvoices = mysqli_query($conn, "SELECT * FROM check_edahab_payments WHERE invoiceStatus = 0");
		if ($getUncheckedInvoices) {
			if (mysqli_num_rows($getUncheckedInvoices) > 0) {
			    
		    	$request_param = array("apiKey" => "HTmlhukw8bdFgrCwIOTB1BO19Qt74pCDfNnkFcFmz", "invoiceId" => $invoice_rs[1]);
				/* Encode it into a JSON string. */
				$json = json_encode($request_param, JSON_UNESCAPED_SLASHES);
				$hashed = hash('SHA256', $json."cPbek0aR9tbklSKKbziaug7ou5XC9VHBFGlWMQ");
				$url = "https://edahab.net/api/api/CheckInvoiceStatus?hash=".$hashed;
				$curl = curl_init($url);
				// Tell cURL to send a POST request.
				curl_setopt($curl, CURLOPT_POST, TRUE);
				// Set the JSON object as the POST content.
				curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
				// Set the JSON content-type: application/json.
				curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
				// Transfer the options -- Added by MC Hamouda
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
				// Send the request.
				$result = curl_exec($curl);
				$checkout_response = json_decode($result, true);
				if (isset($checkout_response['InvoiceStatus']) && $checkout_response['InvoiceStatus'] == "Paid") {
				    
				    while ($invoice_rs = mysqli_fetch_row($getUncheckedInvoices)) {
				        
    				    // Check Invoice Status Wether it is Paid of Pending - One by One
    				    if ($invoice_rs[3] == "Tenant") {
    				        
    				        if ($invoice_rs[4] == "MonthlyRentCharge") {
    				            
        						$getInvoiceInformation = mysqli_query($conn, "SELECT tenant_charges.rentingID, tenants.tenantID, tenants.tenantName, tenants.tenantGender, tenants.tenantMobile, tenant_charges.chargeID, tenant_charges.chargedAmount, tenant_charges.chargeMonth FROM tenant_charges JOIN tenants ON tenant_charges.tenantID = tenants.tenantID WHERE tenant_charges.chargeID = '". mysqli_real_escape_string($conn, $invoice_rs[2]) ."'") or die(mysqli_error($conn));
        						if ($getInvoiceInformation) {
        							if (mysqli_num_rows($getInvoiceInformation) > 0) {
        								$invoice_info_rs = mysqli_fetch_array($getInvoiceInformation);
        								//Generate New ID for the current inserted receipt ....
                                		$getMaxReceiptID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenant_receipts") or die(mysqli_error($conn));
                                		if (mysqli_num_rows($getMaxReceiptID) > 0) {
                                			$maxReceiptID = mysqli_fetch_array($getMaxReceiptID);
                                			$curMaxReceiptID = $maxReceiptID[0] + 1;
                                			$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
                                		} else {
                                			$curMaxReceiptID = 1;
                                			$generatedReceiptID = "TRV" . sprintf("%04d", $curMaxReceiptID);
                                		}
        								$register_receipt = mysqli_query($conn, "INSERT INTO tenant_receipts VALUES (NULL, '". $generatedReceiptID ."', '". mysqli_real_escape_string($conn, $invoice_info_rs[0]) ."', '". mysqli_real_escape_string($conn, $invoice_info_rs[1]) ."', '". mysqli_real_escape_string($conn, $invoice_info_rs[4])  ."', '". mysqli_real_escape_string($conn, $invoice_info_rs[5]) ."', 'ACC0002', '". mysqli_real_escape_string($conn, $invoice_info_rs[6]) ." Rent Payment - Online', 'US2100002', '". date("Y-m-d H:i") ."', '-', '-', '-', '-')");
        								if ($register_receipt) {
        									//Save receipts into account_transactions Table
        									//Generate New ID for the current inserted row....
        									$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
        									if (mysqli_num_rows($getTransactionMaxID) > 0) {
        										$transMaxID = mysqli_fetch_array($getTransactionMaxID);
        										$currentMaxID = $transMaxID[0] + 1;
        										$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
        									} else {
        										$currentMaxID = 1;
        										$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
        									}
        									$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', 'ACC0002', '0', '" . mysqli_real_escape_string($conn, $invoice_info_rs[5]) . "', '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . mysqli_real_escape_string($conn, $invoice_info_rs[6]) . " Rent Payment - Online', '1', 'US2100002', '". date("Y-m-d H:i:s") ."', '-', '-')");
        									if ($registerTransaction) {
        										// Update the invoice status into 1 after receiving the balance
        										$updateInvoiceStatus = mysqli_query($conn, "UPDATE check_edahab_payments SET invoiceStatus = 1 WHERE invoiceID = '". mysqli_real_escape_string($conn, $invoice_rs[1]) ."'") or die(mysqli_errno($conn));
        										if ($updateInvoiceStatus) {
        											// Send payment receipt notification through tenant's mobile number
        											if ($invoice_info_rs[3] == "Male") {
                            						    $cutomer_information = "Mudane ". $invoice_info_rs[2];
                            						} else if ($invoice_info_rs[3] == "Female") {
                            						    $cutomer_information = "Marwo ". $invoice_info_rs[2];
                            						}
                            						$messageBody = $cutomer_information. ", waxaan kugu wargelinaynaa in lacag dhan $". number_format($invoice_info_rs[6], 2) ." laga qabtay telefoon number: ". $invoice_rs[5] ." lana dhigay eDahab Merchant Account: 099414. Tixraaca lacag bixintaadu waa: ". $generatedReceiptID .". Wixii talo iyo tusaalooyiin ah, Fadlan naga soo wac +252614273333 ama noogu soo dir email info@lighthousecore.com";
        											$data = array(
        												"refid" => "0", "mobile" => $invoice_info_rs[4], "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
        											);
        											$data1 = json_encode($data);
        											$username = 'lighthouse1';
        											$password = 'Sja3wj5EhSr4tggVLJmcCw==';
        											$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
        											$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
        											curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        											curl_setopt($ch, CURLOPT_HEADER, 1);
        											curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
        											curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
        											curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        											$return = curl_exec($ch);
        											$return = explode(':', $return);
        											// for ($i=0; $i < count($return) ; $i++) {
        											//     echo $i. ':' . $return[$i];
        											// }
        											$stat = explode('"', $return[17]);
        											$msg1 = explode(',', $return[20]);
        											$msg = explode('"', $msg1[0]);
        											// print_r($msg[1]);
        											if ($stat[1] != 'Failed.') {
        												$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedReceiptID) . "', '" . mysqli_real_escape_string($conn, $invoice_info_rs[1]) . "', 'Tenant Receipt Voucher', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". mysqli_real_escape_string($conn, $invoice_info_rs[4]) ."', 'US2100002', '". date("Y-m-d H:i:s") ."')");
        												if ($saveSms) {
        													//$success_arr = array('message' => $msg[1]);
        													$successMsg = "Payment has been received successfully";
        													$data = json_encode(array('Status' => true, 'Message' => $successMsg));
        												} else {
        													$errorList[] = mysqli_error($conn);
        													$data = json_encode(array('Status' => false, 'Message' => $errorList));
        												}
        											} else {
        												$errorList[] = $msg[1];
        												$data = json_encode(array('Status' => false, 'Message' => $errorList));
        											}
        										} else {
        											$errorList[] = mysqli_error($conn);
        											$data = json_encode(array('Status' => false, 'Message' => $errorList));
        										}
    										
        									} else {
        										$successMsg = $objName . " has been registered successfully";
        										$data = json_encode(array('Status' => true, 'Message' => $successMsg));
        									}
        									$data = json_encode(array('Status' => true, 'Message' => 'Payment has been received successfully'));
        								} else {
        									$errorList[] = mysqli_error($conn);
        									$data = json_encode(array('Status' => false, 'Message' => $errorList));
        								}
        							}
        						} else {
									$errorList[] = mysqli_error($conn);
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								}
				    
				            } else if ($invoice_rs[4] == "RentalBookingOnline") {
				                
				                $getInvoiceInformation = mysqli_query($conn, "SELECT tenants.tenantID, tenants.tenantName, tenants.tenantMobile, booked_properties.bookingID, booked_properties.rentalPropertyID, booked_properties.bookingFee, booked_properties.bookingRemarks 
        						FROM booked_properties 
        						JOIN tenants ON booked_properties.tenantID = tenants.tenantID 
        						WHERE booked_properties.bookingID = '". mysqli_real_escape_string($conn, $invoice_rs[2]) ."'") or die(mysqli_error($conn));
        						if ($getInvoiceInformation) {
        							if (mysqli_num_rows($getInvoiceInformation) > 0) {
        								$invoice_info_rs = mysqli_fetch_array($getInvoiceInformation);

    									//Generate New ID for the current inserted row....
    									$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
    									if (mysqli_num_rows($getTransactionMaxID) > 0) {
    										$transMaxID = mysqli_fetch_array($getTransactionMaxID);
    										$currentMaxID = $transMaxID[0] + 1;
    										$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    									} else {
    										$currentMaxID = 1;
    										$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
    									}
        									
    									$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', 'ACC0002', '0', '" . mysqli_real_escape_string($conn, $invoice_info_rs[5]) . "', '" . mysqli_real_escape_string($conn, $invoice_info_rs[3]) . "', '" . mysqli_real_escape_string($conn, $invoice_info_rs[6]) . " Rent Payment - Online', '1', 'US2100002', '". date("Y-m-d H:i:s") ."', '-', '-')");
    									if ($registerTransaction) {
    										// Update the invoice status into 1 after receiving the balance
    										$updateInvoiceStatus = mysqli_query($conn, "UPDATE check_edahab_payments SET invoiceStatus = 1 WHERE invoiceID = '". mysqli_real_escape_string($conn, $invoice_rs[1]) ."'") or die(mysqli_errno($conn));
    										if ($updateInvoiceStatus) {
    											// Send payment receipt notification through tenant's mobile number
    											$messageBody = "Hello Dear ". $invoice_info_rs[1] .", this message is to inform you that the amount of $". number_format($invoice_info_rs[5], 2) ." has been received from ". $invoice_rs[4] ." as the booking payment for ". $invoice_info_rs[4] ." through the Hormuud Merchant Account: 667839. Your Booking ID: ". $invoice_info_rs[3] .". NB. Your booking will expire within 24 hours and then there will be no refunds. For further information, please contact +252614273333 or visit our website https://lighthousecore.com. Wish you the best.";
    											$data = array(
    												"refid" => "0", "mobile" => $invoice_info_rs[2], "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
    											);
    											$data1 = json_encode($data);
    											$username = 'lighthouse1';
    											$password = 'Sja3wj5EhSr4tggVLJmcCw==';

    											$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
    											$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
    											curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    											curl_setopt($ch, CURLOPT_HEADER, 1);
    											curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    											curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
    											curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    											$return = curl_exec($ch);
    											$return = explode(':', $return);
    
    											// for ($i=0; $i < count($return) ; $i++) {
    											//     echo $i. ':' . $return[$i];
    											// }
    											$stat = explode('"', $return[17]);
    											$msg1 = explode(',', $return[20]);
    											$msg = explode('"', $msg1[0]);
    											// print_r($msg[1]);
        											
    											if ($stat[1] != 'Failed.') {
    											    $saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $invoice_info_rs[3]) . "', '" . $invoice_info_rs[0] . "', 'Booking Notification', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $invoice_info_rs[2] ."', 'US2100002', '". date("Y-m-d H:i:s") ."')");
    												if ($saveSms) {
    													//$success_arr = array('message' => $msg[1]);
    													$successMsg = "Payment has been received successfully";
    													$data = json_encode(array('Status' => true, 'Message' => $successMsg));
    												} else {
    													$errorList[] = mysqli_error($conn);
    													$data = json_encode(array('Status' => false, 'Message' => $errorList));
    												}
    											} else {
    												$errorList[] = $msg[1];
    												$data = json_encode(array('Status' => false, 'Message' => $errorList));
    											}
    										} else {
    											$errorList[] = mysqli_error($conn);
    											$data = json_encode(array('Status' => false, 'Message' => $errorList));
    										}
										
    									} else {
    										$successMsg = $objName . " has been registered successfully";
    										$data = json_encode(array('Status' => true, 'Message' => $successMsg));
    									}
    									$data = json_encode(array('Status' => true, 'Message' => 'Payment has been received successfully'));
    
        							}
        						} else {
    								$errorList[] = mysqli_error($conn);
    								$data = json_encode(array('Status' => false, 'Message' => $errorList));
        						}
				                
				            }
                    
    				    } else if ($invoice_rs[3] = "Landlord") {
    				        
    				    } else if ($invoice_rs[3] = "prospectiveTenant") {
				        
				        }

				    }
				    $data = json_encode(array('Status' => true, 'Message' => $checked_invoices));

			    }
			}
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}

		echo $data;
	}

	// Tenant Statement Online (Tenant Portal)
	function tenant_statement_report_online($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $_SESSION['tenantIdd']);
		$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
		$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		if ($selected_start_date == " 00:00") {
			$generatedReportQuery = mysqli_query($conn, "CALL tenant_statement_online('". $selected_tenant_id ."', '0000-00-00', '0000-00-00')") or die("Error is this one kkkkk : ". mysqli_error($conn));
		} else {
			$generatedReportQuery = mysqli_query($conn, "CALL tenant_statement_online('". $selected_tenant_id ."', '". $selected_start_date ."', '". $selected_end_date ."')") or die(mysqli_error($conn));
		}
		if (mysqli_num_rows($generatedReportQuery) > 0) { ?>
			<div class="card">
				<div class="card-body">
					<div class="row mt-3" id="tenantStatementReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="../img/reportHeader.png" width="100%" height="180px" /><br />
									<h2 class="mt-2 mb-2 text-center" style="font-weight: 700">Tenant Statement Online</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
											$conn2 = mysqli_connect("localhost", "lighthq2_user", "Lighthouse9414", "lighthq2_lighthouse_db");
								// 			$conn2 = mysqli_connect("localhost", "root", "", "lighthq2_lighthouse_db");
											$selected_tenant_info = mysqli_query($conn2, "SELECT tenantID, tenantName, tenantMobile  FROM tenants WHERE tenantID = '" . $selected_tenant_id . "'") or mysqli_error($conn);
											$tenant_rs = mysqli_fetch_array($selected_tenant_info);
										?>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Tenant ID</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[0]; ?></h6>
										</div>
										<div class="col-md-3 pb-4">
											<h5 class="font-weight-bold">Tenant Name</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[1]; ?></h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Mobile Number</h5>
											<h6 class="font-weight-normal"><?php echo $tenant_rs[2]; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">From Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">To Date</h5>
											<h6 class="font-weight-normal"><?php echo "-"; ?></h6>
										</div>
									</div>	

									<div class="table-responsive">
										<table class="table table-bordered">
											<thead>
												<tr class="bg-primary text-white text-center">
													<th>Date</th>
													<th>Type</th>
													<th>Description</th>
													<th>Charge</th>
													<th>Receipt</th>
													<th>Balance</th>
												</tr>
											</thead>
											<tbody>

												<?php
													$counter = 1;
													$count_statement = mysqli_num_rows($generatedReportQuery);
													while ($result = mysqli_fetch_array($generatedReportQuery)) {
														if ($counter == 1) {?>
															<tr>
																<td colspan="5" style="text-align: right">Previous Balance &nbsp; </td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2)."</b>"; ?></td>													
															</tr> <?php
														} else if ($counter == $count_statement - 1) {?>
															<tr class="bg-light font-weight-bold">
																<td colspan="3" style="text-align: right"> Total</td>
																<td class="text-center" style="font-weight: 600"> <?php echo "$ ". number_format($result[5], 2); ?></td>
																<td class="text-center" style="font-weight: 600"> <?php echo "$ ". number_format($result[6], 2); ?></td>
																<td class="text-center" style="font-weight: 600"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														} else if ($counter == $count_statement) {?>
															<tr class="font-weight-normal">
																<td colspan="5" style="text-align: right">Current Balance &nbsp; </td>
																<td class="text-center"> <?php echo "<b>$ ". number_format($result[7], 2). "</b>"; ?></td>
															</tr> <?php
														} else { ?>
															<tr>
																<td class="text-center"> <?php echo substr($result[0], 0, 10); ?></td>
																<td class="text-center"> <?php echo $result[1]; ?></td>
																<td> <?php echo $result[2]; ?></td>
																<td class="text-center"><?php if ($result[5] != 0) { echo "$ ". number_format($result[5], 2); } ?></td>
																<td class="text-center"><?php if ($result[6] != 0) { echo "$ ". number_format($result[6], 2); } ?></td>
																<td class="text-center"> <?php echo "$ ". number_format($result[7], 2); ?></td>
															</tr> <?php
														}
														$counter++;
													}
												?>

											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;">Generated Statement<br /><span style="font-weight: normal;"> Online Statement</span></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Send Tenant Maintenance Request (Tenant Portal)
	function send_tenant_new_maintenance_request_tenant_portal($conn) {
	
		global $errorList;
		$data = array();
		extract($_POST);

		//Generate New ID for the current inserted row....
		$getMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM maintenance_requests") or die(mysqli_error($conn));
		if (mysqli_num_rows($getMaxID) > 0) {
			$maxID = mysqli_fetch_array($getMaxID);
			$curMaxID = $maxID[0] + 1;
			$generatedID = "RQ". "". sprintf("%04d", $curMaxID);
		} else {
			$curMaxID = 1;
			$generatedID = "RQ". "". sprintf("%04d", $curMaxID);
		}

		$maintenance_request_subject = mysqli_real_escape_string($conn, $maintenance_request_subject);
		$maintenance_request_body = mysqli_real_escape_string($conn, $maintenance_request_body);

		$uploadedPhotoNames = "";

		if (isset($_FILES['txtMaintenanceAttachmentPhotos'])) {
			// Maintenance Request Photos count, check then upload
			$count_maintenance_request_photos = count($_FILES['txtMaintenanceAttachmentPhotos']['name']);
			$photos_location = "../tenant/uploads/photos/";

			for($index = 0;$index < $count_maintenance_request_photos; $index++){
				if(isset($_FILES['txtMaintenanceAttachmentPhotos']['name'][$index]) && $_FILES['txtMaintenanceAttachmentPhotos']['name'][$index] != ''){
					$filename = $_FILES['txtMaintenanceAttachmentPhotos']['name'][$index];
					$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
					$valid_ext = array('jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG'); 
					if(in_array($ext, $valid_ext)){
						$new_photo_name = "CRQMT". ($index + 1) ."_" . date("YmdHis") . "." . $ext;
						if(move_uploaded_file($_FILES['txtMaintenanceAttachmentPhotos']['tmp_name'][$index], $photos_location.$new_photo_name)){
							$uploadedPhotoNames .= substr($photos_location.$new_photo_name, 3). "###";
						}
					} else {
						$errorMsg = "Upload only the allowed photo types";
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}
			}
		} else {
			$uploadedPhotoNames = "NoPhoto###";
		}

		//echo rtrim($uploadedPhotoNames, "###");
		
		$registerCustomerMaintenanceRequest = mysqli_query($conn, "INSERT INTO maintenance_requests VALUES (NULL, '". $generatedID ."', '". $_SESSION['tenantIdd'] ."', 'NotAssigned', 'Unknown', '". $maintenance_request_subject ."', 1, 'NotRated', 'NoComment', '". date("Y-m-d H:i:s") ."')"); 
		if ($registerCustomerMaintenanceRequest) { 
			$registerRequestMessage = mysqli_query($conn, "INSERT INTO request_messages VALUES (NULL, '". $generatedID ."', '". $maintenance_request_body ."', '". rtrim($uploadedPhotoNames, "###") ."', 0, '". $_SESSION['tenantIdd'] ."', '". date("Y-m-d H:i:s") ."')");
			if($registerRequestMessage) {
				$data = json_encode(array('Status' => true, 'Message' => 'Maintenance request has been sent successfully'));
			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		} else { 
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} 
		
		echo $data;

	}

	// Fetch Tenant Maintenance Request (Tenant Portal)
	function fetch_tenant_portal_maintenance_request_chat_box_tenant_portal($conn) {

		extract($_POST);
		$request_tracking_number = mysqli_real_escape_string($conn, $request_tracking_number);
		$_SESSION['maintenanceRequestTrackingIdd'] = $request_tracking_number;
		$reportQuery = mysqli_query($conn, "SELECT * FROM request_messages WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' ORDER BY messageDate ASC");
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				while($report_rs = mysqli_fetch_array($reportQuery)) {
					if ($report_rs[5] == $_SESSION['tenantIdd']) {
					    
					    // Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: right;">
									<div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
										<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
									    </span>
									</div>
								</div>
							</div><?php
						} else {
    					    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: right;">
    				                    <div class="bg-success text-white" style="display: inline-block; max-width: 70%; padding: 7px 10px 0px 10px; border-radius: 15px 0px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
                                            <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
						        ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
						                <div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
						                    <?php echo nl2br($report_rs[2]); ?>
                                            <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>
								        </div>
								    </div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
								        <div class="bg-success text-white" style="max-width: 70%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
                                            <script src="../tenant/assets/js/venobox.js"></script>
											<script>
												$(document).ready(function () {
													$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
												})
											</script>
											<?php
												$message_photos = explode("###", $report_rs[3]);
												foreach($message_photos as $photo) {
													?><div class="p-1">
														<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
													</div><?php
												}
											?>
                                            <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;">
    										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.80rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
    									    </span>
								        </div>
								    </div>
								</div><?php
							} 
				        }
						
					} else {
					    
					    // Messages from the Admin Buddy

						$getRespondingEmployeeInfo = mysqli_query($conn, "SELECT employees.employeePhoto, employees.employeeName, employee_positions.positionName, system_users.loginStatus
						FROM system_users
						JOIN employees ON system_users.employeeID = employees.employeeID
						JOIN employee_positions ON employees.employeePosition = employee_positions.positionID
						WHERE system_users.userID = '". mysqli_real_escape_string($conn, $report_rs[5]) ."'") or die(mysqli_error($conn));
						if (mysqli_num_rows($getRespondingEmployeeInfo) > 0) {
							$responding_emp_rs = mysqli_fetch_array($getRespondingEmployeeInfo);
						}
						
						// Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: left;">
									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
									</div>
								</div>
							</div><?php
						} else {
						    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
                                ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
    								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    										<?php echo nl2br($report_rs[2]); ?>
    									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    									</div>
    								</div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.62rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
								</div><?php
						    }
						}

					}
				}
				mysqli_query($conn, "UPDATE request_messages SET messageStatus = '1' WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' AND messageSender <> '". $_SESSION['tenantIdd'] ."'") or die(mysqli_error($conn));
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

    // Fetch Live Tenant Maintenance Request (Tenant Portal)
	function fetch_live_tenant_portal_maintenance_request_chat_box_tenant_portal($conn) {

		extract($_POST);
		$reportQuery = mysqli_query($conn, "SELECT * FROM request_messages WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' ORDER BY messageDate ASC");
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				while($report_rs = mysqli_fetch_array($reportQuery)) {
					if ($report_rs[5] == $_SESSION['tenantIdd']) {
					    
					    // Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: right;">
									<div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
										<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.60rem; text-align: right;">
										    <?php echo time_formatter($report_rs[6]); ?> <i style="font-size: 0.70rem; font-weight: bold;" class="bi bi-check2-all <?php if ($report_rs[4] == 1) { echo "text-info"; } else if ($report_rs[4] == 0) { echo "text-warning"; } ?>"></i>
									    </span>
									</div>
								</div>
							</div><?php
						} else {
    					    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: right;">
    				                    <div class="bg-success text-white" style="display: inline-block; max-width: 70%; padding: 7px 10px 0px 10px; border-radius: 15px 0px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
    										<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?> <i class="bi bi-check2-all fa-lg text-info"></i></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
						        ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
						                <div class="bg-success text-white" style="max-width: 80%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
						                    <?php echo nl2br($report_rs[2]); ?>
						                    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?> <i class="bi bi-check2-all fa-lg text-info"></i></span>
								        </div>
								    </div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: right;">
								        <div class="bg-success text-white" style="max-width: 70%; display: inline-block; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 15px 0px 15px 15px;">
                                            <script src="../tenant/assets/js/venobox.js"></script>
											<script>
												$(document).ready(function () {
													$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
												})
											</script>
											<?php
												$message_photos = explode("###", $report_rs[3]);
												foreach($message_photos as $photo) {
													?><div class="p-1">
														<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
													</div><?php
												}
											?>
											<span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?> <i class="bi bi-check2-all fa-lg text-info"></i></span>
								        </div>
								    </div>
								</div><?php
							} 
				        }
						
					} else {
					    
					    // Messages from the Admin Buddy

						$getRespondingEmployeeInfo = mysqli_query($conn, "SELECT employees.employeePhoto, employees.employeeName, employee_positions.positionName, system_users.loginStatus
						FROM system_users
						JOIN employees ON system_users.employeeID = employees.employeeID
						JOIN employee_positions ON employees.employeePosition = employee_positions.positionID
						WHERE system_users.userID = '". mysqli_real_escape_string($conn, $report_rs[5]) ."'") or die(mysqli_error($conn));
						if (mysqli_num_rows($getRespondingEmployeeInfo) > 0) {
							$responding_emp_rs = mysqli_fetch_array($getRespondingEmployeeInfo);
						}
						
						// Messages from the Tenant Buddy
						if ($report_rs[3] == "NoPhoto") { ?>
							<div class="row mt-2">
								<div class="col-md-12" style="text-align: left;">
									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
										<?php echo nl2br($report_rs[2]); ?>
									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
									</div>
								</div>
							</div><?php
						} else {
						    if ($report_rs[2] == "-" || $report_rs[2] == "") {
    					        ?><div class="row mt-2">
    				                <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
    						    </div><?php
						    } else {
                                ?><div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    									<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
    								    <div class="align-top bg-info text-white" style="max-width: 80%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    										<?php echo nl2br($report_rs[2]); ?>
    									    <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    									</div>
    								</div>
							    </div>
							    <div class="row mt-2">
				                    <div class="col-md-12" style="text-align: left;">
    				                	<img src="<?php echo "../". $responding_emp_rs[0]; ?>" class="align-top rounded-circle" style="float: left;" width="38px" height="38px"><i class="fa fa-circle fa-sm <?php if ($responding_emp_rs[3] == 0) { echo "text-dark"; } else if ($responding_emp_rs[3] == 1) { echo "text-success"; } ?>" style="margin: 25px 0px 0px -15px"></i>
								        <div class="align-top bg-info text-white" style="max-width: 70%; vertical-align: top; display: inline-block; margin-left: 5px; padding: 7px 10px 0px 10px; font-size: 0.75rem; text-align: left; border-radius: 0px 15px 15px 15px;">
    							            <script src="../tenant/assets/js/venobox.js"></script>
    										<script>
    											$(document).ready(function () {
    												$('.<?php echo "venobox".$report_rs[1]; ?>').venobox()
    											})
    										</script>
                                            <?php
    											$message_photos = explode("###", $report_rs[3]);
    											foreach($message_photos as $photo) {
    												?><div class="p-1">
    													<a class="<?php echo "venobox".$report_rs[1]; ?>" data-gall="<?php echo "myGallery".$report_rs[1]; ?>" href="<?php echo "../".$photo; ?>"><img class="img-fluid rounded" src="<?php echo "../".$photo; ?>" width="100%"/></a>
    												</div><?php
    											}
    										?>
									        <span class="text-white" style="display: block; padding-bottom: 5px; font-size: 0.55rem; text-align: right;"><?php echo time_formatter($report_rs[6]); ?></span>
    							        </div>
    							    </div>
								</div><?php
						    }
						}

					}
				}
				mysqli_query($conn, "UPDATE request_messages SET messageStatus = '1' WHERE trackingNumber = '". $_SESSION['maintenanceRequestTrackingIdd'] ."' AND messageSender <> '". $_SESSION['tenantIdd'] ."'") or die(mysqli_error($conn));
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Send Live Tenant Maintenance Request Live Message (Tenant Portal)
	function send_tenant_maintenance_request_live_message_tenant_portal($conn) {

		global $errorList;
		$data = array();
		extract($_POST);

		$maintenance_request_body = mysqli_real_escape_string($conn, $maintenance_request_body);

		$uploadedPhotoNames = "";

		if (!isset($_FILES['txtLiveMaintenanceAttachmentPhotosTenantPortal'])) {
			$uploadedPhotoNames = "NoPhoto###";
		} else {
			// Maintenance Request Photos count, check then upload
			$count_maintenance_request_photos = count($_FILES['txtLiveMaintenanceAttachmentPhotosTenantPortal']['name']);
			$photos_location = "../tenant/uploads/photos/";

			for($index = 0;$index < $count_maintenance_request_photos; $index++){
				if(isset($_FILES['txtLiveMaintenanceAttachmentPhotosTenantPortal']['name'][$index]) && $_FILES['txtLiveMaintenanceAttachmentPhotosTenantPortal']['name'][$index] != ''){
					$filename = $_FILES['txtLiveMaintenanceAttachmentPhotosTenantPortal']['name'][$index];
					$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
					$valid_ext = array('jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG'); 
					if(in_array($ext, $valid_ext)){
						$new_photo_name = "CRQMT". ($index + 1) ."_" . date("YmdHis") . "." . $ext;
						if(move_uploaded_file($_FILES['txtLiveMaintenanceAttachmentPhotosTenantPortal']['tmp_name'][$index], $photos_location.$new_photo_name)){
							$uploadedPhotoNames .= substr($photos_location.$new_photo_name, 3). "###";
						}
					} else {
						$errorMsg = "Upload only the allowed photo types";
						$errorList[] = $errorMsg;
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					}
				}
			}
		}

		//echo rtrim($uploadedPhotoNames, "###");

		$registerRequestMessage = mysqli_query($conn, "INSERT INTO request_messages VALUES (NULL, '". $_SESSION['maintenanceRequestTrackingIdd'] ."', '". $maintenance_request_body ."', '". rtrim($uploadedPhotoNames, "###") ."', 0, '". $_SESSION['tenantIdd'] ."', '". date("Y-m-d H:i:s") ."')");
		if($registerRequestMessage) {
			$data = json_encode(array('Status' => true, 'Message' => 'Message has been sent'));
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}

		echo $data;

	}

	// Search Tenant Short Messages (SMS) (Tenant Portal)
	function search_tenant_short_messages_sms($conn) {
		extract($_POST);
		$selected_message_subject = mysqli_real_escape_string($conn, $selected_message_subject);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
			// $selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}

		$generatedReportQuery = "SELECT bulk_sms.smsID, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, bulk_sms.sentDate
		FROM bulk_sms WHERE bulk_sms.receiverID = '". $_SESSION['tenantIdd'] ."' ";
		if ($selected_message_subject != "") { 
			$generatedReportQuery .= "AND bulk_sms.messageSubject = '". $selected_message_subject ."' "; 
		}

		if ($selected_date_type != 0) {
			if ($selected_message_subject != "") {
				$generatedReportQuery .= "AND bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "AND bulk_sms.sentDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY bulk_sms.smsID DESC";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="col-lg-12">
				<div class="card">
					<div class="card-body">
						<div class="row mt-3 mb-3">
							<?php
								if ($selected_date_type == 0) {
									$date_type_label = "All Date";
									$tenant_sms_start_date = "-";
									$tenant_sms_end_date = "-";
								} else if ($selected_date_type == 1) {
									$date_type_label = "Today";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 2) {
									$date_type_label = "Yesterday";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 3) {
									$date_type_label = "Last 3 Days";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 4) {
									$date_type_label = "This Week";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 5) {
									$date_type_label = "Last 10 Days";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 6) {
									$date_type_label = "This Month";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 7) {
									$date_type_label = "This Year";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								} else if ($selected_date_type == 8) {
									$date_type_label = "Customized Date";
									$tenant_sms_start_date = $selected_start_date;
									$tenant_sms_end_date = $selected_end_date;
								}
							?>
							<div class="col-md-5 pb-2">
								<h6 class="font-weight-bold">Message Subject</h6>
								<p><?php if ($selected_message_subject === "") { echo "-"; } else { echo $selected_message_subject; } ?></p>
							</div>
							<div class="col-md-3 pb-2">
								<h6 class="font-weight-bold">Date Type</h6>
								<p><?php echo $date_type_label; ?></p>
							</div>
							<div class="col-md-2 pb-2">
								<h6 class="font-weight-bold">Start Date</h6>
								<p><?php echo substr($tenant_sms_start_date, 0, 10); ?></p>
							</div>
							<div class="col-md-2 pb-2">
								<h6 class="font-weight-bold">End Date</h6>
								<p><?php echo substr($tenant_sms_end_date, 0, 10); ?></p>
							</div>							
						</div>
						<div class="table-responsive mt-3">
							<table class="table table-stripe" id="tenantShortMessagesTable">
								<thead>
									<tr class="text-white bg-info">
										<th class="text-center">SMS ID</th>
										<th class="text-left">Subject</th>
										<th class="text-left">Body</th>
										<th class="text-center">Status</th>
										<th class="text-center">Sent Date</th>
									</tr>
								</thead>
								<tbody>
									<?php
										$x = 1;
										while ($request_rs = mysqli_fetch_array($reportQuery)) { ?>
											<tr>
												<td class="text-center" width="8%"><?php echo $request_rs[0]; ?></td>
												<td class="text-left" width="20%"><?php echo $request_rs[1]; ?></td>
												<td class="text-justify"><a href="#" class="btnOpenTenantShortMessageContentDetailsModalTenantPortal" data-id="<?php echo $request_rs[0]; ?>" data-bs-toggle="modal" data-bs-target="#tenantShortMessageContentDetailsModal"><?php echo substr($request_rs[2], 0, 100). " ..."; ?></a></td>
												<td class="text-center" width="7%">
													<?php if ($request_rs[3] == 1) { ?><span class="badge text-success p-2"><i class="bi bi-check2-all"></i> Sent</span><?php } ?>
												</td>
												<td class="text-center" width="15%"><?php echo substr($request_rs[4], 0, 16); ?></td>
											</tr><?php
											$x++;
										}
									?>
								</tbody>
							</table>
						</div>

					</div>
				</div>

			</div><?php
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Short Messages (SMS) Not Found</h6>
						</div>
					</div>
				</div>
			</div><?php
		}
	}

	// Read Full Tenant Short Messages (SMS) (Tenant Portal)
	function fetch_tenant_short_message_content_details_tenant_portal($conn) {

		extract($_POST);
		$short_message_id = mysqli_real_escape_string($conn, $short_message_id);
		$generatedReportQuery = "SELECT bulk_sms.smsID, tenants.tenantName, bulk_sms.telephoneSentTo, bulk_sms.messageSubject, bulk_sms.messageBody, bulk_sms.messageStatus, system_users.Username, employees.employeeName, bulk_sms.sentDate
		FROM bulk_sms
		JOIN tenants ON bulk_sms.receiverID = tenants.tenantID
		JOIN system_users ON bulk_sms.senderUser = system_users.userID
		JOIN employees ON system_users.employeeID = employees.employeeID
		WHERE bulk_sms.smsID = '". $short_message_id ."'";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if ($reportQuery) {
			if (mysqli_num_rows($reportQuery) > 0) {
				$report_rs = mysqli_fetch_array($reportQuery);
				?>
					<div class="row m-2" style="margin: 0xp;">
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-key"></i> Message ID</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[0]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Receiver Name</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[1]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-phone"></i> Mobile No</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo "+252 ". $report_rs[2]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-book"></i> Message Subject</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[3]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-envelope-open"></i> Message Body</strong></h6></div>
						<div class="col-md-8 pt-2" style="text-align: justify;"><?php echo $report_rs[4]; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-info-circle"></i> Message Status</strong></h6></div>
						<div class="col-md-8 pt-2 text-success" style="text-align: justify;"><?php if ($report_rs[5] == 1) { echo "<i class='bi bi-check2-all'></i> Sent"; } ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-user"></i> Sender User</strong></h6></div>
						<div class="col-md-8 pt-2"><?php echo $report_rs[6]. " (<strong>". $report_rs[7]. "</strong>)"; ?></div>
						<div class="col-md-3 pt-2 text-primary"><strong><h6><i class="fa fa-calendar"></i> Sent Date</strong></h6></div>
						<div class="col-md-8 p-2"><?php echo substr($report_rs[8], 0, 16); ?></div>
					</div>
				<?php
			} else {

			}
		} else {
			?><div class="card">
				<div class="card-body">
					<br />
					<div class="row p-3">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Update Tenant Profile
	function update_tenant_profile_tenant_portal($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$updateMainMenu = mysqli_query($conn, "UPDATE tenant_profile SET employerName = '". mysqli_real_escape_string($conn, $tenant_work_place) ."', titlePosition = '". mysqli_real_escape_string($conn, $tenant_position_title) ."', twitterProfile = '". mysqli_real_escape_string($conn, $tenant_twitter_user) ."', facebookProfile = '". mysqli_real_escape_string($conn, $tenant_facebook_user) ."', instagramProfile = '". mysqli_real_escape_string($conn, $tenant_instagram_user) ."' WHERE tenantID = '". mysqli_real_escape_string($conn, $_SESSION['tenantIdd']) ."'");
		if ($updateMainMenu) {
			$data = json_encode(array('Status' => true, 'Message' => 'Your profile has been updated successfully'));
		} else {
			$errorMsg = mysqli_error($conn);
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		echo $data;
	}

	// Change Passcode (Tenant Portal)
	function change_tenant_passcode_tenant_poretal($conn) {
		global $ereyFure;
		global $errorList;

		$data = array();
		extract($_POST);

		$tenant_current_passcode = mysqli_real_escape_string($conn, $tenant_current_passcode);
		$tenant_new_passcode = mysqli_real_escape_string($conn, $tenant_new_passcode);
		$tenant_confirm_passcode = mysqli_real_escape_string($conn, $tenant_new_passcode);

		if ($tenant_new_passcode != $tenant_confirm_passcode) {
			$errorMsg = "Sorry!! Passwords are not matching, please check it...";
			$errorList[] = $errorMsg;
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			$getUsernamePassword = mysqli_query($conn, "SELECT * FROM tenants WHERE tenantID = '" . $_SESSION['tenantIdd'] . "' AND tenantPasscode = '". $tenant_current_passcode ."'");
			if ($getUsernamePassword) {
				if (mysqli_num_rows($getUsernamePassword) > 0) {
					$changePass = mysqli_query($conn, "UPDATE tenants SET tenantPasscode = '" . mysqli_real_escape_string($conn, $tenant_new_passcode) . "' WHERE tenantID = '" . $_SESSION['tenantIdd'] . "'");
					if ($changePass) {
						$data = json_encode(array('Status' => true, 'Message' => 'Your passcode has been changed successfully'));
					} else {
						$errorMsg = mysqli_error($conn);
						$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
					}
				} else {
					$errorMsg = "Current passcode is wrong, please check again";
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}

			} else {
				$errorMsg = mysqli_error($conn);
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		}

		echo $data;
	}

	// ================ END OF TENANT PORTAL MODULE ==============================================

	// ================ START OF WEBSITE PORTAL MODULE ===========================================

	//Search for the availbale rental properties website online
	function search_available_rental_properties_onilne_website($conn) {
		extract($_POST);
		$selected_property_type = mysqli_real_escape_string($conn, $selected_property_type);
		$selected_property_location = mysqli_real_escape_string($conn, $selected_property_location);
		$selected_property_price_range = mysqli_real_escape_string($conn, $selected_property_price_range);
		$selected_bedrooms = mysqli_real_escape_string($conn, $selected_bedrooms);

		$generatedReportQuery = "SELECT rental_properties.rentalPropertyID, rental_properties.propertyPhotos, buildings.buildingID, buildings.buildingName, rental_properties.propertyName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, property_types.propertyTypeDescription, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_properties.rentalPrice, rental_properties.depositAmount, rental_property_statuses.propertyStatusDescription, rental_property_statuses.propertyStatusID 
		FROM rental_properties 
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID 
		JOIN property_locations ON buildings.locationID = property_locations.locationID 
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID 
		JOIN floors ON rental_properties.floorID = floors.floorID 
		JOIN rental_property_statuses ON rental_properties.propertyStatus = rental_property_statuses.propertyStatusID
		WHERE ";
		if ($selected_property_type != "") { $generatedReportQuery .= "rental_properties.propertyType = '". $selected_property_type ."' AND "; } 
		if ($selected_property_location != "") {
			if ($selected_property_type != "")
				$generatedReportQuery .= "buildings.locationID = '". $selected_property_location ."' AND ";
			else
				$generatedReportQuery .= "buildings.locationID = '". $selected_property_location ."' AND ";

		}
		if ($selected_property_price_range != "") {
			if ($selected_property_type != "" || $selected_property_location != "")
				$generatedReportQuery .= "rental_properties.rentalPrice <= '". $selected_property_price_range ."' AND ";
			else
				$generatedReportQuery .= "rental_properties.rentalPrice <= '". $selected_property_price_range ."' AND ";
		}
		if ($selected_bedrooms != "") {
			if ($selected_property_type != "" || $selected_property_location != "" || $selected_property_price_range != "")
				$generatedReportQuery .= "rental_properties.noOfBedrooms = '". $selected_bedrooms ."' AND ";
			else
				$generatedReportQuery .= "rental_properties.noOfBedrooms = '". $selected_bedrooms ."' AND ";
		}
		$generatedReportQuery .= "rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM booked_properties WHERE bookingStatus = 1) AND rental_properties.propertyStatus = '1'
		ORDER BY rental_properties.rentalPropertyID";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		?>
		<div class="container-fluid wow fadeInUp" data-wow-delay="0.3s" style="padding: 35px; background-color: wheat;">
			<div class="container-fluid">
				<div class="row g-4"><?php
					if ($reportQuery) {
						if (mysqli_num_rows($reportQuery) > 0) {
							$count = 0;
							while ($rental_property_rs = mysqli_fetch_array($reportQuery)) { ?>
								<div class="col-lg-3 col-md-4">
									<div class="property-item bg-white rounded overflow-hidden">
										<div class="position-relative overflow-hidden">
											<?php $property_photos = explode("###", $rental_property_rs[1]); ?>
											<a href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><img class="img-fluid" src="<?php echo "admin_panel/". $property_photos[0]; ?>" alt=""></a>
											<div class="bg-primary rounded text-white position-absolute start-0 top-0 m-4 py-1 px-3">For Rent</div>
											<div class="bg-danger rounded-top text-white position-absolute start-0 bottom-0 mx-4 pt-1 px-3"><?php echo $rental_property_rs[8]?></div>
										</div>
										<div class="p-4 pb-0">
											<h5 class="text-primary mb-3"><?php echo "$ ". number_format($rental_property_rs[12], 2)?></h5>
											<a class="d-block h5 mb-2" href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><?php echo $rental_property_rs[4]. ", ". $rental_property_rs[3]; ?></a>
											<p><i class="fa fa-map-marker-alt text-primary me-2"></i><?php echo $rental_property_rs[5]. ", ". $rental_property_rs[6] . " - ". $rental_property_rs[7]; ?></p>
										</div>
										<div class="d-flex border-top">
											<small class="flex-fill text-center border-end py-2"><i class="fa fa-dollar text-primary me-2"></i><?php echo number_format($rental_property_rs[13], 2). " Deposit"; ?></small>
											<small class="flex-fill text-center border-end py-2"><i class="fa fa-bed text-primary me-2"></i><?php echo $rental_property_rs[10]. " Bedrooms"; ?></small>
											<small class="flex-fill text-center py-2"><i class="fa fa-bath text-primary me-2"></i><?php echo $rental_property_rs[11]. " Bathrooms"; ?></small>
										</div>
									</div>
								</div><?php
								$count += 1;
							}
							if ($count == 1) { ?>
								<div class="row mt-3">
									<div class="col-md-12">
										<hr class="bg-primary">
										<h5 style="text-align: right;" class="text-primary">Only <b>one</b> rental property is available</h5>
									</div>
								</div><?php
							} else if ($count >= 2) { ?>
								<div class="row mt-3">
									<div class="col-md-12 pull-right">
										<hr class="bg-primary">
										<h5 style="text-align: right;" class="text-primary">A total of <b><?php echo $count; ?></b> rental properties are available</h5>
									</div>
								</div><?php
							}
						} else {
							echo "<h5 class='text-center'>Rental Properties Not Found</h5>";
						}
					} else {
						echo "<h5 class='text-center'>". mysqli_error($conn). "</h5>";
					} ?>
				</div>
			</div>
        </div><?php
			
	}

	//Sort rental properties by post date website online
	function sort_rental_properties_by_post_date_onilne_website($conn) {
		extract($_POST);
		$selected_sort_type = mysqli_real_escape_string($conn, $selected_sort_type);

		$generatedReportQuery = "SELECT rental_properties.rentalPropertyID, rental_properties.propertyPhotos, buildings.buildingID, buildings.buildingName, rental_properties.propertyName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, property_types.propertyTypeDescription, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_properties.rentalPrice, rental_properties.depositAmount, rental_property_statuses.propertyStatusDescription, rental_property_statuses.propertyStatusID, rental_properties.registerDate 
		FROM rental_properties 
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID 
		JOIN property_locations ON buildings.locationID = property_locations.locationID 
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID 
		JOIN floors ON rental_properties.floorID = floors.floorID 
		JOIN rental_property_statuses ON rental_properties.propertyStatus = rental_property_statuses.propertyStatusID 
		WHERE rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM booked_properties WHERE bookingStatus = 1) AND rental_properties.propertyStatus = '1' 
		ORDER BY rental_properties.registerDate ". $selected_sort_type;
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		?><div class="row g-4"><?php
			if ($reportQuery) {
				if (mysqli_num_rows($reportQuery) > 0) {
					while ($rental_property_rs = mysqli_fetch_array($reportQuery)) { ?>
						<div class="col-lg-4 col-md-6">
							<div class="property-item bg-white rounded overflow-hidden">
								<div class="position-relative overflow-hidden">
									<?php $property_photos = explode("###", $rental_property_rs[1]); ?>
									<a href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><img class="img-fluid" src="<?php echo "admin_panel/". $property_photos[0]; ?>" alt=""></a>
									<div class="bg-primary rounded text-white position-absolute start-0 top-0 m-4 py-1 px-3">For Rent</div>
									<div class="bg-danger rounded-top text-white position-absolute start-0 bottom-0 mx-4 pt-1 px-3"><?php echo $rental_property_rs[8]?></div>
								</div>
								<div class="p-4 pb-0">
									<h5 class="text-primary mb-3"><?php echo "$ ". number_format($rental_property_rs[12], 2)?></h5>
									<a class="d-block h5 mb-2" href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><?php echo $rental_property_rs[4]. ", ". $rental_property_rs[3]; ?></a>
									<p><i class="fa fa-map-marker-alt text-primary me-2"></i><?php echo $rental_property_rs[5]. ", ". $rental_property_rs[6] . " - ". $rental_property_rs[7]; ?></p>
									<p class="bg-light p-2 rounded"><i class="fa fa-calendar text-primary me-2"></i> Posted <strong><?php echo time_formatter($rental_property_rs[16]); ?></strong></p>
								</div>
								<div class="d-flex border-top">
									<small class="flex-fill text-center border-end py-2"><i class="fa fa-dollar text-primary me-2"></i><?php if ($rental_property_rs[13] == 0) { echo "No Deposit"; } else if ($rental_property_rs[13] > 0) { echo number_format($rental_property_rs[13], 2). " Deposit"; } ?></small>
									<small class="flex-fill text-center border-end py-2"><i class="fa fa-bed text-primary me-2"></i><?php echo $rental_property_rs[10]. " Bedrooms"; ?></small>
									<small class="flex-fill text-center py-2"><i class="fa fa-bath text-primary me-2"></i><?php echo $rental_property_rs[11]. " Bathrooms"; ?></small>
								</div>
							</div>
						</div><?php
					}
				} else {
					echo "<h5 class='text-center'>Rental Properties Not Found</h5>";
				}
			} else {
				echo "<h5 class='text-center'>". mysqli_error($conn). "</h5>";
			}
		?></div><?php
			
	}

	//Sort rental properties by property type website online
	function sort_rental_properties_by_property_type_onilne_website($conn) {
		extract($_POST);
		$selected_sort_type = mysqli_real_escape_string($conn, $selected_sort_type);

		$getPropertyTypes = "SELECT rental_properties.propertyType, property_types.propertyTypeDescription FROM rental_properties
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID
		WHERE rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM booked_properties WHERE bookingStatus = 1) AND rental_properties.propertyStatus = 1
		GROUP BY property_types.propertyTypeDescription
		ORDER BY property_types.propertyTypeDescription ". $selected_sort_type;
		// echo $getPropertyTypes;
		$getPropertyTypesQuery = mysqli_query($conn, $getPropertyTypes) or die(mysqli_error($conn));
		?><div class="row g-4"><?php
			if ($getPropertyTypes) {
				if (mysqli_num_rows($getPropertyTypesQuery) > 0) {
					while ($rental_property_rs = mysqli_fetch_array($getPropertyTypesQuery)) {
						$generatedReportQuery = "SELECT rental_properties.rentalPropertyID, rental_properties.propertyPhotos, buildings.buildingID, buildings.buildingName, rental_properties.propertyName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, property_types.propertyTypeDescription, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_properties.rentalPrice, rental_properties.depositAmount, rental_property_statuses.propertyStatusDescription, rental_property_statuses.propertyStatusID, rental_properties.registerDate 
						FROM rental_properties 
						JOIN buildings ON rental_properties.buildingID = buildings.buildingID 
						JOIN property_locations ON buildings.locationID = property_locations.locationID 
						JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID 
						JOIN floors ON rental_properties.floorID = floors.floorID 
						JOIN rental_property_statuses ON rental_properties.propertyStatus = rental_property_statuses.propertyStatusID 
						WHERE rental_properties.propertyType = '". $rental_property_rs[0] ."' AND rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM booked_properties WHERE bookingStatus = 1) AND rental_properties.propertyStatus = '1' 
						ORDER BY rental_properties.rentalPrice DESC";
						// echo $generatedReportQuery;
						$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
						?><div class="row g-4">
							<div class="col-md-12">
								<h4 class="bg-primary text-light rounded p-3"><i class="fa fa-building"></i> <?php echo $rental_property_rs[1]; ?></h4>
							</div><?php
							if ($reportQuery) {
								if (mysqli_num_rows($reportQuery) > 0) {
									while ($rental_property_rs = mysqli_fetch_array($reportQuery)) { ?>
										<div class="col-lg-4 col-md-6">
											<div class="property-item bg-white rounded overflow-hidden">
												<div class="position-relative overflow-hidden">
													<?php $property_photos = explode("###", $rental_property_rs[1]); ?>
													<a href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><img class="img-fluid" src="<?php echo "admin_panel/". $property_photos[0]; ?>" alt=""></a>
													<div class="bg-primary rounded text-white position-absolute start-0 top-0 m-4 py-1 px-3">For Rent</div>
													<div class="bg-danger rounded-top text-white position-absolute start-0 bottom-0 mx-4 pt-1 px-3"><?php echo $rental_property_rs[8]?></div>
												</div>
												<div class="p-4 pb-0">
													<h5 class="text-primary mb-3"><?php echo "$ ". number_format($rental_property_rs[12], 2)?></h5>
													<a class="d-block h5 mb-2" href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><?php echo $rental_property_rs[4]. ", ". $rental_property_rs[3]; ?></a>
													<p><i class="fa fa-map-marker-alt text-primary me-2"></i><?php echo $rental_property_rs[5]. ", ". $rental_property_rs[6] . " - ". $rental_property_rs[7]; ?></p>
													<p><i class="fa fa-calendar text-primary me-2"></i> Posted <strong><?php echo time_formatter($rental_property_rs[16]); ?></strong></p>
												</div>
												<div class="d-flex border-top">
													<small class="flex-fill text-center border-end py-2"><i class="fa fa-dollar text-primary me-2"></i><?php if ($rental_property_rs[13] == 0) { echo "No Deposit"; } else if ($rental_property_rs[13] > 0) { echo number_format($rental_property_rs[13], 2). " Deposit"; } ?></small>
													<small class="flex-fill text-center border-end py-2"><i class="fa fa-bed text-primary me-2"></i><?php echo $rental_property_rs[10]. " Bedrooms"; ?></small>
													<small class="flex-fill text-center py-2"><i class="fa fa-bath text-primary me-2"></i><?php echo $rental_property_rs[11]. " Bathrooms"; ?></small>
												</div>
											</div>
										</div><?php
									}
								} else {
									echo "<h5 class='text-center'>Rental Properties Not Found</h5>";
								}
							} else {
								echo "<h5 class='text-center'>". mysqli_error($conn). "</h5>";
							}
						?></div><?php
					}
				} else {
					echo "<h5 class='text-center'>Rental Properties Not Found</h5>";
				}
			} else {
				echo "<h5 class='text-center'>". mysqli_error($conn). "</h5>";
			}
		?></div><?php
			
	}

	//Sort rental properties by property location website online
	function sort_rental_properties_by_property_location_onilne_website($conn) {
		extract($_POST);
		$selected_sort_type = mysqli_real_escape_string($conn, $selected_sort_type);

		$getPropertyLocaiton = "SELECT buildings.locationID, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity
		FROM rental_properties
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_locations ON buildings.locationID = property_locations.locationID
		WHERE rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM booked_properties WHERE bookingStatus = 1) AND rental_properties.propertyStatus = 1
		GROUP BY property_locations.locationID
		ORDER BY property_locations.locationCity ". $selected_sort_type;
		// echo $getPropertyLocaiton;
		$getPropertyLocaitonQuery = mysqli_query($conn, $getPropertyLocaiton) or die(mysqli_error($conn));
		?><div class="row g-4"><?php
			if ($getPropertyLocaiton) {
				if (mysqli_num_rows($getPropertyLocaitonQuery) > 0) {
					while ($rental_property_rs = mysqli_fetch_array($getPropertyLocaitonQuery)) {
						$generatedReportQuery = "SELECT rental_properties.rentalPropertyID, rental_properties.propertyPhotos, buildings.buildingID, buildings.buildingName, rental_properties.propertyName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, property_types.propertyTypeDescription, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_properties.rentalPrice, rental_properties.depositAmount, rental_property_statuses.propertyStatusDescription, rental_property_statuses.propertyStatusID, rental_properties.registerDate 
						FROM rental_properties 
						JOIN buildings ON rental_properties.buildingID = buildings.buildingID 
						JOIN property_locations ON buildings.locationID = property_locations.locationID 
						JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID 
						JOIN floors ON rental_properties.floorID = floors.floorID 
						JOIN rental_property_statuses ON rental_properties.propertyStatus = rental_property_statuses.propertyStatusID 
						WHERE buildings.locationID = '". $rental_property_rs[0] ."' AND rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM booked_properties WHERE bookingStatus = 1) AND rental_properties.propertyStatus = '1' 
						ORDER BY property_locations.locationCity ASC";
						// echo $generatedReportQuery;
						$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
						?><div class="row g-4">
							<div class="col-md-12">
								<h4 class="bg-primary text-light rounded p-3"><i class="fa fa-map-marker"></i> <?php echo $rental_property_rs[1] .", ". $rental_property_rs[2] ."-". $rental_property_rs[3]; ?></h4>
							</div><?php
							if ($reportQuery) {
								if (mysqli_num_rows($reportQuery) > 0) {
									while ($rental_property_rs = mysqli_fetch_array($reportQuery)) { ?>
										<div class="col-lg-4 col-md-6">
											<div class="property-item bg-white rounded overflow-hidden">
												<div class="position-relative overflow-hidden">
													<?php $property_photos = explode("###", $rental_property_rs[1]); ?>
													<a href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><img class="img-fluid" src="<?php echo "admin_panel/". $property_photos[0]; ?>" alt=""></a>
													<div class="bg-primary rounded text-white position-absolute start-0 top-0 m-4 py-1 px-3">For Rent</div>
													<div class="bg-danger rounded-top text-white position-absolute start-0 bottom-0 mx-4 pt-1 px-3"><?php echo $rental_property_rs[8]?></div>
												</div>
												<div class="p-4 pb-0">
													<h5 class="text-primary mb-3"><?php echo "$ ". number_format($rental_property_rs[12], 2)?></h5>
													<a class="d-block h5 mb-2" href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><?php echo $rental_property_rs[4]. ", ". $rental_property_rs[3]; ?></a>
													<p class="bg-light p-2 rounded"><i class="fa fa-map-marker-alt text-primary me-2"></i><strong><?php echo $rental_property_rs[5]. ", ". $rental_property_rs[6] . " - ". $rental_property_rs[7]; ?></strong></p>
													<p><i class="fa fa-calendar text-primary me-2"></i> Posted <?php echo time_formatter($rental_property_rs[16]); ?></p>
												</div>
												<div class="d-flex border-top">
													<small class="flex-fill text-center border-end py-2"><i class="fa fa-dollar text-primary me-2"></i><?php if ($rental_property_rs[13] == 0) { echo "No Deposit"; } else if ($rental_property_rs[13] > 0) { echo number_format($rental_property_rs[13], 2). " Deposit"; } ?></small>
													<small class="flex-fill text-center border-end py-2"><i class="fa fa-bed text-primary me-2"></i><?php echo $rental_property_rs[10]. " Bedrooms"; ?></small>
													<small class="flex-fill text-center py-2"><i class="fa fa-bath text-primary me-2"></i><?php echo $rental_property_rs[11]. " Bathrooms"; ?></small>
												</div>
											</div>
										</div><?php
									}
								} else {
									echo "<h5 class='text-center'>Rental Properties Not Found</h5>";
								}
							} else {
								echo "<h5 class='text-center'>". mysqli_error($conn). "</h5>";
							}
						?></div><?php
					}
				} else {
					echo "<h5 class='text-center'>Rental Properties Not Found</h5>";
				}
			} else {
				echo "<h5 class='text-center'>". mysqli_error($conn). "</h5>";
			}
		?></div><?php
			
	}

	//Sort rental properties by rental price website online
	function sort_rental_properties_by_rental_price_onilne_website($conn) {
		extract($_POST);
		$selected_sort_type = mysqli_real_escape_string($conn, $selected_sort_type);

		$generatedReportQuery = "SELECT rental_properties.rentalPropertyID, rental_properties.propertyPhotos, buildings.buildingID, buildings.buildingName, rental_properties.propertyName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, property_types.propertyTypeDescription, floors.floorDescription, rental_properties.noOfBedrooms, rental_properties.noOfBathrooms, rental_properties.rentalPrice, rental_properties.depositAmount, rental_property_statuses.propertyStatusDescription, rental_property_statuses.propertyStatusID, rental_properties.registerDate 
		FROM rental_properties 
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID 
		JOIN property_locations ON buildings.locationID = property_locations.locationID 
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID 
		JOIN floors ON rental_properties.floorID = floors.floorID 
		JOIN rental_property_statuses ON rental_properties.propertyStatus = rental_property_statuses.propertyStatusID 
		WHERE rental_properties.rentalPropertyID NOT IN (SELECT rentalPropertyID FROM booked_properties WHERE bookingStatus = 1) AND rental_properties.propertyStatus = '1' 
		ORDER BY rental_properties.rentalPrice ". $selected_sort_type;
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		?><div class="row g-4"><?php
			if ($reportQuery) {
				if (mysqli_num_rows($reportQuery) > 0) {
					while ($rental_property_rs = mysqli_fetch_array($reportQuery)) { ?>
						<div class="col-lg-4 col-md-6">
							<div class="property-item bg-white rounded overflow-hidden">
								<div class="position-relative overflow-hidden">
									<?php $property_photos = explode("###", $rental_property_rs[1]); ?>
									<a href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><img class="img-fluid" src="<?php echo "admin_panel/". $property_photos[0]; ?>" alt=""></a>
									<div class="bg-primary rounded text-white position-absolute start-0 top-0 m-4 py-1 px-3">For Rent</div>
									<div class="bg-danger rounded-top text-white position-absolute start-0 bottom-0 mx-4 pt-1 px-3"><?php echo $rental_property_rs[8]?></div>
								</div>
								<div class="p-4 pb-0">
									<h5 class="text-primary bg-light mb-3 p-2 rounded"><?php echo "$ ". number_format($rental_property_rs[12], 2)?></h5>
									<a class="d-block h5 mb-2" href="detail?property_id=<?php echo $rental_property_rs[0]; ?>"><?php echo $rental_property_rs[4]. ", ". $rental_property_rs[3]; ?></a>
									<p><i class="fa fa-map-marker-alt text-primary me-2"></i><?php echo $rental_property_rs[5]. ", ". $rental_property_rs[6] . " - ". $rental_property_rs[7]; ?></p>
									<p><i class="fa fa-calendar text-primary me-2"></i> Posted <strong><?php echo time_formatter($rental_property_rs[16]); ?></strong></p>
								</div>
								<div class="d-flex border-top">
									<small class="flex-fill text-center border-end py-2"><i class="fa fa-dollar text-primary me-2"></i><?php if ($rental_property_rs[13] == 0) { echo "No Deposit"; } else if ($rental_property_rs[13] > 0) { echo number_format($rental_property_rs[13], 2). " Deposit"; } ?></small>
									<small class="flex-fill text-center border-end py-2"><i class="fa fa-bed text-primary me-2"></i><?php echo $rental_property_rs[10]. " Bedrooms"; ?></small>
									<small class="flex-fill text-center py-2"><i class="fa fa-bath text-primary me-2"></i><?php echo $rental_property_rs[11]. " Bathrooms"; ?></small>
								</div>
							</div>
						</div><?php
					}
				} else {
					echo "<h5 class='text-center'>Rental Properties Not Found</h5>";
				}
			} else {
				echo "<h5 class='text-center'>". mysqli_error($conn). "</h5>";
			}
		?></div><?php
			
	}

    // Booking rental property from website online
	function book_rental_property_online($conn) {

		global $errorList;
		extract($_POST);
		$data = array();
		$customer_fullname = mysqli_real_escape_string($conn, $customer_fullname);
		$customer_passcode = mysqli_real_escape_string($conn, $customer_passcode);
		$rental_property_id = mysqli_real_escape_string($conn, $rental_property_id);
		$customer_phone = mysqli_real_escape_string($conn, $customer_phone);
		$total_paid_amount = 0.01;
		$deposit_account = mysqli_real_escape_string($conn, $merchant_idd);

		//Generate New ID for the current inserted booking ....
		$getMaxBookingID = mysqli_query($conn, "SELECT MAX(rowNo) FROM booked_properties") or die(mysqli_error($conn));
		if (mysqli_num_rows($getMaxBookingID) > 0) {
			$maxBookingID = mysqli_fetch_array($getMaxBookingID);
			$curMaxBookingID = $maxBookingID[0] + 1;
			$generatedBookingID = "PK" . sprintf("%04d", $curMaxBookingID);
		} else {
			$curMaxBookingID = 1;
			$generatedBookingID = "PK" . sprintf("%04d", $curMaxBookingID);
		}
		
		if ($deposit_account == "ACC0001") {

			$body = array(
				'schemaVersion' => '1.0',
				'requestId' => '10111331033',
				'timestamp' => date('Y-m-d H:i'),
				'channelName' => 'WEB',
				'serviceName' => 'API_PURCHASE',
				'serviceParams' => array(
					'merchantUid' => 'M0913227',
					'apiUserId' => '1007082',
					'apiKey' => 'API-2039520938AHX',
					'paymentMethod' => 'mwallet_account',
					'payerInfo' => array(
						'accountNo' => '252' . $customer_phone,
					),
					'transactionInfo' => array(
						'referenceId' => '12334',
						'invoiceId' => $generatedBookingID,
						'amount' => $total_paid_amount,
						'currency' => 'USD',
						'description' => 'Rental Property Booking - Online',
					),
				),
			);
	
			// Update the API endpoint URL
			$apiEndpoint = 'https://api.waafipay.net/asm';
			
			// responseMsg:
			$ch = curl_init($apiEndpoint);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
			
			$response = curl_exec($ch);
			curl_close($ch);
			
			// echo $response;
			
			// Decode the JSON response
			$checkout_response = json_decode($response, true);
			
			// Check if responseMsg is "RCS_SUCCESS"
			if (isset($checkout_response['responseMsg']) && $checkout_response['responseMsg'] == "RCS_SUCCESS") {

				// First search if this customer has already made a booking and it is already registered as a tenant
				$check_customer_exeistance = mysqli_query($conn, "SELECT * FROM tenants WHERE tenantMobile = '". $customer_phone ."'") or die(mysqli_error($conn));
				if ($check_customer_exeistance) {
					if (mysqli_num_rows($check_customer_exeistance) > 0) {
						$tenant_result = mysqli_fetch_array($check_customer_exeistance);
						$register_booking = mysqli_query($conn, "INSERT INTO booked_properties VALUES (NULL, '". $generatedBookingID ."', '". $tenant_result[1] ."', '". $rental_property_id ."', '". $total_paid_amount ."', '". $deposit_account ."', 'Rental Property Booking - Online#". $customer_phone ."', '". date("Y-m-d H:i") ."', '1', '-', '-')") or die(mysqli_error($conn));
						if ($register_booking) {
	
							//Save receipts into account_transactions Table
							//Generate New ID for the current inserted row....
							$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
							if (mysqli_num_rows($getTransactionMaxID) > 0) {
								$transMaxID = mysqli_fetch_array($getTransactionMaxID);
								$currentMaxID = $transMaxID[0] + 1;
								$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
							} else {
								$currentMaxID = 1;
								$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
							}
						
							$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $total_paid_amount) . "', '" . mysqli_real_escape_string($conn, $generatedBookingID) . "', 'Rental Property Booking - Online#". $customer_phone ."', '1', 'US2100002', '". date("Y-m-d H:i:s") ."', '-', '-')") or die(mysqli_error($conn));
							if ($registerTransaction) {
								// Send payment receipt notification through tenant's mobile number
        						if ($tenant_result[5] == "Male") {
        						    $cutomer_information = "Mudane ". $tenant_result[2];
        						} else if ($tenant_result[5] == "Female") {
        						    $cutomer_information = "Marwo ". $tenant_result[2];
        						}
						
								$messageBody = $cutomer_information. ", waxaan kugu wargelinaynaa in lacag dhan $". number_format($total_paid_amount, 2) ." laga qabtay telefoon number: ". $customer_phone ." lana dhigay Hormuud Merchant Account: 667839 taas oo ah lacag balan guri qabsasho ah (Booking), Tixraaca lacag bixintaadu waa: ". $generatedBookingID .". Fiiro gaar ah: Balanta guri qabsashadda waxa ay ku ektahay 24 saac sidoo kale ma lahan lacag dib u soo celin (No Refund). Wixii talo iyo tusaalooyiin ah, Fadlan naga soo wac +252614273333 ama noogu soo dir info@lighthousecore.com";

								// $messageBody = "Hello Dear ". $customer_fullname. ", this message is to inform you that the amount of $". number_format($total_paid_amount, 2) ." has been received from ". $customer_phone ." as the booking payment for ". $rental_property_id ." through the Hormuud Merchant Account: 667839. Your Booking ID: ". $generatedBookingID .". NB. Your booking will expire within 24 hours and then there will be no refunds. For further information, please contact +252614273333 or visit our website https://lighthousecore.com. Wish you the best.";
						
								$data = array(
									"refid" => "0", "mobile" => $customer_phone, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
								);
								$data1 = json_encode($data);
								$username = 'lighthouse1';
								$password = 'Sja3wj5EhSr4tggVLJmcCw==';
						
								$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
								$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
								curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
								curl_setopt($ch, CURLOPT_HEADER, 1);
								curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
								curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
								curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
								$return = curl_exec($ch);
								$return = explode(':', $return);
						
								// for ($i=0; $i < count($return) ; $i++) {
								//     echo $i. ':' . $return[$i];
								// }
								$stat = explode('"', $return[17]);
								$msg1 = explode(',', $return[20]);
								$msg = explode('"', $msg1[0]);
								// print_r($msg[1]);
							
								if ($stat[1] != 'Failed.') {
									$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedBookingID) . "', '" . $tenant_result[1] . "', 'Booking Notification', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $customer_phone ."', 'US2100002', '". date("Y-m-d H:i:s") ."')");
									if ($saveSms) {
										//$success_arr = array('message' => $msg[1]);
										$successMsg = "Booking completed successfully";
										$data = json_encode(array('Status' => true, 'Message' => $successMsg));
									} else {
										$errorMsg = mysqli_error($conn);
										$errorList[] = $errorMsg;
										$data = json_encode(array('Status' => false, 'Message' => $errorList));
									}
								} else {
									$errorList[] = $msg[1];
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								}
							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}

						} else {
							$errorMsg = mysqli_error($conn);
							$errorList[] = $errorMsg;
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}

					} else {

						// Register tenant first
						//Generate New ID for the current registered tenant ....
						$getMaxTenantID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenants") or die(mysqli_error($conn));
						if (mysqli_num_rows($getMaxTenantID) > 0) {
							$maxTenantID = mysqli_fetch_array($getMaxTenantID);
							$curMaxTenantID = $maxTenantID[0] + 1;
							$generatedTenantID = "TN" . sprintf("%04d", $curMaxTenantID);
						} else {
							$curMaxTenantID = 1;
							$generatedTenantID = "TN" . sprintf("%04d", $curMaxTenantID);
						}
						$register_tenant = mysqli_query($conn, "INSERT INTO tenants(tenantID, tenantName, tenantMobile, tenantPasscode, tenantStatus, tenantLoginStatus, registeredBy, registerDate, updatedBy, updatedDate, tenantPhoto, tenantIdentificationDocument) VALUES ('". $generatedTenantID ."', '". $customer_fullname ."', '". $customer_phone  ."', '". $customer_passcode ."', '2', '0', 'US2100002', '". date("Y-m-d H:i") ."', '-', '-', 'uploads/photos/no-image.jpg', 'uploads/documents/no-file.png')") or die(mysqli_error($conn));
						if ($register_tenant) {
							$register_booking = mysqli_query($conn, "INSERT INTO booked_properties VALUES (NULL, '". $generatedBookingID ."', '". $generatedTenantID ."', '". $rental_property_id ."', '". $total_paid_amount ."', '". $deposit_account ."', 'Rental Property Booking - Online#". $customer_phone ."', '". date("Y-m-d H:i") ."', '1', '-', '-')") or die(mysqli_error($conn));
							if ($register_booking) {
		
								//Save receipts into account_transactions Table
								//Generate New ID for the current inserted row....
								$getTransactionMaxID = mysqli_query($conn, "SELECT MAX(rowNo) FROM account_transactions") or die(mysqli_error($conn));
								if (mysqli_num_rows($getTransactionMaxID) > 0) {
									$transMaxID = mysqli_fetch_array($getTransactionMaxID);
									$currentMaxID = $transMaxID[0] + 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								} else {
									$currentMaxID = 1;
									$generatedTransactionID = "TR" . sprintf("%04d", $currentMaxID);
								}
							
								$registerTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . $deposit_account . "', '0', '" . mysqli_real_escape_string($conn, $total_paid_amount) . "', '" . mysqli_real_escape_string($conn, $generatedBookingID) . "', 'Rental Property Booking - Online#". $customer_phone ."', '1', 'US2100002', '". date("Y-m-d H:i:s") ."', '-', '-')") or die(mysqli_error($conn));
								if ($registerTransaction) {
									// Send payment receipt notification through tenant's mobile number
									$messageBody = "Hello Dear ". $customer_fullname. ", this message is to inform you that the amount of $". number_format($total_paid_amount, 2) ." has been received from ". $customer_phone ." as the booking payment for ". $rental_property_id ." through the Hormuud Merchant Account: 667839. Your Booking ID: ". $generatedBookingID .". NB. Your booking will expire within 24 hours and then there will be no refunds. For further information, please contact +252614273333 or visit our website https://lighthousecore.com. Wish you the best.";
							
									$data = array(
										"refid" => "0", "mobile" => $customer_phone, "message" => $messageBody, "senderid" => "TEST", "validity" => 5, "delivery" => 6,
									);
									$data1 = json_encode($data);
									$username = 'lighthouse1';
									$password = 'Sja3wj5EhSr4tggVLJmcCw==';
							
									$ch = curl_init("https://smsapi.hormuud.com/api/sms/Send");
									$headers = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("lighthouse1:Sja3wj5EhSr4tggVLJmcCw=="));
									curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
									curl_setopt($ch, CURLOPT_HEADER, 1);
									curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
									curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
									curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
									$return = curl_exec($ch);
									$return = explode(':', $return);
						
									// for ($i=0; $i < count($return) ; $i++) {
									//     echo $i. ':' . $return[$i];
									// }
									$stat = explode('"', $return[17]);
									$msg1 = explode(',', $return[20]);
									$msg = explode('"', $msg1[0]);
									// print_r($msg[1]);
								
									if ($stat[1] != 'Failed.') {
										$saveSms = mysqli_query($conn, "INSERT INTO bulk_sms VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedBookingID) . "', '" . $generatedTenantID . "', 'Booking Notification', '" . mysqli_real_escape_string($conn, $messageBody) . "', '1', '". $customer_phone ."', 'US2100002', '". date("Y-m-d H:i:s") ."')");
										if ($saveSms) {
											//$success_arr = array('message' => $msg[1]);
											$successMsg = "Booking completed successfully";
											$data = json_encode(array('Status' => true, 'Message' => $successMsg));
										} else {
											$errorMsg = mysqli_error($conn);
											$errorList[] = $errorMsg;
											$data = json_encode(array('Status' => false, 'Message' => $errorList));
										}
									} else {
										$errorList[] = $msg[1];
										$data = json_encode(array('Status' => false, 'Message' => $errorList));
									}
								} else {
									$errorMsg = mysqli_error($conn);
									$errorList[] = $errorMsg;
									$data = json_encode(array('Status' => false, 'Message' => $errorList));
								}

							} else {
								$errorMsg = mysqli_error($conn);
								$errorList[] = $errorMsg;
								$data = json_encode(array('Status' => false, 'Message' => $errorList));
							}
						} else {
							$errorMsg = mysqli_error($conn);
							$errorList[] = $errorMsg;
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}
					}

				} else {
					$errorMsg = mysqli_error($conn);
					$errorList[] = $errorMsg;
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}

			} else {
				// Handle other cases or errors
				$errorMsg = $checkout_response['responseMsg'];
				$errorList[] = $errorMsg;
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}

		} else if ($deposit_account == "ACC0002") {
		    



			
			$request_param = array("apiKey" => "HTmlhukw8bdFgrCwIOTB1BO19Qt74pCDfNnkFcFmz", "edahabNumber" => $customer_phone, "amount" => $total_paid_amount, "agentCode" => "099414", "returnUrl" => "http://lighthousecore.com/rental-properties-listing");

			/* Encode it into a JSON string. */
			$json = json_encode($request_param, JSON_UNESCAPED_SLASHES);

			$hashed = hash('SHA256', $json."cPbek0aR9tbklSKKbziaug7ou5XC9VHBFGlWMQ");

			$url = "https://edahab.net/api/api/IssueInvoice?hash=".$hashed;

			$curl = curl_init($url);
			// Tell cURL to send a POST request.
			curl_setopt($curl, CURLOPT_POST, TRUE);

			// Set the JSON object as the POST content.
			curl_setopt($curl, CURLOPT_POSTFIELDS, $json);

			// Set the JSON content-type: application/json.
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

			// Transfer the options -- Added by MC Hamouda
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

			// Send the request.
			$result = curl_exec($curl);

			$checkout_response = json_decode($result, true);

			if (isset($checkout_response['StatusCode']) && $checkout_response['StatusCode'] == 0) {

			    // First search if this customer has already made a booking and it is already registered as a tenant
    			$check_customer_exeistance = mysqli_query($conn, "SELECT * FROM tenants WHERE tenantMobile = '". $customer_phone ."'") or die(mysqli_error($conn));
    			if ($check_customer_exeistance) {
    				if (mysqli_num_rows($check_customer_exeistance) > 0) {
    					$tenant_result = mysqli_fetch_array($check_customer_exeistance);
    					$register_booking = mysqli_query($conn, "INSERT INTO booked_properties VALUES (NULL, '". $generatedBookingID ."', '". $tenant_result[1] ."', '". $rental_property_id ."', '". $total_paid_amount ."', '". $deposit_account ."', 'Rental Property Booking - Online#". $customer_phone ."', '". date("Y-m-d H:i") ."', '1', '-', '-')") or die(mysqli_error($conn));
    					if ($register_booking) {
    					    $saveInvoiceIdd = mysqli_query($conn, "INSERT INTO check_edahab_payments VALUES (NULL, '". mysqli_real_escape_string($conn, $checkout_response['InvoiceId']) ."', '". $generatedBookingID ."', 'RentalBookingOnline', '". $customer_phone ."', 0, '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
            				if ($saveInvoiceIdd) {
            					$successMsg = "https://edahab.net/api/payment?invoiceId=".$checkout_response['InvoiceId'];
            					$data = json_encode(array('Status' => true, 'Message' => $successMsg));	
            				} else {
							    $errorList[] = mysqli_error($conn);
            					$data = json_encode(array('Status' => false, 'Message' => $errorList));
            				}
						} else {
							$errorList[] = mysqli_error($conn);
							$data = json_encode(array('Status' => false, 'Message' => $errorList));
						}

    				} else {
    
    					// Register tenant first
    					//Generate New ID for the current registered tenant ....
    					$getMaxTenantID = mysqli_query($conn, "SELECT MAX(rowNo) FROM tenants") or die(mysqli_error($conn));
    					if (mysqli_num_rows($getMaxTenantID) > 0) {
    						$maxTenantID = mysqli_fetch_array($getMaxTenantID);
    						$curMaxTenantID = $maxTenantID[0] + 1;
    						$generatedTenantID = "TN" . sprintf("%04d", $curMaxTenantID);
    					} else {
    						$curMaxTenantID = 1;
    						$generatedTenantID = "TN" . sprintf("%04d", $curMaxTenantID);
    					}
    					$register_tenant = mysqli_query($conn, "INSERT INTO tenants(tenantID, tenantName, tenantMobile, tenantPasscode, tenantStatus, tenantLoginStatus, registeredBy, registerDate, updatedBy, updatedDate, tenantPhoto, tenantIdentificationDocument) VALUES ('". $generatedTenantID ."', '". $customer_fullname ."', '". $customer_phone  ."', '". $customer_passcode ."', '2', '0', 'US2100002', '". date("Y-m-d H:i") ."', '-', '-', 'uploads/photos/no-image.jpg', 'uploads/documents/no-file.png')") or die(mysqli_error($conn));
    					if ($register_tenant) {
    						$register_booking = mysqli_query($conn, "INSERT INTO booked_properties VALUES (NULL, '". $generatedBookingID ."', '". $generatedTenantID ."', '". $rental_property_id ."', '". $total_paid_amount ."', '". $deposit_account ."', 'Rental Property Booking - Online#". $customer_phone ."', '". date("Y-m-d H:i") ."', '1', '-', '-')") or die(mysqli_error($conn));
    						if ($register_booking) {
    						    $saveInvoiceIdd = mysqli_query($conn, "INSERT INTO check_edahab_payments VALUES (NULL, '". mysqli_real_escape_string($conn, $checkout_response['InvoiceId']) ."', '". $generatedBookingID ."', 'RentalBookingOnline', '". $customer_phone ."', 0, '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
                				if ($saveInvoiceIdd) {
                					$successMsg = "https://edahab.net/api/payment?invoiceId=".$checkout_response['InvoiceId'];
                					$data = json_encode(array('Status' => true, 'Message' => $successMsg));	
                				} else {
    							    $errorList[] = mysqli_error($conn);
                					$data = json_encode(array('Status' => false, 'Message' => $errorList));
                				}
    						} else {
    							$errorList[] = mysqli_error($conn);
    							$data = json_encode(array('Status' => false, 'Message' => $errorList));
    						}
    					} else {
    						$errorList[] = mysqli_error($conn);
    						$data = json_encode(array('Status' => false, 'Message' => $errorList));
    					}
    				}
    			} else {
    				$errorList[] = mysqli_error($conn);
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}

			} else {
				$errorList[] = "There is an error from the request response";
				$data = json_encode(array('Status' => false, 'Message' => $errorList));			
			}

		} else if ($deposit_account == "ACC0003") {

		}

		echo $data;
	}
	
	// Cancel Booked Property Automatically After 24 Hour
	function cancel_bookings_over24_hours_automatically($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		//Get Active Rents in the System
		$getBookingsOver24Hours = mysqli_query($conn, "SELECT bookingID, TIME_FORMAT(TIMEDIFF(NOW(), bookingDate),'%H') 'HoursSinceBooking' FROM booked_properties WHERE bookingStatus = '1' HAVING HoursSinceBooking > 24") or die(mysqli_error($conn));
		if ($getBookingsOver24Hours) {
			if (mysqli_num_rows($getBookingsOver24Hours) > 0) {
				while ($over24_hours_bookings_rs = mysqli_fetch_array($getBookingsOver24Hours)) {
					// Cancel this booking
					// print_r($over24_hours_bookings_rs);
					// echo "UPDATE booked_properties SET bookingStatus = '3' WHERE bookingID = '". mysqli_real_escape_string($conn, $over24_hours_bookings_rs[0]) ."'";
					mysqli_query($conn, "UPDATE booked_properties SET bookingStatus = '3' WHERE bookingID = '". mysqli_real_escape_string($conn, $over24_hours_bookings_rs[0]) ."'") or die (mysqli_error($conn));
				}
				$data = json_encode(array('Status' => true, 'Message' => 'Booking has been cancelled successfully'));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Bookings Over 24 Hours Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}


	
	// ================ END OF WEBSITE PORTAL MODULE =============================================

	// ALL FILLING FUNCTIONS =====================================================================

	// Fill Identification Document Types
	function fill_identification_document_types($conn) {
		$returned_data = array();
		$data = array();
		$getAllIdentificationDocumentTypes = mysqli_query($conn, "SELECT * FROM identification_document_types ORDER BY documentTypeName ASC") or die(mysqli_error($conn));
		if ($getAllIdentificationDocumentTypes) {
			if (mysqli_num_rows($getAllIdentificationDocumentTypes) > 0) {
				while ($row = mysqli_fetch_array($getAllIdentificationDocumentTypes)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Identification Document Types Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Fill Employee Departments
	function fill_employee_departments($conn) {
		$returned_data = array();
		$data = array();
		$getAllEmployeeDepartments = mysqli_query($conn, "SELECT * FROM departments ORDER BY departmentName ASC") or die(mysqli_error($conn));
		if ($getAllEmployeeDepartments) {
			if (mysqli_num_rows($getAllEmployeeDepartments) > 0) {
				while ($row = mysqli_fetch_array($getAllEmployeeDepartments)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Departments Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Fill Employee Posititons
	function fill_employee_positions($conn) {
		$returned_data = array();
		$data = array();
		$getAllEmployeePositions = mysqli_query($conn, "SELECT * FROM employee_positions WHERE positionID != 'PS0001' ORDER BY positionName ASC") or die(mysqli_error($conn));
		if ($getAllEmployeePositions) {
			if (mysqli_num_rows($getAllEmployeePositions) > 0) {
				while ($row = mysqli_fetch_array($getAllEmployeePositions)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Positions Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Fill All Tenants
	function fill_all_tenants($conn) {
		$returned_data = array();
		$data = array();
		$getAllTenants = mysqli_query($conn, "SELECT * FROM tenants ORDER BY tenantName ASC") or die(mysqli_error($conn));
		if ($getAllTenants) {
			if (mysqli_num_rows($getAllTenants) > 0) {
				while ($row = mysqli_fetch_array($getAllTenants)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Tenants Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Active Tenants
	function fill_active_tenants($conn) {
		$returned_data = array();
		$data = array();
		$getActiveTenants = mysqli_query($conn, "SELECT * FROM tenants WHERE tenantStatus = '1' ORDER BY tenantName ASC") or die(mysqli_error($conn));
		if ($getActiveTenants) {
			if (mysqli_num_rows($getActiveTenants) > 0) {
				while ($row = mysqli_fetch_array($getActiveTenants)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Tenants Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Fill Rental Buildings
	function fill_rental_buildings($conn) {
		$returned_data = array();
		$data = array();
		$getActiveTenants = mysqli_query($conn, "SELECT buildings.buildingID, buildings.buildingName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity
        FROM buildings
        JOIN property_locations ON buildings.locationID = property_locations.locationID
        WHERE buildings.buildingType = '1' 
        ORDER BY buildings.buildingName ASC") or die(mysqli_error($conn));
		if ($getActiveTenants) {
			if (mysqli_num_rows($getActiveTenants) > 0) {
				while ($row = mysqli_fetch_array($getActiveTenants)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Buildings Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fetch Tenant Information
	function fetch_tenant_information($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$getTenantInformation = mysqli_query($conn, "SELECT * FROM tenants WHERE tenantID = '". $selected_tenant_id ."'") or die(mysqli_error($conn));
		if ($getTenantInformation) {
			if (mysqli_num_rows($getTenantInformation) > 0) {
				while ($row = mysqli_fetch_array($getTenantInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Tenant Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Active Landlords
	function fill_active_landlords($conn) {
		$returned_data = array();
		$data = array();
		$getActiveLandlords = mysqli_query($conn, "SELECT * FROM landlords WHERE landlordStatus = '1' ORDER BY landlordName ASC") or die(mysqli_error($conn));
		if ($getActiveLandlords) {
			if (mysqli_num_rows($getActiveLandlords) > 0) {
				while ($row = mysqli_fetch_array($getActiveLandlords)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Landlords Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Property Locations
	function fill_property_locations($conn) {
		$returned_data = array();
		$data = array();
		$getPropertyLocations = mysqli_query($conn, "SELECT * FROM property_locations ORDER BY locationCity ASC") or die(mysqli_error($conn));
		if ($getPropertyLocations) {
			if (mysqli_num_rows($getPropertyLocations) > 0) {
				while ($row = mysqli_fetch_array($getPropertyLocations)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Locations Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Building Names
	function fill_building_names($conn) {
		$returned_data = array();
		$data = array();
		$getBuildingNames = mysqli_query($conn, "SELECT * FROM buildings WHERE buildingType = '1' ORDER BY buildingName ASC") or die(mysqli_error($conn));
		if ($getBuildingNames) {
			if (mysqli_num_rows($getBuildingNames) > 0) {
				while ($row = mysqli_fetch_array($getBuildingNames)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Buildings Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fetch Building Location
	function fetch_building_location($conn) {
		extract($_POST);
		$selected_building_id = mysqli_real_escape_string($conn, $selected_building_id);
		$data = array();
		$getBuildingLocation = mysqli_query($conn, "SELECT property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity FROM buildings JOIN property_locations ON buildings.locationID = property_locations.locationID WHERE buildings.buildingID = '". $selected_building_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($getBuildingLocation) > 0) {
			$location_rs = mysqli_fetch_array($getBuildingLocation);
			$locationInfo = $location_rs[0]. ", " . $location_rs[1]. " - ". $location_rs[2];
			$data = json_encode(array('Status' => true, 'Message' => $locationInfo));
		} else {
			$data = json_encode(array('Status' => false, 'Message' => "Location Not Found"));
		}
		echo $data;
	}

	// Fetch Building Location ID Only
	function fetch_building_location_id($conn) {
		extract($_POST);
		$selected_building_id = mysqli_real_escape_string($conn, $selected_building_id);
		$data = array();
		$getBuildingLocation = mysqli_query($conn, "SELECT locationID FROM buildings WHERE buildingID = '". $selected_building_id ."'") or die(mysqli_error($conn));
		if (mysqli_num_rows($getBuildingLocation) > 0) {
			$location_rs = mysqli_fetch_array($getBuildingLocation);
			$locationInfo = $location_rs[0];
			$data = json_encode(array('Status' => true, 'Message' => $locationInfo));
		} else {
			$data = json_encode(array('Status' => false, 'Message' => "Location Not Found"));
		}
		echo $data;
	}

	// Fill Property Types
	function fill_property_types($conn) {
		$returned_data = array();
		$data = array();
		$getPropertyTypes = mysqli_query($conn, "SELECT * FROM property_types ORDER BY propertyTypeDescription ASC") or die(mysqli_error($conn));
		if ($getPropertyTypes) {
			if (mysqli_num_rows($getPropertyTypes) > 0) {
				while ($row = mysqli_fetch_array($getPropertyTypes)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Types Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Floor No
	function fill_floor_numbers($conn) {
		$returned_data = array();
		$data = array();
		$getRentalPaymentType = mysqli_query($conn, "SELECT * FROM floors ORDER BY floorID ASC") or die(mysqli_error($conn));
		if ($getRentalPaymentType) {
			if (mysqli_num_rows($getRentalPaymentType) > 0) {
				while ($row = mysqli_fetch_array($getRentalPaymentType)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Payment Type Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Rental Property Payment Types
	function fill_rental_property_payment_types($conn) {
		$returned_data = array();
		$data = array();
		$getRentalPaymentType = mysqli_query($conn, "SELECT * FROM rental_property_payment_types ORDER BY paymentTypeID ASC") or die(mysqli_error($conn));
		if ($getRentalPaymentType) {
			if (mysqli_num_rows($getRentalPaymentType) > 0) {
				while ($row = mysqli_fetch_array($getRentalPaymentType)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Payment Type Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Rental Property Status
	function fill_rental_property_status($conn) {
		$returned_data = array();
		$data = array();
		$getRentalPropertyStatus = mysqli_query($conn, "SELECT * FROM rental_property_statuses ORDER BY propertyStatusID ASC") or die(mysqli_error($conn));
		if ($getRentalPropertyStatus) {
			if (mysqli_num_rows($getRentalPropertyStatus) > 0) {
				while ($row = mysqli_fetch_array($getRentalPropertyStatus)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Status Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Ongoing/Active Rents
	function fill_ongoing_rents($conn) {
		$returned_data = array();
		$data = array();
		$getOnGoingRents = mysqli_query($conn, "SELECT rented_properties.rentingID, tenants.tenantName, tenants.tenantMobile, rental_properties.propertyName, buildings.buildingName, property_locations.locationVillage, property_locations.locationDistrict, rented_properties.rentEndDate
		FROM rented_properties
		JOIN rental_properties ON rented_properties.rentalPropertyID = rental_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_locations ON buildings.locationID = property_locations.locationID
		JOIN tenants ON rented_properties.tenantID = tenants.tenantID
		WHERE rented_properties.rentEndDate >= '". date("Y-m-d H:i:s") ."' AND rented_properties.rentStatus = '1'") or die(mysqli_error($conn));
		if ($getOnGoingRents) {
			if (mysqli_num_rows($getOnGoingRents) > 0) {
				while ($row = mysqli_fetch_array($getOnGoingRents)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Ongoing Rents Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Property Type Information
	function fill_property_type_information($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		$getPropertyTypes = mysqli_query($conn, "SELECT * FROM property_types WHERE propertyTypeID = '". $selected_property_type_id ."' ORDER BY propertyTypeDescription ASC") or die(mysqli_error($conn));
		if ($getPropertyTypes) {
			if (mysqli_num_rows($getPropertyTypes) > 0) {
				while ($row = mysqli_fetch_array($getPropertyTypes)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Types Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Property Location Information
	function fill_property_location_information($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		$getPropertyTypes = mysqli_query($conn, "SELECT * FROM property_locations WHERE locationID = '". $selected_property_location_id ."' ORDER BY locationCity ASC") or die(mysqli_error($conn));
		if ($getPropertyTypes) {
			if (mysqli_num_rows($getPropertyTypes) > 0) {
				while ($row = mysqli_fetch_array($getPropertyTypes)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Types Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Total Bedrooms
	function fill_bedrooms($conn) {
		$returned_data = array();
		$data = array();
		$getTotalBedroom = mysqli_query($conn, "SELECT DISTINCT(noOfBedrooms) FROM rental_properties ORDER BY noOfBedrooms DESC") or die(mysqli_error($conn));
		if ($getTotalBedroom) {
			if (mysqli_num_rows($getTotalBedroom) > 0) {
				while ($row = mysqli_fetch_array($getTotalBedroom)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Bedrooms Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Price Range Reports
	function fill_price_range($conn) {
		$returned_data = array();
		$data = array();
		$getPriceRange = mysqli_query($conn, "SELECT DISTINCT(rentalPrice) FROM rental_properties ORDER BY rentalPrice DESC") or die(mysqli_error($conn));
		if ($getPriceRange) {
			if (mysqli_num_rows($getPriceRange) > 0) {
				while ($row = mysqli_fetch_array($getPriceRange)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Bedrooms Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Tenant Charge Types Reports
	function fill_tenant_charge_types($conn) {
		$returned_data = array();
		$data = array();
		$getChargeTypes = mysqli_query($conn, "SELECT * FROM charge_types WHERE chargeTypeFor = 'Tenants' ORDER BY chargeTypeName DESC") or die(mysqli_error($conn));
		if ($getChargeTypes) {
			if (mysqli_num_rows($getChargeTypes) > 0) {
				while ($row = mysqli_fetch_array($getChargeTypes)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Charge Types Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// Fill Landlord Charge Types Reports
	function fill_landlord_charge_types($conn) {
		$returned_data = array();
		$data = array();
		$getChargeTypes = mysqli_query($conn, "SELECT * FROM charge_types WHERE chargeTypeFor = 'Landlords' ORDER BY chargeTypeName DESC") or die(mysqli_error($conn));
		if ($getChargeTypes) {
			if (mysqli_num_rows($getChargeTypes) > 0) {
				while ($row = mysqli_fetch_array($getChargeTypes)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Charge Types Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// ================ End of Special System Functions ========================

	// ================ Start of Main System Reports ===========================

	// ---------------- Print employees report group ---------------------------
	function employeesReport($conn) {
		extract($_POST);
		$employe_id = mysqli_real_escape_string($conn, $emplInfoEmpReport);
		$str_datee = mysqli_real_escape_string($conn, substr($strDateEmpReport, 0, 10) . " 00:00:00");
		$end_datee = mysqli_real_escape_string($conn, substr($endTooEmpReport, 0, 10) . " 23:59:59");
		$qry = "";
		if ($employe_id == "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT * FROM `employees` WHERE titlePosition <> 0 ORDER BY empName") or die(mysqli_error($conn));
		} else if ($employe_id == "" && $str_datee != " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT * FROM `employees` WHERE registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND titlePosition <> 0 ORDER BY empName") or die(mysqli_error($conn));
		} else if ($employe_id != "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT * FROM `employees` WHERE empID = '" . $employe_id . "' AND titlePosition <> 0 ORDER BY empName") or die(mysqli_error($conn));
		} else {
			$qry = mysqli_query($conn, "SELECT * FROM `employees` WHERE empID = '" . $employe_id . "' AND registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND titlePosition <> 0 ORDER BY empName") or die(mysqli_error($conn));
		}
		$checkReturn = mysqli_num_rows($qry);
		if ($checkReturn > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printEmployeesReport"><i class="fa fa-print"></i> Print</button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="employeesReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="160px" /><br />
									<center><h2 style="color: #010132;">Employees Report</h2></center>
								</div>
							</div>
							<br />
							<?php
								if ($employe_id != "") {
									$get_emp_name = mysqli_query($conn, "SELECT empName from employees WHERE empID = '" . $employe_id . "'") or mysqli_error($conn);
									$emp_rs = mysqli_fetch_array($get_emp_name);
									$emp_name = $emp_rs[0];
									?><div class="row">
										<div class="col-md-8">&nbsp;</div>
										<div class="col-md-4 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left" style="font-size: 15px; font-weight: normal; padding-left: 15px;"><b>Employee Name:</b><?php echo $emp_name; ?></h5>
										</div>
									</div><?php
								} else {
									?><div class="row">
										<div class="col-md-8">&nbsp;</div>
										<div class="col-md-4 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left" style="font-size: 15px; font-weight: normal; padding-left: 15px;"><b>Report Type: </b> General (All)</h5>
										</div>
									</div><?php
								} 
							?>
							<div class="row"><?php
								if ($str_datee == " 00:00:00" && $end_datee == " 23:59:59") {

								} else {
									?><div class="col-md-4 text-left">
										<h5 class="text-left" style="font-size: 15px; font-weight: normal;"><b>Start Date (From):</b><?php echo substr($str_datee, 0, 10); ?></h5>
									</div>
									<div class="col-md-3 text-left">
										<h5 class="text-left" style="font-size: 15px; font-weight: normal;"><b>End Date (To):</b><?php echo substr($end_datee, 0, 10); ?></h5>
									</div><?php
								}
							?></div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<br />
									<?php
										if ($employe_id == "") {?>
											<div class="table-responsive">
												<table class="table table-bordered table-sm" style="font-size: 17px;">
													<thead>
														<tr class="bg-light">
															<th style="border-bottom: 1px solid black;"><center>Ser_No</center></th>
															<th style="border-bottom: 1px solid black;"><center>Employee Name</center></th>
															<th style="border-bottom: 1px solid black;"><center>Position</center></th>
															<th style="border-bottom: 1px solid black;"><center>Salary ($)</center></th>
															<th style="border-bottom: 1px solid black;"><center>Hire Date</center></th>
															<th style="border-bottom: 1px solid black;"><center>Mobile No</center></th>
															<th style="border-bottom: 1px solid black;"><center>Email</center></th>
															<th style="border-bottom: 1px solid black;"><center>Status</center></th>
														</tr>
													</thead>
													<tbody>
														<?php
															$i = 1;
															while ($result = mysqli_fetch_array($qry)) { ?>
																<tr>
																	<td align="center"><?php echo $i; ?></td>
																	<td><?php echo $result[2]; ?></td>
																	<td align="left"><?php echo $result[5]; ?></td>
																	<td align="center"><?php echo "$ " . number_format($result[6], 2); ?></td>
																	<td align="center"><?php echo $result[7]; ?></td>
																	<td align="left"><?php echo $result[10]; ?></td>
																	<td align="left"><?php echo $result[11]; ?></td>
																	<td align="center">
																		<?php if ($result[12] == "1") {
																			echo "<span class='badge badge-success col-12'>Working</span>";
																		} else {
																			echo "<span class='badge badge-danger col-12'>Left</span>";
																		} ?>
																	</td>
																</tr><?php
																$i++;
															}
														?>
													</tbody>
												</table>
											</div><?php
										} else {
											$result = mysqli_fetch_array($qry);
											$emplID = $result[1];
											$emplName = $result[2];
											$brthPlace = $result[3];
											$brthDate = $result[4];
											$title = $result[5];
											$salary = $result[6];
											$hireDate = $result[7];
											$Addreesss = $result[9];
											$emplMobilee = $result[10];
											$emplEmail = $result[11];
											$emplPhoto = $result[17];
											$emplStatus = $result[12];
											$registerDate = substr($result[14], 0, 16);
											$regisretedBy = $result[16]; ?>
											<div class="row" style="margin: 0px;">
												<div class="col-md-4 text-left"><img class="img-fluid" src="<?php echo $emplPhoto; ?>" width="150px" height="150px" /></div>
												<div class="col-md-8 text-left" style="padding: 10px 0px 50px 0px;">&nbsp;</div>
											</div>
											<br /><br />
											<div class="row" style="margin: 0px;">
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Employee ID</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $emplID; ?></h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Employee Name</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $emplName; ?></h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">
														Place of Birth</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $brthPlace; ?></h5>
												</div>
											</div>
											<div class="row" style="margin: 8px 0px 0px 0px;">
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Date of Birth</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $brthDate; ?></h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Position</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $title; ?></h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Salary ($)</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo "$ " . number_format($salary, 2); ?></h5>
												</div>
											</div>
											<div class="row" style="margin: 8px 0px 0px 0px;">
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Hire Date</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $hireDate; ?></h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Address</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $Addreesss; ?></h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Mobile No</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $emplMobilee; ?></h5>
												</div>
											</div>
											<div class="row" style="margin: 8px 0px 0px 0px;">
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Email Address</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo $emplEmail; ?></h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Employee Status</h5>
													<h5 style="font-size: 15px; font-weight: normal;">
														<?php 
															if ($emplStatus == "1") {
																echo "<span class='badge badge-success col-12'>Working</span>";
															} else {
																echo "<span class='badge badge-danger col-12'>Left</span>";
															} 
														?>
													</h5>
												</div>
												<div class="col-md-4">
													<h5 style="border-bottom: 1px dashed black; font-size: 16px; padding: 8px 8px 8px 0px;">Register Date</h5>
													<h5 style="font-size: 15px; font-weight: normal;"><?php echo substr($registerDate, 0, 16); ?></h5>
												</div>
											</div>
											<br /><br /><?php
										}
									?>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-4">&nbsp;</div>
								<div class="col-md-5">&nbsp;</div>
								<div class="col-md-3">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<center>
								<h3 style="font-family: 'Poppins'; color: maroon; font-weight: normal">Employee(s) information not
									found</h3>
							</center>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Account Statement
	function account_statement($conn) {
		extract($_POST);
		$selected_account_id = mysqli_real_escape_string($conn, $selected_account_id);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}
		$generatedReportQuery = "SELECT account_transactions.transactionID, account_transactions.registerDate, account_transactions.referenceID, account_transactions.transactionDescription, payment_gateways.gatewayType, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber, account_transactions.withdrawalAmount, account_transactions.depositedAmount, system_users.Username 
		FROM account_transactions 
		JOIN account_numbers ON account_transactions.accountNoID = account_numbers.accountNoID 
		JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID 
		JOIN system_users ON account_transactions.registeredBy = system_users.userID 
		WHERE account_transactions.accountNoID = '". $selected_account_id ."' ";
		if ($selected_date_type != 0) {
			$generatedReportQuery .= "AND account_transactions.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
		}
		$generatedReportQuery .= "AND account_transactions.transactionStatus = '1' 
		ORDER BY account_transactions.registerDate ASC";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printAccountStatement"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="accountStatementPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Account Statement</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
											if ($selected_date_type == 0) {
												$date_type_label = "All Date";
												$report_start_date = "-";
												$report_end_date = "-";
											} else if ($selected_date_type == 1) {
												$date_type_label = "Today";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 2) {
												$date_type_label = "Yesterday";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 3) {
												$date_type_label = "Last 3 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 4) {
												$date_type_label = "This Week";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 5) {
												$date_type_label = "Last 10 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 6) {
												$date_type_label = "This Month";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 7) {
												$date_type_label = "This Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 8) {
												$date_type_label = "This Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											}
										?>
										<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Account Information</h5>
											<h6 class="font-weight-normal">
												<?php 
													$get_account_details = mysqli_query($conn, "SELECT payment_gateways.gatewayType, payment_gateways.gatewayLogo, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber FROM account_numbers JOIN payment_gateways ON (account_numbers.gatewayID = payment_gateways.gatewayID) WHERE account_numbers.accountNoID = '" . $selected_account_id . "'") or mysqli_error($conn);
													$account_rs = mysqli_fetch_array($get_account_details);
													if ($account_rs[0] == 1) {
														?><span class="font-weight-bold;"><img class="img-fluid" src="<?php echo $account_rs[1]; ?>" width="25px"/> <?php echo $account_rs[2]; ?></span><?php
													} else if ($account_rs[0] == 2) {
														?><span class="font-weight-bold;"><img src="<?php echo $account_rs[1]; ?>" width="25px" /> <?php echo $account_rs[2]; ?> - <b><span class='text-danger'> <?php echo $account_rs[3]; ?></span></b> <b>(</b><?php echo $account_rs[4]; ?><b>)</b></span><?php
													} else if ($account_rs[0] == 3) {
														?><span class="font-weight-bold;"><img src="<?php echo $account_rs[1]; ?>" width="25px" /> <?php echo $account_rs[3]; ?></span></b> <b>(</b><?php echo $account_rs[4]; ?><b>)</b></h3><?php
													}

												?>
											</h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Date Type</h5>
											<h6 class="font-weight-normal"><?php echo $date_type_label; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Start Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_start_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">End Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_end_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm">
											<thead>
												<tr class="text-center">
													<th>Date</th>
													<th>Reference</th>
													<th>Remarks</th>
													<th>Account Information</th>
													<th>Withdrawal</th>
													<th>Deposit</th>
													<th>Balance</th>
												</tr>
											</thead>
											<tbody>
												<?php
													if ($selected_date_type == 0) {
														$open_balance_amount = 0;
													} else {
														$get_openning_balance = mysqli_query($conn, "SELECT ROUND(IFNULL(SUM(depositedAmount), 0), 2) - ROUND(IFNULL(SUM(withdrawalAmount), 0), 2) 'Openning Balance' FROM account_transactions WHERE accountNoID = '" . $selected_account_id . "' AND registerDate < '". substr($report_start_date, 0, 10) ." 00:00' AND account_transactions.transactionStatus = '1' GROUP BY accountNoID") or die(mysqli_error($conn));
														if (mysqli_num_rows($get_openning_balance) > 0) {
															$open_balance_rs = mysqli_fetch_array($get_openning_balance);
															$open_balance_amount = $open_balance_rs[0];
														} else {
															$open_balance_amount = 0;
														}
														
													}
													$total_withdraw_amount = 0;
													$total_deposit_amount = 0;
													$current_balance = $open_balance_amount;
													?><tr>
														<td class="text-right align-middle pr-3 font-weight-bold" colspan="6">Opening Balance</td>
														<td class="text-center"> <?php echo "$ " . number_format($current_balance, 2); ?></td>
													</tr><?php
													while ($result = mysqli_fetch_array($reportQuery)) {
														$total_withdraw_amount += $result[8];
														$total_deposit_amount += $result[9];
														$current_balance += $result[9] - $result[8];
														?><tr>
															<td class="text-center"> <?php echo substr($result[1], 0, 10); ?></td>
															<td class="text-left"><?php if ($result[2] != "0") { echo $result[2]; } else { echo $result[0]; } ?></td>
															<td class="text-left"> <?php echo $result[3]; ?></td>
															<td class="text-left">
																<?php 
																	if ($result[4] === "1") {
																		echo $result[5] . " (" . $result[7] . ") ";
																	} else if ($result[4] === "2") {
																		echo $result[5] . " " . $result[6] . " (" . $result[7] . ") ";
																	} else if ($result[4] === "3") {
																		echo $result[5] . " (" . $result[7] . ") ";
																	} 
																?>
															</td>
															<td class="text-center"> <?php echo "$ " . number_format($result[8], 2); ?></td>
															<td class="text-center"> <?php echo "$ " . number_format($result[9], 2); ?></td>
															<td class="text-center"> <?php echo "$ " . number_format($current_balance, 2); ?></td>
														</tr> <?php
													}
												?>
												<tr class="font-weight-bold bg-light">
													<td class="text-right align-middle pr-3" colspan="4">Total</td>
													<td class="text-center"> <?php echo "$ " . number_format($total_withdraw_amount, 2); ?></td>
													<td class="text-center"> <?php echo "$ " . number_format($total_deposit_amount, 2); ?></td>
													<td class="text-center"> <?php echo "$ " . number_format($current_balance, 2); ?></td>
												</tr>
												<tr>
													<td class="text-right align-middle pr-3" colspan="7">&nbsp;</td>
												</tr>
												<tr class="font-weight-bold">
													<?php
														if ($selected_date_type == 0) {
															$available_balance = $current_balance;
														} else {
															$get_available_balance = mysqli_query($conn, "SELECT ROUND(IFNULL(SUM(depositedAmount), 0), 2) - ROUND(IFNULL(SUM(withdrawalAmount), 0), 2) 'Available Balance' FROM account_transactions WHERE accountNoID = '" . $selected_account_id . "' AND registerDate > '" . substr($report_start_date, 0, 10) . " 00:00" . "' AND account_transactions.transactionStatus = '1' GROUP BY accountNoID") or die(mysqli_error($conn));
															if (mysqli_num_rows($get_available_balance) > 0) {
																$open_balance_rs = mysqli_fetch_array($get_available_balance);
																$available_balance = $open_balance_rs[0];
															} else {
																$available_balance = $current_balance;
															}
														}
													?>
													<td class="text-right align-middle pr-3" colspan="6">Available Balance</td>
													<td class="text-center"><?php echo "$ " . number_format($available_balance, 2); ?></td>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}


	// ---------------- Print Charged salaries report group --------------------
	function charged_salaries_report($conn) {
		extract($_POST);
		$employe_id = mysqli_real_escape_string($conn, $emplInfoChargeSalRep);
		$charge_salary_month = mysqli_real_escape_string($conn, $monthInfoChargeSalRep);
		$str_datee = mysqli_real_escape_string($conn, substr($strDateChargeSalRep, 0, 10) . " 00:00:00");
		$end_datee = mysqli_real_escape_string($conn, substr($endTooChargeSalRep, 0, 10) . " 23:59:59");
		$qry = "";
		if ($employe_id == "" && $charge_salary_month == "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id == "" && $charge_salary_month == "" && $str_datee != " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id == "" && $charge_salary_month != "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id == "" && $charge_salary_month != "" && $str_datee != " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id != "" && $charge_salary_month == "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id != "" && $charge_salary_month == "" && $str_datee != " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id != "" && $charge_salary_month != "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else {
			$qry = mysqli_query($conn, "SELECT charge_pay_salaries.employeeID, employees.employeeName, employees.titlePosition, charge_pay_salaries.salaryMonth, charge_pay_salaries.chargedAmount, charge_pay_salaries.registerDate, system_users.Username FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		}
		if (mysqli_num_rows($qry) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<button class="btn btn-success btn-sm" id="printChargeSalariesReport"><i class="fa fa-2x fa-print"></i>Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="chargeSalariesPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="160px" /><br />
									<center><h2 style="color: #010132;">Charged Salaries Report</h2></center>
								</div>
							</div>
							<br />
							<?php
								if ($employe_id != "" && $charge_salary_month == "") {
									$get_emp_name = mysqli_query($conn, "SELECT empName from employees WHERE empID = '" . $employe_id . "'") or mysqli_error($conn);
									$emp_rs = mysqli_fetch_array($get_emp_name);
									$emp_name = $emp_rs[0];
									?>
									<div class="row">
										<div class="col-md-7">&nbsp;</div>
										<div class="col-md-5 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Employee Name:</b><?php echo $emp_name; ?></h5>
										</div>
									</div><?php
								} else if ($employe_id == "" && $charge_salary_month != "") {
									?><div class="row">
										<div class="col-md-7">&nbsp;</div>
										<div class="col-md-5 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Salary Of:</b><?php echo $charge_salary_month; ?> </h5>
										</div>
									</div><?php
								} else {
									?><div class="row">
										<div class="col-md-8">&nbsp;</div>
										<div class="col-md-4 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left"style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Type: </b> General (All)</h5>
										</div>
									</div><?php
								}
							?>
							<div class="row">
								<?php
									if ($str_datee == " 00:00:00" && $end_datee == " 23:59:59") {

									} else {
										?><div class="col-md-4 text-left">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal;"><b>Start Date (From):</b><?php echo substr($str_datee, 0, 10); ?></h5>
										</div>
										<div class="col-md-3 text-left">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal;"><b>End Date (To):</b><?php echo substr($end_datee, 0, 10); ?></h5>
										</div><?php
									}
								?>
							</div>
							<div class="row">
								<div class="col-md-12"
									style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<br />
									<div class="table-responsive">
										<table class="table table-bordered table-sm" style="font-size: 17px;">
											<thead>
												<tr class="bg-light">
													<th style="border-bottom: 1px solid black;"><center>Serial</center></th>
													<th style="border-bottom: 1px solid black;"><center>Employee Name</center></th>
													<th style="border-bottom: 1px solid black;"><center>Position</center></th>
													<th style="border-bottom: 1px solid black;"><center>Salary Month</center></th>
													<th style="border-bottom: 1px solid black;"><center>Charge Date</center></th>
													<th style="border-bottom: 1px solid black;"><center>Charged By</center></th>
													<th style="border-bottom: 1px solid black;"><center>Charged Amount ($)</center></th>
												</tr>
											</thead>
											<tbody>
												<?php
													$i = 1;
													$totalChargedAmount = 0;
													while ($result = mysqli_fetch_array($qry)) { ?>
														<tr>
															<td align="center"><?php echo $i; ?></td>
															<td align="left"><?php echo $result[1]; ?></td>
															<td align="left"><?php echo $result[2]; ?></td>
															<td align="center"><?php echo $result[3]; ?></td>
															<td align="center"><?php echo substr($result[5], 0, 16); ?></td>
															<td align="center"><?php echo $result[6]; ?></td>
															<td align="center"><?php echo "$ " . number_format($result[4], 2); ?></td>
														</tr><?php
														$totalChargedAmount += $result[4];
														$i++;
													}
												?>
												<tr>
													<td align="right" colspan="6"><b>Total:</b></td>
													<td align="center"><b><?php echo "$ " . number_format($totalChargedAmount, 2); ?></b></td>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-9">&nbsp;</div>
								<div class="col-md-3">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<center><h5 style="font-family: 'Poppins'; color: maroon; font-weight: normal">Salary Charge(s) Not Found</h5></center>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// ---------------- Print salary payments report group ---------------------
	function chargeSalaryPaymentReport($conn) {
		extract($_POST);
		$employe_id = mysqli_real_escape_string($conn, $emplInfoSalaPaymRep);
		$charge_salary_month = mysqli_real_escape_string($conn, $monthInfoSalaPaymRep);
		$str_datee = mysqli_real_escape_string($conn, substr($strDateSalaPaymRep, 0, 10) . " 00:00:00");
		$end_datee = mysqli_real_escape_string($conn, substr($endTooSalaPaymRep, 0, 10) . " 23:59:59");
		$qry = "";
		if ($employe_id == "" && $charge_salary_month == "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id == "" && $charge_salary_month == "" && $str_datee != " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id == "" && $charge_salary_month != "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id == "" && $charge_salary_month != "" && $str_datee != " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0'AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id != "" && $charge_salary_month == "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id != "" && $charge_salary_month == "" && $str_datee != " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else if ($employe_id != "" && $charge_salary_month != "" && $str_datee == " 00:00:00") {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		} else {
			$qry = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID)  AND charge_pay_salaries.employeeID = '" . $employe_id . "' AND charge_pay_salaries.salaryMonth = '" . $charge_salary_month . "' AND charge_pay_salaries.registerDate BETWEEN '" . $str_datee . "' AND '" . $end_datee . "' AND charge_pay_salaries.transactionType = '0' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
		}
		if (mysqli_num_rows($qry) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<button class="btn btn-success btn-sm" id="printSalaryPaymentsReport"><i class="fa fa-2x fa-print"></i>Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="salaryPaymentsPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="160px" /><br /><br />
									<center><h2 style="color: #010132;">Employee Salary Payment Report</h2></center>
								</div>
							</div>
							<br />
							<?php
								if ($employe_id != "" && $charge_salary_month == "") {
									$get_emp_name = mysqli_query($conn, "SELECT empName from employees WHERE empID = '" . $employe_id . "'") or mysqli_error($conn);
									$emp_rs = mysqli_fetch_array($get_emp_name);
									$emp_name = $emp_rs[0];
									?>
									<div class="row">
										<div class="col-md-8">&nbsp;</div>
										<div class="col-md-4 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Employee Name:</b><?php echo $emp_name; ?></h5>
										</div>
									</div><?php
								} else if ($employe_id == "" && $charge_salary_month != "") {
									?><div class="row">
										<div class="col-md-8">&nbsp;</div>
										<div class="col-md-4 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Salary Month:</b><?php echo $charge_salary_month; ?></h5>
										</div>
									</div><?php
								} else {
									?><div class="row">
										<div class="col-md-8">&nbsp;</div>
										<div class="col-md-4 text-left" style="padding: 0px 20px 0px 0px;">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Date:</b><?php echo date("d M Y H:i"); ?></h5>
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Report Type: </b> General (All)</h5>
										</div>
									</div><?php
								}
							?>
							<div class="row">
								<?php
									if ($str_datee == " 00:00:00" && $end_datee == " 23:59:59") {
										
									} else {
										?><div class="col-md-4 text-left">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal;"><b>Start Date (From):</b><?php echo substr($str_datee, 0, 10); ?></h5>
										</div>
										<div class="col-md-3 text-left">
											<h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal;"><b>End Date (To):</b><?php echo substr($end_datee, 0, 10); ?></h5>
										</div><?php
									}
								?>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<br />
									<div class="table-responsive">
										<table class="table table-bordered table-sm" style="font-size: 17px;">
											<thead>
												<tr class="bg-light">
													<th style="border-bottom: 2px solid black;"><center>Serial</center></th>
													<th style="border-bottom: 2px solid black;"><center>Employee Name</center></th>
													<th style="border-bottom: 2px solid black;"><center>Salary Month</center></th>
													<th style="border-bottom: 2px solid black;"><center>Date</center></th>
													<th style="border-bottom: 2px solid black;"><center>Paid By</center></th>
													<th style="border-bottom: 2px solid black;"><center>Paid Amount ($)</center></th>
													<th style="border-bottom: 2px solid black;"><center>Charged Amount ($)</center></th>
												</tr>
											</thead>
											<tbody>
												<?php
													$totalChargedAmount = 0;
													$totalPaidAmount = 0;
													$f = 1;
													while ($result = mysqli_fetch_array($qry)) { ?>
														<tr>
															<td align="center"><?php echo $f; ?></td>
															<td align="left"><?php echo $result[1]; ?></td>
															<td align="center"><?php echo $result[2]; ?></td>
															<td align="center"><?php echo substr($result[3], 0, 10); ?></td>
															<td align="center"><?php echo $result[4]; ?></td>
															<td align="center"></td>
															<td align="center"><?php echo "<span> $ " . number_format($result[6], 2) . "</span>"; ?></td>
														</tr><?php
														$emploIDd = $result[0];
														$salMonth = $result[2];
														$innerPaid = 0;
														$getSalPaym = mysqli_query($conn, "SELECT employees.employeeID, employees.employeeName, charge_pay_salaries.salaryMonth, charge_pay_salaries.registerDate, system_users.Username, charge_pay_salaries.paidAmount, charge_pay_salaries.chargedAmount FROM charge_pay_salaries JOIN employees ON (charge_pay_salaries.employeeID = employees.employeeID) JOIN system_users ON (charge_pay_salaries.registeredBy = system_users.userID) WHERE charge_pay_salaries.employeeID = '" . $emploIDd . "' AND charge_pay_salaries.salaryMonth = '" . $salMonth . "' AND charge_pay_salaries.transactionType = '1' AND charge_pay_salaries.transactionStatus = '1' AND employees.titlePosition <> 0 ORDER BY charge_pay_salaries.rowNo DESC") or die(mysqli_error($conn));
														while ($rs = mysqli_fetch_array($getSalPaym)) {
															$j = $f + 1; //Increment the inner loop ?>
															<tr>
																<td align="center"><?php echo $j; ?></td>
																<td align="left"><?php echo $rs[1]; ?></td>
																<td align="center"><?php echo $rs[2]; ?></td>
																<td align="center"><?php echo substr($rs[3], 0, 10); ?></td>
																<td align="center"><?php echo $rs[4]; ?></td>
																<td align="center"><?php echo "<span> $ " . number_format($rs[5], 2) . "</span>"; ?></td>
																<td align="center"></td>
															</tr><?php
															$innerPaid += $rs[5];
															$f++;
														}
														$totalChargedAmount += $result[6];
														$totalPaidAmount += $innerPaid;
														$f++;
													}
												?>
												<tr>
													<td align="right" colspan="5"></td>
													<td align="center"><b>Total Paid<?php echo "<br /><span> $ " . number_format($totalPaidAmount, 2) . "</span></b>"; ?></h5></td>
													<td align="center"><b>Total Charged<?php echo "<br /><span> $ " . number_format($totalChargedAmount, 2), "</span></b>"; ?></h5>
													</td>
												</tr>
											</tbody>
										</table>
									</div>
									<div class="row" style="margin-top: 40px;">
										<div class="col-md-9">&nbsp;</div>
										<div class="col-md-3">
											<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
											<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<center><h5 style="font-family: 'Poppins'; color: maroon; font-weight: normal">Salary Payment(s) Not Found</h5></center>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Expenses Report
	function expenses_report($conn) {
		extract($_POST);
		$selected_expense_type = mysqli_real_escape_string($conn, $selected_expense_type);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}

		$generatedReportQuery = "SELECT expenses.expenseID, expenses.registerDate, expenses.expenseType, expenses.expenseRemarks, payment_gateways.gatewayType, payment_gateways.gatewayLogo, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber, processors.Username, verifiers.Username, expenses.expenseAmount
		FROM expenses 
		JOIN account_numbers ON (expenses.accountNoID = account_numbers.accountNoID) 
		JOIN payment_gateways ON (account_numbers.gatewayID = payment_gateways.gatewayID) 
		LEFT JOIN system_users AS processors ON expenses.registeredBy = processors.userID 
		LEFT JOIN system_users AS verifiers ON expenses.approvedBy = verifiers.userID 
		WHERE expenses.approvedBy != '-' AND expenses.expenseStatus != '0' ";
		if ($selected_expense_type != "") { 
			$generatedReportQuery .= "AND expenses.expenseType = '". $selected_expense_type ."' "; 
		}

		if ($selected_date_type != 0) {
			if ($selected_expense_type != "") {
				$generatedReportQuery .= "AND expenses.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "AND expenses.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY expenses.registerDate ASC";
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printExpensesReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="expensesReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center">Expenses Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
											if ($selected_date_type == 0) {
												$date_type_label = "All Date";
												$expenses_start_date = "-";
												$expenses_end_date = "-";
											} else if ($selected_date_type == 1) {
												$date_type_label = "Today";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											} else if ($selected_date_type == 2) {
												$date_type_label = "Yesterday";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											} else if ($selected_date_type == 3) {
												$date_type_label = "Last 3 Days";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											} else if ($selected_date_type == 4) {
												$date_type_label = "This Week";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											} else if ($selected_date_type == 5) {
												$date_type_label = "Last 10 Days";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											} else if ($selected_date_type == 6) {
												$date_type_label = "This Month";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											} else if ($selected_date_type == 7) {
												$date_type_label = "This Year";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											} else if ($selected_date_type == 8) {
												$date_type_label = "This Year";
												$expenses_start_date = $selected_start_date;
												$expenses_end_date = $selected_end_date;
											}
										?>
										<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Expense Type</h5>
											<h6 class="font-weight-normal"><?php if ($selected_expense_type === "") { echo "-"; } else { echo $selected_expense_type; } ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Date Type</h5>
											<h6 class="font-weight-normal"><?php echo $date_type_label; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Start Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($expenses_start_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">End Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($expenses_end_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("Y-m-d H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm">
											<thead>
												<tr class="bg-light text-center">
													<th>No</th>
													<th>Date</th>
													<th>Expense Type</th>
													<th>Desctiption</th>
													<th>Withdrawal Acc</th>
													<th>Processed</th>
													<th>Approved</th>
													<th>Paid Amount</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$count = 1;
													$total_expenses = 0;
													while ($result = mysqli_fetch_array($reportQuery)) { ?>
														<tr>
															<td class="text-center"><?php echo $count; ?></td>
															<td class="text-center"><?php echo substr($result[1], 0, 10); ?></td>
															<td><?php echo $result[2]; ?></td>
															<td><?php echo $result[3]; ?></td>
															<td>
																<?php 
																	if ($result[4] == "1") {
																		echo $result[6] . " (" . $result[8] . ") ";
																	} else if ($result[4] == "2") {
																		echo $result[6] . " " . $result[7] . " (" . $result[8] . ") ";
																	} else if ($result[4] == "3") {
																		echo $result[7] . " (" . $result[8] . ") ";
																	} 
																?>
															</td>
															<td><?php echo $result[9]; ?></td>
															<td><?php echo $result[10]; ?></td>
															<td class="text-center text-danger"><?php echo "$ ". number_format($result[11], 2); ?></td>
														</tr><?php
														$total_expenses += $result[11];
														$count++;
													}
												?>
												<tr>
													<td class="text-right font-weight-bold" colspan="7">Total Expenses</td>
													<td class="text-center text-danger"><?php echo "$ ". number_format($total_expenses, 2); ?></td>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// ================ End of Main System Reports ============================

	// ================ Start of Special System Reports =======================

	// Rented Properties Report
	function rented_properties_report($conn) {
		extract($_POST);
		$selected_property_type = mysqli_real_escape_string($conn, $selected_property_type);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}
		$generatedReportQuery = "SELECT rented_properties.rentingID, rental_properties.propertyName, buildings.buildingName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, tenants.tenantName, tenants.tenantMobile, rented_properties.rentStartDate, rented_properties.rentEndDate, rented_properties.rentStatus
		FROM rented_properties
		JOIN rental_properties ON rental_properties.rentalPropertyID = rented_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_locations ON buildings.locationID = property_locations.locationID
		JOIN tenants ON rented_properties.tenantID = tenants.tenantID ";
		if ($selected_property_type != "" || $selected_date_type != 0) { $generatedReportQuery .= "WHERE "; }
		if ($selected_property_type != "") { 
			$generatedReportQuery .= "rental_properties.propertyType = '". $selected_property_type ."' "; 
		}
		if ($selected_date_type != 0) {
			if ($selected_property_type != "") {
				$generatedReportQuery .= "AND rented_properties.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "rented_properties.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY rented_properties.rentingID DESC";
// 		echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printRentedPropertiesReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="rentedPropertiesReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Rented Properties Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
											if ($selected_date_type == 0) {
												$date_type_label = "All Date";
												$report_start_date = "-";
												$report_end_date = "-";
											} else if ($selected_date_type == 1) {
												$date_type_label = "Today";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 2) {
												$date_type_label = "Yesterday";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 3) {
												$date_type_label = "Last 3 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 4) {
												$date_type_label = "This Week";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 5) {
												$date_type_label = "Last 10 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 6) {
												$date_type_label = "This Month";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 7) {
												$date_type_label = "This Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 8) {
												$date_type_label = "This Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											}
										?>
										<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Property Type</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_property_type === "") { 
														echo "-"; 
													} else {
														$getPropertyTypes = mysqli_query($conn, "SELECT propertyTypeDescription FROM property_types WHERE propertyTypeID = '". $selected_property_type ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getPropertyTypes) > 0) {
															$prop_type_rs = mysqli_fetch_array($getPropertyTypes);
															echo $prop_type_rs[0];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Date Type</h5>
											<h6 class="font-weight-normal"><?php echo $date_type_label; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Start Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_start_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">End Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_end_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm" id="rentedPropertiesTable">
											<thead>
												<tr class="text-center">
													<th>No</th>
													<th>Property Name</th>
													<th>Tenant Name</th>
													<th>Rent Start-End Date</th>
													<th>Duration</th>
													<th>Status</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$x = 1;
													while ($rs = mysqli_fetch_array($reportQuery)) {
														$rent_start_date = strtotime(substr($rs[8], 0, 10));
														$rent_end_date = strtotime(substr($rs[9], 0, 10));
														$current_date = strtotime(date("Y-m-d"));
		
														$duration_in_months = ceil(($rent_end_date - $rent_start_date) / 2592000);
		
														?>
															<tr>
																<td class="text-center align-middle"><?php echo $x; ?></td>
																<td class="text-left"><?php echo "<span class='font-weight-bold'>". $rs[1]. ", ". $rs[2]. "</span><br/><span class='text-secondary'>". $rs[3] .", ". $rs[4] ."-". $rs[5]. "</span>"; ?></td>
																<td class="text-left align-middle"><?php echo "<span class='font-weight-bold'>". $rs[6] ."</span><br /><span class='text-secondary'>". $rs[7]. "</span>"; ?></td>
																<td class="text-center align-middle"><?php echo "<strong>". substr($rs[8], 0, 10). "</strong> - <strong>". substr($rs[9], 0, 10) ."</strong>"; ?></td>
																<td class="text-center align-middle">
																	<?php 
																		if ($duration_in_months == 1) {
																			echo $duration_in_months. " Month"; 
																		} else if ($duration_in_months > 1) {
																			echo $duration_in_months. " Months"; 
																		}
																	?>
																</td>
																<td class="text-center align-middle">
																	<?php
                                                                        if ($rs[10] == '0') {
                                                                            ?><span class="btn btn-outline-warning btn-sm border border-warning rounded-pill pl-3 pr-3"><i class="fa fa-times"></i>Cancel</span><?php
                                                                        } else if ($rs[10] == '1') {
                                                                            ?><span class="btn btn-outline-success btn-sm border border-success rounded-pill pl-3 pr-3"><i class="fa fa-calendar-check-o"></i>Active</span><?php
                                                                        } else if ($rs[10] == '2') {
                                                                            ?><span class="btn btn-outline-danger btn-sm border border-danger rounded-pill pl-3 pr-3"><i class="fa fa-calendar-times-o"></i>Expire</span><?php
                                                                        }
                                                                    ?>
																</td>
															</tr>
														<?php
														$x++;
													}
												?>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Expiring Contracts Report
	function expiring_contracts_report($conn) {
		extract($_POST);
		$selected_property_type = mysqli_real_escape_string($conn, $selected_property_type);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00",strtotime("last year January 1st"));
			$selected_end_date = date("Y-m-d 23:59",strtotime("last year December 31st"));
		} else if ($selected_date_type == 2) {
			$selected_start_date = date("Y-m-d 00:00", strtotime("first day of previous month"));
			$selected_end_date = date("Y-m-d 23:59", strtotime("last day of previous month"));
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-30 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("+1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("+1 days"));
		} else if ($selected_date_type == 8) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("last Saturday"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 9) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date('Y-m-d 23:59', strtotime('+7 days'));
		} else if ($selected_date_type == 10) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date('Y-m-d 23:59', strtotime('+10 days'));
		} else if ($selected_date_type == 11) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date('Y-m-d 23:59', strtotime('+30 days'));
		} else if ($selected_date_type == 12) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 13) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 14) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}
		$generatedReportQuery = "SELECT rented_properties.rentingID, rental_properties.propertyName, buildings.buildingName, property_locations.locationVillage, property_locations.locationDistrict, property_locations.locationCity, tenants.tenantName, tenants.tenantMobile, rented_properties.rentStartDate, rented_properties.rentEndDate, DATEDIFF(rented_properties.rentEndDate, CURDATE()) 'LeftDays', rented_properties.rentStatus
		FROM rented_properties
		JOIN rental_properties ON rental_properties.rentalPropertyID = rented_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN property_locations ON buildings.locationID = property_locations.locationID
		JOIN tenants ON rented_properties.tenantID = tenants.tenantID 
		WHERE rented_properties.rentStatus != '0' ";
		if ($selected_property_type != "" || $selected_date_type != 0) { $generatedReportQuery .= "AND "; }
		if ($selected_property_type != "") { 
			$generatedReportQuery .= "rental_properties.propertyType = '". $selected_property_type ."' "; 
		}
		if ($selected_date_type != 0) {
			if ($selected_property_type != "") {
				$generatedReportQuery .= "AND rented_properties.rentEndDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "rented_properties.rentEndDate  BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY rented_properties.rentEndDate DESC";
// 		echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printExpiringContractsReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="expiringContractsReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Rented Properties Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
											if ($selected_date_type == 0) {
												$date_type_label = "All Date";
												$report_start_date = "-";
												$report_end_date = "-";
											} else if ($selected_date_type == 1) {
												$date_type_label = "Last Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 2) {
												$date_type_label = "Last Month";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 3) {
												$date_type_label = "Last 30 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 4) {
												$date_type_label = "Last 10 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 5) {
												$date_type_label = "Yesterday";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 6) {
												$date_type_label = "Today";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 7) {
												$date_type_label = "Tomorrow";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 8) {
												$date_type_label = "This Week";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 9) {
												$date_type_label = "Next 7 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 10) {
												$date_type_label = "Next 10 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 11) {
												$date_type_label = "Next 30 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 12) {
												$date_type_label = "This Month";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 13) {
												$date_type_label = "This Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 14) {
												$date_type_label = "Custom Date";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											}
										?>
										<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Property Type</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_property_type === "") { 
														echo "-"; 
													} else {
														$getPropertyTypes = mysqli_query($conn, "SELECT propertyTypeDescription FROM property_types WHERE propertyTypeID = '". $selected_property_type ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getPropertyTypes) > 0) {
															$prop_type_rs = mysqli_fetch_array($getPropertyTypes);
															echo $prop_type_rs[0];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Date Type</h5>
											<h6 class="font-weight-normal"><?php echo $date_type_label; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Start Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_start_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">End Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_end_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm">
											<thead>
												<tr class="text-center" height="45px">
													<th class="align-middle">No</th>
													<th class="align-middle">Property Information</th>
													<th class="align-middle">Tenant Information</th>
													<th class="align-middle">Start Date</th>
													<th class="align-middle">End Date</th>
													<th class="align-middle">Status</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$x = 1;
													while ($rs = mysqli_fetch_array($reportQuery)) { ?>
														<tr>
															<td class="text-center align-middle"><?php echo $x; ?></td>
															<td class="text-left"><?php echo "<span class='font-weight-bold'>". $rs[1]. ", ". $rs[2]. "</span><br/><span class='text-secondary'>". $rs[3] .", ". $rs[4] ."-". $rs[5]. "</span>"; ?></td>
															<td class="text-left align-middle"><?php echo "<span class='font-weight-bold'>". $rs[6] ."</span><br /><span class='text-secondary'>". $rs[7]. "</span>"; ?></td>
															<td class="text-center align-middle"><?php echo substr($rs[8], 0, 10); ?></td>
															<td class="text-center align-middle"><?php echo substr($rs[9], 0, 10); ?></td>
															<td class="text-center align-middle" width="18%">
																<?php 
																	if ($rs[10] < 0) {
																		?><span class="btn btn-outline-danger btn-sm border border-danger rounded-pill d-block pt-2 pb-2"><strong><i class="fa fa-times"></i>Already Expired</strong><br /><?php echo "Expired ". abs($rs[10]). " Days Ago"; ?></span><?php
																	} else if ($rs[10] == 0) {
																		?><span class="btn btn-outline-warning btn-sm border border-warning rounded-pill d-block pt-2 pb-2"><strong><i class="fa fa-check"></i>Expiring Today </strong><br />Expires Today</span><?php
																	} else if ($rs[10] > 0) {
																		?><span class="btn btn-outline-success btn-sm border border-success rounded-pill d-block pt-2 pb-2"><strong><i class="fa fa-check-square"></i>Active Contract</strong><br /><?php echo "Expires After ". abs($rs[10]). " Days"; ?></span><?php
																	}
																?>
															</td>
														</tr>
													<?php
													$x++;
													}
												?>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Rental Charges Report
	function rental_charges_report($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$selected_charge_type = mysqli_real_escape_string($conn, $selected_charge_type);
		$selected_charge_month = mysqli_real_escape_string($conn, $selected_charge_month);
		$generatedReportQuery = "SELECT tenant_charges.registerDate, charge_types.chargeTypeName, tenants.tenantName, tenants.tenantMobile, rental_properties.propertyName, buildings.buildingName, property_types.propertyTypeDescription, tenant_charges.chargeRemarks, tenant_charges.chargeMonth, tenant_charges.chargedAmount
		FROM tenant_charges
		JOIN tenants ON tenant_charges.tenantID = tenants.tenantID
		JOIN rental_properties ON tenant_charges.rentalPropertyID = rental_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN charge_types ON tenant_charges.chargeTypeID = charge_types.chargeTypeID
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID ";
		if ($selected_tenant_id != "" || $selected_charge_type != "" || $selected_charge_month != "-") { $generatedReportQuery .= "WHERE "; }
		if ($selected_tenant_id != "") { 
			$generatedReportQuery .= "tenant_charges.tenantID = '". $selected_tenant_id ."' "; 
		}
		if ($selected_charge_type != "") {
			if ($selected_tenant_id != "") {
				$generatedReportQuery .= "AND tenant_charges.chargeTypeID = '". $selected_charge_type ."' "; 
			} else {
				$generatedReportQuery .= "tenant_charges.chargeTypeID = '". $selected_charge_type ."' "; 
			}
		}
		if ($selected_charge_month != "-") {
			if ($selected_tenant_id != "" || $selected_charge_type != "") {
				$generatedReportQuery .= "AND tenant_charges.chargeMonth = '". $selected_charge_month ."' "; 
			} else {
				$generatedReportQuery .= "tenant_charges.chargeMonth = '". $selected_charge_month ."' "; 
			}
		}

		$generatedReportQuery .= "ORDER BY tenant_charges.registerDate DESC";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile mt-3">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printRentalChargesReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="rentalChargesReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Rental Charges Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
									<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Tenant Name</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_tenant_id === "") { 
														echo "-"; 
													} else {
														$getTenantName = mysqli_query($conn, "SELECT tenantName FROM tenants WHERE tenantID = '". $selected_tenant_id ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getTenantName) > 0) {
															$tenant_info_rs = mysqli_fetch_array($getTenantName);
															echo $tenant_info_rs[0];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Charge Type</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_charge_type === "") { 
														echo "-"; 
													} else {
														$getChargeType = mysqli_query($conn, "SELECT * FROM charge_types WHERE chargeTypeID = '". $selected_charge_type ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getChargeType) > 0) {
															$charge_type_rs = mysqli_fetch_array($getChargeType);
															echo $charge_type_rs[2];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Charge Month</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_charge_type == "-") { 
														echo "-"; 
													} else {
														echo $selected_charge_month; 
													}
												?>
											</h6>										
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm" id="rentedPropertiesTable">
											<thead>
												<tr class="text-center">
													<th>Charge Date</th>
													<th>Charge Type</th>
													<th>Tenant Information</th>
													<th>Remarks</th>
													<th>Charged Month</th>
													<th>Charged Amount</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$x = 1;
													$total_charged_rental = 0;
													while ($rs = mysqli_fetch_array($reportQuery)) { ?>
														<tr>
															<td class="text-center align-middle"><?php echo substr($rs[0], 0, 10); ?></td>
															<td class="text-left align-middle"><?php echo $rs[1]; ?></td>
															<td class="text-left"><?php echo "<span class='font-weight-bold'>". $rs[2]. " - ". $rs[3]. "</span><br/><span class='text-secondary'>". $rs[4] .", ". $rs[5] ." - ". $rs[6]. "</span>"; ?></td>
															<td class="text-left align-middle"><?php echo $rs[7]; ?></td>
															<td class="text-left align-middle"><?php echo $rs[8]; ?></td>
															<td class="text-center align-middle"><?php echo "$". number_format($rs[9], 2); ?></td>
														</tr>
														<?php
														$total_charged_rental += $rs[9];
														$x++;
													}
												?>
												<tr class="bg-light">
													<td class="text-right align-middle pr-3 font-weight-bold" colspan="5">Total</td>
													<td class="text-center align-middle font-weight-bold"><?php echo "$". number_format($total_charged_rental, 2); ?></td>
												
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile mt-3">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Rental Payments Report
	function rental_payments_report($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		if ($selected_date_type == 1) {
			$selected_start_date = date("Y-m-d 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 2) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-1 days"));
			$selected_end_date = date('Y-m-d 23:59', strtotime("-1 days"));
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-3 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 00:00', strtotime('last Saturday'));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 00:00', strtotime("-10 days"));
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 00:00");
			$selected_end_date = date("Y-m-d 23:59");
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 00:00");
			$selected_end_date = mysqli_real_escape_string($conn, substr($selected_end_date, 0, 10) . " 23:59");
		}
		$generatedReportQuery = "SELECT tenant_receipts.registerDate, tenants.tenantName, tenants.tenantMobile, rental_properties.propertyName, buildings.buildingName, property_types.propertyTypeDescription, tenant_receipts.receiptDescription, payment_gateways.gatewayType, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber, tenant_receipts.paidAmount
		FROM tenant_receipts 
		JOIN tenants ON tenant_receipts.tenantID = tenants.tenantID
		JOIN rented_properties ON tenant_receipts.rentingID = rented_properties.rentingID
		JOIN rental_properties ON rented_properties.rentalPropertyID = rental_properties.rentalPropertyID 
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID 
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID
		JOIN account_numbers ON tenant_receipts.accountNoID = account_numbers.accountNoID 
		JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID ";
		if ($selected_tenant_id != "" || $selected_date_type != 0) { $generatedReportQuery .= "WHERE "; }
		if ($selected_tenant_id != "") { 
			$generatedReportQuery .= "tenant_receipts.tenantID = '". $selected_tenant_id ."' "; 
		}
		if ($selected_date_type != 0) {
			if ($selected_tenant_id != "") {
				$generatedReportQuery .= "AND tenant_receipts.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			} else {
				$generatedReportQuery .= "tenant_receipts.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."' "; 
			}
		}
		$generatedReportQuery .= "ORDER BY tenant_receipts.registerDate DESC";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printRentalPaymentsReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="rentalPaymentsReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Rental Payments Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<?php
											if ($selected_date_type == 0) {
												$date_type_label = "All Date";
												$report_start_date = "-";
												$report_end_date = "-";
											} else if ($selected_date_type == 1) {
												$date_type_label = "Today";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 2) {
												$date_type_label = "Yesterday";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 3) {
												$date_type_label = "Last 3 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 4) {
												$date_type_label = "This Week";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 5) {
												$date_type_label = "Last 10 Days";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 6) {
												$date_type_label = "This Month";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 7) {
												$date_type_label = "This Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											} else if ($selected_date_type == 8) {
												$date_type_label = "This Year";
												$report_start_date = $selected_start_date;
												$report_end_date = $selected_end_date;
											}
										?>
										<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Property Type</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_tenant_id === "") { 
														echo "-"; 
													} else {
														$getTenantInfo = mysqli_query($conn, "SELECT tenantName FROM tenants WHERE tenantID = '". $selected_tenant_id ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getTenantInfo) > 0) {
															$tenant_info = mysqli_fetch_array($getTenantInfo);
															echo $tenant_info[0];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Date Type</h5>
											<h6 class="font-weight-normal"><?php echo $date_type_label; ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Start Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_start_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">End Date</h5>
											<h6 class="font-weight-normal"><?php echo substr($report_end_date, 0, 10); ?></h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm" id="rentedPropertiesTable">
											<thead>
												<tr class="text-center">
													<th>Payment Date</th>
													<th>Tenant Information</th>
													<th>Remarks</th>
													<th>Deposit Account</th>
													<th>Paid Amount</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$total_paid_rental = 0;
													while ($rs = mysqli_fetch_array($reportQuery)) { ?>
														<tr>
															<td class="text-center align-middle"><?php echo substr($rs[0], 0, 10); ?></td>
															<td class="text-left"><?php echo "<span class='font-weight-bold'>". $rs[1]. " - ". $rs[2]. "</span><br/><span class='text-secondary'>". $rs[3] .", ". $rs[4] ." - ". $rs[5]. "</span>"; ?></td>
															<td class="text-left align-middle"><?php echo $rs[6]; ?></td>
															<td class="text-left align-middle">
																<?php
																	if ($rs[7] === "1") {
																		echo $rs[8] . " (" . $rs[10] . ") ";
																	} else if ($rs[7] === "2") {
																		echo $rs[8] . " " . $rs[9] . " (" . $rs[10] . ") ";
																	} else if ($rs[7] === "3") {
																		echo $rs[8] . " (" . $rs[10] . ") ";
																	}
																?>
															</td>
															<td class="text-center align-middle"><?php echo "$". number_format($rs[11], 2); ?></td>
														
														</tr>
														<?php
														$total_paid_rental += $rs[11];
													}
												?>
												<tr class="bg-light">
													<td class="text-right align-middle pr-3 font-weight-bold" colspan="4">Total</td>
													<td class="text-center align-middle font-weight-bold"><?php echo "$". number_format($total_paid_rental, 2); ?></td>
												
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Overdue Date Rents Report
	function overdue_date_rents_report($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$selected_charge_type = mysqli_real_escape_string($conn, $selected_charge_type);
		$selected_charge_month = mysqli_real_escape_string($conn, $selected_charge_month);

		$generatedReportQuery = "SELECT tenant_charges.registerDate, charge_types.chargeTypeName, tenants.tenantName, tenants.tenantMobile, rental_properties.propertyName, buildings.buildingName, property_types.propertyTypeDescription, tenant_charges.chargeMonth, DATE(DATE_ADD(tenant_charges.registerDate, INTERVAL (rented_properties.rentPaymentDay-rented_properties.rentChargeDay) DAY)) 'PaymentDate', DATEDIFF(CURDATE(), DATE_ADD(tenant_charges.registerDate, INTERVAL (rented_properties.rentPaymentDay-rented_properties.rentChargeDay) DAY)) 'OverDueDays',  IFNULL(tenant_charges.chargedAmount, 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0) 'TotalRemaining'
		FROM tenant_charges
		JOIN tenants ON tenant_charges.tenantID = tenants.tenantID
		JOIN rented_properties ON tenant_charges.rentingID = rented_properties.rentingID
		LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID
		JOIN rental_properties ON rented_properties.rentalPropertyID = rental_properties.rentalPropertyID
		JOIN buildings ON rental_properties.buildingID = buildings.buildingID
		JOIN charge_types ON tenant_charges.chargeTypeID = charge_types.chargeTypeID
		JOIN property_types ON rental_properties.propertyType = property_types.propertyTypeID
		WHERE ";
		// if ($selected_tenant_id != "" || $selected_charge_type != "" || $selected_charge_month != "-") { $generatedReportQuery .= "WHERE "; }
		if ($selected_tenant_id != "") { 
			$generatedReportQuery .= "tenant_charges.tenantID = '". $selected_tenant_id ."' AND "; 
		}
		if ($selected_charge_type != "") {
			if ($selected_tenant_id != "") {
				$generatedReportQuery .= "tenant_charges.chargeTypeID = '". $selected_charge_type ."' AND "; 
			} else {
				$generatedReportQuery .= "tenant_charges.chargeTypeID = '". $selected_charge_type ."' AND "; 
			}
		}
		if ($selected_charge_month != "-") {
			if ($selected_tenant_id != "" || $selected_charge_type != "") {
				$generatedReportQuery .= "tenant_charges.chargeMonth = '". $selected_charge_month ."' AND "; 
			} else {
				$generatedReportQuery .= "tenant_charges.chargeMonth = '". $selected_charge_month ."' AND "; 
			}
		}

		$generatedReportQuery .= "DATE(DATE_ADD(tenant_charges.registerDate, INTERVAL (rented_properties.rentPaymentDay-rented_properties.rentChargeDay) DAY)) < CURDATE() GROUP BY tenant_charges.chargeID HAVING TotalRemaining > 0";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile mt-3">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printOverdueDateRentsReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="overdueDateRentsPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Overdue Date Rents Report</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
									<div class="col-md-4 pb-2">
											<h5 class="font-weight-bold">Tenant Name</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_tenant_id === "") { 
														echo "-"; 
													} else {
														$getTenantName = mysqli_query($conn, "SELECT tenantName FROM tenants WHERE tenantID = '". $selected_tenant_id ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getTenantName) > 0) {
															$tenant_info_rs = mysqli_fetch_array($getTenantName);
															echo $tenant_info_rs[0];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Charge Type</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_charge_type === "") { 
														echo "-"; 
													} else {
														$getChargeType = mysqli_query($conn, "SELECT * FROM charge_types WHERE chargeTypeID = '". $selected_charge_type ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getChargeType) > 0) {
															$charge_type_rs = mysqli_fetch_array($getChargeType);
															echo $charge_type_rs[2];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-3 pb-2">
											<h5 class="font-weight-bold">Charge Month</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_charge_type == "-") { 
														echo "-"; 
													} else {
														echo $selected_charge_month; 
													}
												?>
											</h6>										
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm" id="rentedPropertiesTable">
											<thead>
												<tr class="text-center">
													<th>Charge Date</th>
													<th>Charge Type</th>
													<th>Tenant Information</th>
													<th>Charged Month</th>
													<th>Payment Date</th>
													<th>Overdue Days</th>
													<th>Overdue Balance</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$total_charged_rental = 0;
													while ($rs = mysqli_fetch_array($reportQuery)) { ?>
														<tr>
															<td class="text-center align-middle"><?php echo substr($rs[0], 0, 10); ?></td>
															<td class="text-left align-middle"><?php echo $rs[1]; ?></td>
															<td class="text-left"><?php echo "<span class='font-weight-bold'>". $rs[2]. " - ". $rs[3]. "</span><br/><span class='text-secondary'>". $rs[4] .", ". $rs[5] ." - ". $rs[6]. "</span>"; ?></td>
															<td class="text-left align-middle"><?php echo $rs[7]; ?></td>
															<td class="text-center align-middle"><?php echo $rs[8]; ?></td>
															<td class="text-center align-middle text-danger font-weight-bold"><?php echo $rs[9]; ?></td>
															<td class="text-center align-middle"><?php echo "$". number_format($rs[10], 2); ?></td>
														</tr>
														<?php
														$total_charged_rental += $rs[10];
													}
												?>
												<tr class="bg-light">
													<td class="text-right align-middle pr-3 font-weight-bold" colspan="6">Total</td>
													<td class="text-center align-middle font-weight-bold"><?php echo "$". number_format($total_charged_rental, 2); ?></td>
												
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile mt-3">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}

	// Tenant Balance Sheet
	function tenant_balance_sheet($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$generatedReportQuery = "SELECT tenant_charges.tenantID, tenants.tenantName, tenants.tenantMobile, IFNULL(SUM(tenant_charges.chargedAmount), 0) 'TotalCharged', IFNULL(SUM(tenant_receipts.paidAmount), 0) 'TotalPaid', IFNULL(SUM(tenant_charges.chargedAmount), 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0) 'Remaining'
		FROM tenant_charges 
		JOIN tenants ON tenant_charges.tenantID = tenants.tenantID 
		LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID ";
		if ($selected_tenant_id != "") { 
			$generatedReportQuery .= "WHERE tenant_charges.tenantID = '". $selected_tenant_id ."' "; 
		}
		$generatedReportQuery .= "GROUP BY tenant_charges.tenantID HAVING Remaining > 0 
		ORDER BY Remaining DESC";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile mt-3">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printTenantBalanceSheetReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="tenantBalanceSheetReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Tenant Balance Sheet</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<div class="col-md-10 pb-2">
											<h5 class="font-weight-bold">Tenant Name</h5>
											<h6 class="font-weight-normal">
												<?php 
													if ($selected_tenant_id === "") { 
														echo "-"; 
													} else {
														$getTenantInfo = mysqli_query($conn, "SELECT tenantName FROM tenants WHERE tenantID = '". $selected_tenant_id ."' ") or die(mysqli_error($conn));
														if (mysqli_num_rows($getTenantInfo) > 0) {
															$tenant_info = mysqli_fetch_array($getTenantInfo);
															echo $tenant_info[0];
														}
													}
												?>
											</h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm" id="rentedPropertiesTable">
											<thead>
												<tr class="text-center">
													<th>Tenant ID</th>
													<th>Tenant Name</th>
													<th>Mobile Phone</th>
													<th>Total Charged</th>
													<th>Total Paid</th>
													<th>Remaining</th>
													<th>Action</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$tenant_total_charged = 0;
													$tenant_total_paid = 0;
													$tenant_total_remaining = 0;
													while ($rs = mysqli_fetch_array($reportQuery)) { ?>
														<tr>
															<td class="text-center"><?php echo substr($rs[0], 0, 10); ?></td>
															<td class="text-left"><?php echo $rs[1]; ?></td>
															<td class="text-center"><?php echo $rs[2]; ?></td>
															<td class="text-center"><?php echo "$ ". number_format($rs[3], 2); ?></td>
															<td class="text-center"><?php echo "$ ". number_format($rs[4], 2); ?></td>
															<td class="text-center text-danger"><?php echo "$ ". number_format($rs[5], 2); ?></td>
															<td class="text-center">
																<span class="btn btn-sm btn-secondary btnViewIndividualTenantBalanceSheet" id="<?php echo "Update". $rs[0]; ?>" data-id="<?php echo $rs[0]; ?>" data-toggle="modal" data-target="#viewIndividualTenantBalanceSheetModal"><i class="fa fa-eye"></i> See Details</span>  
															</td>
														</tr>
														<?php
														$tenant_total_charged += $rs[3];
														$tenant_total_paid += $rs[4];
														$tenant_total_remaining += $rs[5];
													}
												?>
												<tr class="bg-light font-weight-bold">
													<td class="text-right pr-3" colspan="3">Total</td>
													<td class="text-center"><?php echo "$". number_format($tenant_total_charged, 2); ?></td>
													<td class="text-center"><?php echo "$". number_format($tenant_total_paid, 2); ?></td>
													<td class="text-center text-danger"><?php echo "$". number_format($tenant_total_remaining, 2); ?></td>
													<td class="text-center"> </td>
												
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile mt-3">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}
	
	// View Individual Tenant Balance Sheet
	function view_individual_tenant_balance_sheet($conn) {
		extract($_POST);
		$selected_tenant_id = mysqli_real_escape_string($conn, $selected_tenant_id);
		$generatedReportQuery = "SELECT tenant_charges.tenantID, tenants.tenantName, tenants.tenantMobile, IFNULL(SUM(tenant_charges.chargedAmount), 0) 'TotalCharged', IFNULL(SUM(tenant_receipts.paidAmount), 0) 'TotalPaid', IFNULL(SUM(tenant_charges.chargedAmount), 0) - IFNULL(SUM(tenant_receipts.paidAmount), 0) 'Remaining'
		FROM tenant_charges 
		JOIN tenants ON tenant_charges.tenantID = tenants.tenantID 
		LEFT JOIN tenant_receipts ON tenant_charges.chargeID = tenant_receipts.chargeID
		WHERE tenant_charges.tenantID = '". $selected_tenant_id ."'
		GROUP BY tenant_charges.chargeID HAVING Remaining > 0 
		ORDER BY Remaining DESC";
		// echo $generatedReportQuery;
		$reportQuery = mysqli_query($conn, $generatedReportQuery) or die(mysqli_error($conn));
		if (mysqli_num_rows($reportQuery) > 0) { ?>
			<div class="tile mt-3">
				<div class="tile-body">
					<div class="row" style="margin: 0px;">
						<div class="col-md-12 text-right">
							<br /><button class="btn btn-success btn-sm" id="printIndividualTenantBalanceSheetReport"><i class="fa fa-print"></i> Print </button><br /><br />
						</div>
					</div>
					<div class="row" style="margin-left: 0px; margin-right: 0px;" id="individualTenantBalanceSheetReportPrintArea">
						<div class="col-md-12">
							<div class="row">
								<div class="col-md-12" style="margin: 0px;">
									<img src="img/reportHeader.png" width="100%" height="170px" /><br />
									<h2 class="text-center text-primary">Individual Tenant Balance Sheet</h2>
								</div>
							</div>
							<div class="row">
								<div class="col-md-12" style="background-image: url('img/reportBackground.png'); background-size : 90% 800px; background-repeat : repeat-y; background-position: center; -webkit-print-color-adjust: exact;">
									<div class="row mt-3 mb-3">
										<div class="col-md-10 pb-2">
											<h5 class="font-weight-bold">Tenant Name</h5>
											<h6 class="font-weight-normal">
												<?php
													$getTenantInfo = mysqli_query($conn, "SELECT tenantName FROM tenants WHERE tenantID = '". $selected_tenant_id ."' ") or die(mysqli_error($conn));
													if (mysqli_num_rows($getTenantInfo) > 0) {
														$tenant_info = mysqli_fetch_array($getTenantInfo);
														echo $tenant_info[0];
													}
												?>
											</h6>
										</div>
										<div class="col-md-2 pb-2">
											<h5 class="font-weight-bold">Print Date</h5>
											<h6 class="font-weight-normal"><?php echo date("d M Y H:i"); ?></h6>
										</div>
										
									</div>	
									<div class="table-responsive">
										<table class="table table-bordered table-sm">
											<thead>
												<tr class="text-center">
													<th>Tenant ID</th>
													<th>Tenant Name</th>
													<th>Mobile Phone</th>
													<th>Total Charged</th>
													<th>Total Paid</th>
													<th>Remaining</th>
												</tr>
											</thead>
											<tbody>
												<?php
													$tenant_total_charged = 0;
													$tenant_total_paid = 0;
													$tenant_total_remaining = 0;
													while ($rs = mysqli_fetch_array($reportQuery)) { ?>
														<tr>
															<td class="text-center"><?php echo substr($rs[0], 0, 10); ?></td>
															<td class="text-left"><?php echo $rs[1]; ?></td>
															<td class="text-center"><?php echo $rs[2]; ?></td>
															<td class="text-center"><?php echo "$ ". number_format($rs[3], 2); ?></td>
															<td class="text-center"><?php echo "$ ". number_format($rs[4], 2); ?></td>
															<td class="text-center text-danger"><?php echo "$ ". number_format($rs[5], 2); ?></td>
														</tr>
														<?php
														$tenant_total_charged += $rs[3];
														$tenant_total_paid += $rs[4];
														$tenant_total_remaining += $rs[5];
													}
												?>
												<tr class="bg-light font-weight-bold">
													<td class="text-right pr-3" colspan="3">Total</td>
													<td class="text-center"><?php echo "$". number_format($tenant_total_charged, 2); ?></td>
													<td class="text-center"><?php echo "$". number_format($tenant_total_paid, 2); ?></td>
													<td class="text-center text-danger"><?php echo "$". number_format($tenant_total_remaining, 2); ?></td>

												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							<div class="row" style="margin-top: 40px;">
								<div class="col-md-8">&nbsp;</div>
								<div class="col-md-4">
									<h5 class="text-black text-center" style="font-weight: bold; padding: 10px;"><?php echo $_SESSION['fullName']; ?><br /><b style="font-weight: normal">(Signature)</b></h5>
									<h5 style="font-weight: normal; padding-left: 10px;"><hr style="border-top: 1px solid black;"></h5>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div><?php
		} else {
			?><div class="tile mt-3">
				<div class="tile-body">
					<br />
					<div class="row">
						<div class="col-md-12" style="margin: 0px;">
							<h6 class="text-center text-danger font-weight-normal"">Data Not Found</h6>
						</div>
					</div>
					<br />
				</div>
			</div><?php
		}
	}
	
	// ================ End of Special System Reports =========================

	


	// =============== where action passed ===========
	if ($action) {
		$action($conn);
	}

?>