<?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.workingAreaID, 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[12];
				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[9];
							$_SESSION["tempUserEmail"] = $userDetails[10];
							//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["workingAreaID"] = $userDetails[8];
							$_SESSION["userPhone"] = $userDetails[9];
							$_SESSION["userEmail"] = $userDetails[10];
							$_SESSION["userPhoto"] = $userDetails[11];
							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;
	}

	// Waiter Login Process Starts Here
	function waiter_login_process($conn) {
		global $ereyFure;
		global $errorList;
		$data = array();
		extract($_POST);
		$waiter_username = "-";
		$entered_user_password = mysqli_real_escape_string($conn, $entered_waiter_passcode);
		$getDecryptedPasswords = mysqli_query($conn, "SELECT system_users.Username, system_users.Passcode
		FROM employees
		JOIN system_users ON employees.employeeID = system_users.employeeID
		WHERE employees.employeePosition = 'PS0008'");
		if ($getDecryptedPasswords) {
			if (mysqli_num_rows($getDecryptedPasswords) > 0) {
				while ($waiters_row = mysqli_fetch_array($getDecryptedPasswords)) {
					$user_stored_enc_pass = $waiters_row[1];
					$stored_dec_password = kuceliAsalka($user_stored_enc_pass, $ereyFure);
					if ($entered_user_password === $stored_dec_password) {
						$waiter_username = $waiters_row[0];
						break;
					}
				}
			}
			if ($waiter_username == "-") {
				$errorList[] = "Password is incorrect, try again!";
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			} else {
				$getWaiterUserDetails = mysqli_query($conn, "SELECT system_users.userID, system_users.Username, system_users.Passcode, system_users.twoStepVerification, employees.employeeID, employees.employeeName, employees.employeePOB, employees.employeeDOB, departments.departmentName, employees.employeePosition, employee_positions.positionName, employees.workingAreaID, working_areas.workingAreaName, employees.employeeAddress, 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		
				JOIN working_areas ON employees.workingAreaID = working_areas.workingAreaID		
				WHERE system_users.Username = '" . mysqli_real_escape_string($conn, $waiters_row[0]) . "'");
				if ($getWaiterUserDetails) {
					if (mysqli_num_rows($getWaiterUserDetails) > 0) {
						$userDetails = mysqli_fetch_array($getWaiterUserDetails);
						$emp_Status = $userDetails[17];
						if ($emp_Status == "0") {
							$errorList[] = "Sorry, this user has been blocked the administrator";
							$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["waiterIdd"] = $userDetails[4];
							$_SESSION["waiterFullName"] = $userDetails[5];
							$_SESSION["waiterPlaceOfBirth"] = $userDetails[6];
							$_SESSION["waiterDateOfBirth"] = $userDetails[7];
							$_SESSION["departmentName"] = $userDetails[8];
							$_SESSION["userTypeID"] = $userDetails[9];
							$_SESSION["userType"] = $userDetails[10];
							$_SESSION["workingAreaID"] = $userDetails[11];
							$_SESSION["workingAreaName"] = $userDetails[12];
							$_SESSION["waiterAddress"] = $userDetails[13];
							$_SESSION["waiterPhone"] = $userDetails[14];
							$_SESSION["waiterEmail"] = $userDetails[15];
							$_SESSION["waiterPhoto"] = $userDetails[16];
							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));
							$data = json_encode(array('Status' => true, 'Message' => 'my-pos'));
						}
					}
				} 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 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["workingAreaID"] = $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 {
            		    $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;
					} else if ($val == "currentUserIdd") {
						$getVal .= "'". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."'".",";
					} else if ($val == "currentDateTime") {
						$getVal .= "'". mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) ."'".",";
					} else {
						$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) {
						$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 if ($val == "currentUserIdd") {
							$getVal .= "'". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."'".",";
						} else if ($val == "currentDateTime") {
							$getVal .= "'". mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) ."'".",";
						} else {
							$getVal .= "'". mysqli_real_escape_string($conn, $val) ."'".",";
						}
					} 
				} else {
					foreach ($getValues as $val) {
						if ($val == "") {
							continue;
						} else if ($val == "currentUserIdd") {
							$getVal .= "'". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."'".",";
						} else if ($val == "currentDateTime") {
							$getVal .= "'". mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) ."'".",";
						} else {
							$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 == "customers") {
							$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 {
						$errorList[] = mysqli_error($conn);
						$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;
					} else if ($getValues[$i] == "currentUserIdd") {
						$colVal .= " " . $getColumns[$i] . " = " . "'" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "',";
					} else if ($getValues[$i]  == "currentDateTime") {
						$colVal .= " " . $getColumns[$i] . " = " . "'" . mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) . "',";
					} else {
						$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;
					} else if ($getValues[$i] == "currentUserIdd") {
						$colVal .= " " . $getColumns[$i] . " = " . "'" . mysqli_real_escape_string($conn, $_SESSION['userIdd']) . "',";
					} else if ($getValues[$i]  == "currentDateTime") {
						$colVal .= " " . $getColumns[$i] . " = " . "'" . mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) . "',";
					} else {
						$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 {
						$errorList[] = mysqli_error($conn);
						$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_admin_accounts($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 Details ==========================
	function fill_deposit_accounts($conn) {
		$accounts_data = array();
		$data = array();

		if ($_SESSION['userTypeID'] == 'PS0001') {
			$getAccountNumbers = "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";
		} else {
			$getAccountNumbers = "SELECT account_numbers.accountNoID, payment_gateways.gatewayType, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber FROM account_association JOIN account_numbers ON account_association.accountNoID = account_numbers.accountNoID JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID WHERE account_association.transactionType = 'Deposit' AND account_association.userID = '". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."' ORDER BY payment_gateways.gatewayName ASC";
		}
		$bankAccounts = mysqli_query($conn, $getAccountNumbers) or die(mysqli_error($conn));
		if ($bankAccounts) {
			if (mysqli_num_rows($bankAccounts) > 0) {
				while ($row = mysqli_fetch_array($bankAccounts)) {
					$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;
	}

	function fill_withdrawal_accounts($conn) {
		$accounts_data = array();
		$data = array();

		if ($_SESSION['userTypeID'] == 'PS0001') {
			$getAccountNumbers = "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";
		} else {
			$getAccountNumbers = "SELECT account_numbers.accountNoID, payment_gateways.gatewayType, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber FROM account_association JOIN account_numbers ON account_association.accountNoID = account_numbers.accountNoID JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID WHERE account_association.transactionType = 'Withdrawal' AND account_association.userID = '". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."' ORDER BY payment_gateways.gatewayName ASC";
		}
		$bankAccounts = mysqli_query($conn, $getAccountNumbers) or die(mysqli_error($conn));
		if ($bankAccounts) {
			if (mysqli_num_rows($bankAccounts) > 0) {
				while ($row = mysqli_fetch_array($bankAccounts)) {
					$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;
	}

	// Fetch 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;
	}

	// Fetch User Associated Accounts
	function fetch_user_associated_account_numbers($conn) {
		global $ereyFure;
		extract($_POST);
		$dn = kuceliAsalka($dn, $ereyFure); ?>
		<div class="row">
			<div class="col-md-12">
				<?php
					// First get the current accounts of the selected user
					$user_associated_accounts_list = array();
					$getUserAssociatedAccounts = mysqli_query($conn, "SELECT accountNoID, transactionType, userID FROM account_association WHERE userID = '". mysqli_real_escape_string($conn, $selected_user_id) ."' GROUP BY accountNoID") or die(mysqli_error($conn));
					if ($getUserAssociatedAccounts) {
						if (mysqli_num_rows($getUserAssociatedAccounts) > 0) {
							while ($user_assoc_accounts_rs = mysqli_fetch_array($getUserAssociatedAccounts)) {
								$user_associated_accounts_list[] = $user_assoc_accounts_rs[0];
							}
						}
					}
					// If the current user is super admin, owner or administrator then fetch all the account numbers
					if ($_SESSION['userTypeID'] == 'PS0001') {
						$getAccountNumbers = mysqli_query($conn, "SELECT account_numbers.accountNoID, 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
						ORDER BY LENGTH(account_numbers.accountNoID), account_numbers.accountNoID ASC");
						if ($getAccountNumbers) {
							if (mysqli_num_rows($getAccountNumbers) > 0) {
								?><div class="tile mt-3">
									<div class="row pt-2">
										<div class="col-md-12">
											<h4 class="text-uppercase">Associated Account Numbers</h4>
										</div>
									</div>
								</div>
								<div class="row"><?php
								while ($account_numbers_rs = mysqli_fetch_array($getAccountNumbers)) {
									if ($account_numbers_rs[1] == 1) $account_details = "<img class='img-fluid mb-2' src='". $account_numbers_rs[2] ."' width='30px'/> &nbsp; ". $account_numbers_rs[3] ." (". $account_numbers_rs[5] .")";
									else if ($account_numbers_rs[1] == 2) $account_details = "<img class='img-fluid mb-2' src='". $account_numbers_rs[2] ."' width='30px' /> &nbsp; ". $account_numbers_rs[3] ." - <span class='text-danger'>". $account_numbers_rs[4] ."</span>(". $account_numbers_rs[5] .")";
									else if ($account_numbers_rs[1] == 3) $account_details = "<img class='img-fluid mb-2' src='". $account_numbers_rs[2] ."' width='30px' /> &nbsp; ". $account_numbers_rs[4] ."</span> (". $account_numbers_rs[5] .")";
									?>
									<div class="col-md-6">
										<div class="tile mt-4">
											<div class="row mt-2 pb-4">
												<div class="col-md-12 mb-2"><?php 
													if (in_array($account_numbers_rs[0], $user_associated_accounts_list)) {
														?><h4 class="font-weight-bold"><input type="checkbox" class="form-control mt-2 ml-1 mr-2 mb-1 cbxAssociateDissociateFullAcountNumber" style="height: 27px; width: 27px; display: inline; cursor: pointer;" id="cbxAssociateDissociateFullForAcount<?php echo $account_numbers_rs[0]; ?>" data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked /><?php echo $account_details. "</h4>"; ?><?php
													} else {
														?><h4 class="font-weight-bold"><input type="checkbox" class="form-control mt-2 ml-1 mr-2 mb-1 cbxAssociateDissociateFullAcountNumber" style="height: 27px; width: 27px; display: inline; cursor: pointer;" id="cbxAssociateDissociateFullForAcount<?php echo $account_numbers_rs[0]; ?>" data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>"><?php echo $account_details. "</h4>"; ?><?php
													} 
												?></div>
											</div>
											<div class="row">
												<div class="col-md-3">
													<h4>Deposit</h4>
													<div class="toggle-switch">
														<label>
															<?php
																$getDepositTransaction = mysqli_query($conn, "SELECT transactionType FROM account_association WHERE accountNoID = '$account_numbers_rs[0]' AND transactionType = 'Deposit' AND userID = '$selected_user_id'") or die(mysqli_error($conn));
																if (mysqli_num_rows($getDepositTransaction) > 0) {
																	?><input type="checkbox" class="accountDepositTransaction" id="cbxDepositFor<?php echo $account_numbers_rs[0]; ?>" data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked hidden><span><small></small></span></label><?php
																} else {
																	?><input type="checkbox" class="accountDepositTransaction" id="cbxDepositFor<?php echo $account_numbers_rs[0]; ?>"  data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" hidden><span><small></small></span></label><?php
																}
															?>
														</label>
													</div>
												</div>
												<div class="col-md-3">
													<h4>Withdrawal</h4>
													<div class="toggle-switch">
														<label>
															<?php
																$getWithdrawalTransaction = mysqli_query($conn, "SELECT transactionType FROM account_association WHERE accountNoID = '$account_numbers_rs[0]' AND transactionType = 'Withdrawal' AND userID = '$selected_user_id'") or die(mysqli_error($conn));
																if (mysqli_num_rows($getWithdrawalTransaction) > 0) {
																	?><input type="checkbox" class="accountWithdrawalTransaction" id="cbxWithdrawalFor<?php echo $account_numbers_rs[0]; ?>" data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked hidden><span><small></small></span></label><?php
																} else {
																	?><input type="checkbox" class="accountWithdrawalTransaction" id="cbxWithdrawalFor<?php echo $account_numbers_rs[0]; ?>" data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" hidden><span><small></small></span></label><?php
																}
															?>
														</label>
													</div>													
												</div>
											</div>
										</div>
									</div><?php
								}
								?></div><?php
							} else {
								?><div class="row">
									<div class="col-md-12">
										<div class="tile mt-2"><h6 class='text-danger text-center'>Accounts Not Found</h6>
									</div>
								</div><?php
							}
						} else {
							?><div class="row">
								<div class="col-md-12">
									<div class="tile mt-2"><h6 class='text-danger text-center'><?php echo mysqli_error($conn); ?></h6>
								</div>
							</div><?php
						}
							
					} else {

						$getCurrentUserAccountNumbers = mysqli_query($conn, "SELECT account_numbers.accountNoID, payment_gateways.gatewayType, payment_gateways.gatewayLogo, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber
						FROM account_association
						JOIN account_numbers ON account_association.accountNoID = account_numbers.accountNoID
						JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID
						WHERE account_association.userID = '". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."'
						GROUP BY account_association.accountNoID
						ORDER BY LENGTH(account_association.accountNoID), account_association.accountNoID ASC");
						if ($getCurrentUserAccountNumbers) {
							if (mysqli_num_rows($getCurrentUserAccountNumbers) > 0) {
								?>
								<div class="tile mt-3">
									<div class="row pt-2">
										<div class="col-md-12">
											<h4 class="text-uppercase">Associated Account Numbers</h4>
										</div>
									</div>
								</div>
								<div class="row"><?php
								while ($account_numbers_rs = mysqli_fetch_array($getCurrentUserAccountNumbers)) { 
									if ($account_numbers_rs[1] == 1) $account_details = "<img class='img-fluid mb-2' src='". $account_numbers_rs[2] ."' width='30px'/> &nbsp; ". $account_numbers_rs[3] ." (". $account_numbers_rs[5] .")";
									else if ($account_numbers_rs[1] == 2) $account_details = "<img class='img-fluid mb-2' src='". $account_numbers_rs[2] ."' width='30px' /> &nbsp; ". $account_numbers_rs[3] ." - <span class='text-danger'>". $account_numbers_rs[4] ."</span>(". $account_numbers_rs[5] .")";
									else if ($account_numbers_rs[1] == 3) $account_details = "<img class='img-fluid mb-2' src='". $account_numbers_rs[2] ."' width='30px' /> &nbsp; ". $account_numbers_rs[4] ."</span> (". $account_numbers_rs[5] .")";
									?>
									<div class="col-md-6">
										<div class="tile mt-4">
											<div class="row mt-2 pb-4">
												<div class="col-md-12 mb-2"><?php 
													if (in_array($account_numbers_rs[0], $user_associated_accounts_list)) {
														?><h4 class="font-weight-bold"><?php echo $account_details. "</h4>"; ?><?php
													} else {
														?><h4 class="font-weight-bold"><?php echo $account_details. "</h4>"; ?><?php
													}
												?></div>
											</div>
											<div class="row">
												<?php
													$getDepositTransactionStatus = mysqli_query($conn, "SELECT transactionType FROM account_association WHERE accountNoID = '$account_numbers_rs[0]' AND transactionType = 'Deposit' AND userID = '". $_SESSION['userIdd'] ."'") or die(mysqli_error($conn));
													if (mysqli_num_rows($getDepositTransactionStatus) > 0) {
														?><div class="col-md-3">
															<h4>Deposit</h4>
															<div class="toggle-switch">
																<label>
																	<?php
																		$getDepositTransaction = mysqli_query($conn, "SELECT transactionType FROM account_association WHERE accountNoID = '$account_numbers_rs[0]' AND transactionType = 'Deposit' AND userID = '$selected_user_id'") or die(mysqli_error($conn));
																		if (mysqli_num_rows($getDepositTransaction) > 0) {
																			?><input type="checkbox" class="accountDepositTransaction" id="cbxDepositFor<?php echo $account_numbers_rs[0]; ?>" data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked hidden><span><small></small></span></label><?php
																		} else {
																			?><input type="checkbox" class="accountDepositTransaction" id="cbxDepositFor<?php echo $account_numbers_rs[0]; ?>"  data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" hidden><span><small></small></span></label><?php
																		}
																	?>
																</label>
															</div>
														</div><?php
													}
												?>
												<?php
													$getWithdrawalTransactionStatus = mysqli_query($conn, "SELECT transactionType FROM account_association WHERE accountNoID = '$account_numbers_rs[0]' AND transactionType = 'Withdrawal' AND userID = '". $_SESSION['userIdd'] ."'") or die(mysqli_error($conn));
													if (mysqli_num_rows($getWithdrawalTransactionStatus) > 0) {
														?><div class="col-md-3">
															<h4>Withdrawal</h4>
															<div class="toggle-switch">
																<label>
																	<?php
																		$getWithdrawalTransaction = mysqli_query($conn, "SELECT transactionType FROM account_association WHERE accountNoID = '$account_numbers_rs[0]' AND transactionType = 'Withdrawal' AND userID = '$selected_user_id'") or die(mysqli_error($conn));
																		if (mysqli_num_rows($getWithdrawalTransaction) > 0) {
																			?><input type="checkbox" class="accountWithdrawalTransaction" id="cbxWithdrawalFor<?php echo $account_numbers_rs[0]; ?>" data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" checked hidden><span><small></small></span></label><?php
																		} else {
																			?><input type="checkbox" class="accountWithdrawalTransaction" id="cbxWithdrawalFor<?php echo $account_numbers_rs[0]; ?>"  data-id="<?php echo $account_numbers_rs[0]; ?>" data-src="<?php echo $selected_user_id; ?>" hidden><span><small></small></span></label><?php
																		}
																	?>
																</label>
															</div>
														</div><?php
													}
												?>
											</div>
										</div>
									</div><?php
						
								}
								?></div><?php
							} else {
								echo "<center><h6 class='text-danger text-center'>Accounts Not Found</h6></center>";
							}
						} else {
							echo mysqli_error($conn);
						}
					}
				?>
			</div>
		</div><?php
	}

	// Associate User Account Number Fully Both Deposit and Withdrawal
	function associate_user_with_account_number_fully($conn) {
		$data = array();
		extract($_POST);
		$associateDepositAccountNo = mysqli_query($conn, "INSERT INTO account_association(accountNoID, transactionType, userID, registeredBy, registerDate) VALUES ('" . mysqli_real_escape_string($conn, $selected_account_id) . "', 'Deposit', '" . mysqli_real_escape_string($conn, $selected_user_id) . "', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')");
		if ($associateDepositAccountNo) {
			$associateWithdrawalAccountNo = mysqli_query($conn, "INSERT INTO account_association(accountNoID, transactionType, userID, registeredBy, registerDate) VALUES ('" . mysqli_real_escape_string($conn, $selected_account_id) . "', 'Withdrawal', '" . mysqli_real_escape_string($conn, $selected_user_id) . "', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')");
			if ($associateWithdrawalAccountNo) {
				$data = json_encode(array('Status' => true, 'Message' => 'Account number has been fully <b>associated</b> successfully'));
			} else {
				$errorMsg = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
			}		
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Dissociate User Account Number Fully Both Deposit and Withdrawal
	function disssociate_user_with_account_number_fully($conn) {
		$data = array();
		extract($_POST);
		$disssociateDepositAccountNo = mysqli_query($conn, "DELETE FROM account_association WHERE accountNoID = '" . mysqli_real_escape_string($conn, $selected_account_id) . "' AND transactionType = 'Deposit' AND userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'");
		if ($disssociateDepositAccountNo) {
			$disssociateWithdrawalAccountNo = mysqli_query($conn, "DELETE FROM account_association WHERE accountNoID = '" . mysqli_real_escape_string($conn, $selected_account_id) . "' AND transactionType = 'Withdrawal' AND userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'");
			if ($disssociateWithdrawalAccountNo) {
				$data = json_encode(array('Status' => true, 'Message' => 'Account number has been fully <b>dissociated</b> successfully'));
			} else {
				$errorMsg = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
			}		
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Associate User Account Number Only to Deposit
	function associate_user_with_deposit_account_number_only($conn) {
		$data = array();
		extract($_POST);
		$associateDepositAccountNo = mysqli_query($conn, "INSERT INTO account_association(accountNoID, transactionType, userID, registeredBy, registerDate) VALUES ('" . mysqli_real_escape_string($conn, $selected_account_id) . "', 'Deposit', '" . mysqli_real_escape_string($conn, $selected_user_id) . "', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')");
		if ($associateDepositAccountNo) {
			$data = json_encode(array('Status' => true, 'Message' => 'Account number for deposit has been <b>associated</b> successfully'));		
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Dissociate User Account Number Only to Deposit
	function dissociate_user_with_deposit_account_number_only($conn) {
		$data = array();
		extract($_POST);
		$disssociateDepositAccountNo = mysqli_query($conn, "DELETE FROM account_association WHERE accountNoID = '" . mysqli_real_escape_string($conn, $selected_account_id) . "' AND transactionType = 'Deposit' AND userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'");
		if ($disssociateDepositAccountNo) {
			$data = json_encode(array('Status' => true, 'Message' => 'Account number for deposit has been <b>dissociated</b> successfully'));		
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}


	// Associate User Account Number Only to Withdraw
	function associate_user_with_withdrawal_account_number_only($conn) {
		$data = array();
		extract($_POST);
		$associateWithdrawalAccountNo = mysqli_query($conn, "INSERT INTO account_association(accountNoID, transactionType, userID, registeredBy, registerDate) VALUES ('" . mysqli_real_escape_string($conn, $selected_account_id) . "', 'Withdrawal', '" . mysqli_real_escape_string($conn, $selected_user_id) . "', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')");
		if ($associateWithdrawalAccountNo) {
			$data = json_encode(array('Status' => true, 'Message' => 'Account number for withdrawal has been <b>associated</b> successfully'));		
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Dissociate User Account Number Only Withdraw
	function dissociate_user_with_withdrawal_account_number_only($conn) {
		$data = array();
		extract($_POST);
		$disssociateWithdrawalAccountNo = mysqli_query($conn, "DELETE FROM account_association WHERE accountNoID = '" . mysqli_real_escape_string($conn, $selected_account_id) . "' AND transactionType = 'Withdrawal' AND userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'");
		if ($disssociateWithdrawalAccountNo) {
			$data = json_encode(array('Status' => true, 'Message' => 'Account number for withdrawal has been <b>dissociated</b> successfully'));		
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		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 ===================================================
	
	// First Fetch User Information
	function fetch_user_information_to_change_passcode($conn) {
		$data = array();
		$user_data = array();
		extract($_POST);
		$selected_user_id = mysqli_real_escape_string($conn, $selected_user_id);

// 		echo "SELECT system_users.userID, employees.employeeName, employees.employeeMobileNo, system_users.Username FROM system_users JOIN employees ON system_users.employeeID = employees.employeeID WHERE system_users.userID = '" . $selected_user_id . "'";
		$readInformation = 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 = '" . $selected_user_id . "'") or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				$data_rs = mysqli_fetch_array($readInformation);
				$user_data[] = $data_rs;
				$data = json_encode(array('Status' => true, 'Message' => $user_data));
			}
		} else {
			$erroMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $erroMsg));
		}
		echo $data;
	}

	
	
	function change_password($conn) {
		global $ereyFure;
		global $errorList;

		$data = array();
		extract($_POST);
		
		if (mysqli_real_escape_string($conn, $changing_user_type) == "administrator") {
	    	$changePasscode = mysqli_query($conn, "UPDATE system_users SET Username = '" . mysqli_real_escape_string($conn, $selected_user_name) . "', Passcode = '" . mysqli_real_escape_string($conn, bedelXogta($new_passcode_admin, $ereyFure)) . "' WHERE userID = '" . mysqli_real_escape_string($conn, $selected_user_id) . "'");
			if ($changePasscode) {
				$data = json_encode(array('Status' => true, 'Message' => 'Passcode has been changed successfully'));
			} else {
				$errorMsg = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
			}
		} else if (mysqli_real_escape_string($conn, $changing_user_type) == "user_its_self") {

    		if ($new_passcode_user != $confirm_passcode_user) {
    			$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 = $old_passcode_user;
    					$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 Passcode = '" . mysqli_real_escape_string($conn, bedelXogta($new_passcode_user, $ereyFure)) . "' WHERE userID = '" . $_SESSION['userIdd'] . "'");
    						if ($changePass) {
    							$data = json_encode(array('Status' => true, 'Message' => 'Passcode has been changed successfully'));
    						} else {
    							$errorMsg = mysqli_error($conn);
    							$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
    						}
    					} else {
    						$errorList[] = "Old passcode is wrong, please check again";
    						$data = json_encode(array('Status' => false, 'Message' => $errorList));
    					}
    				} else {
    					$errorList[] = "Sorry, <b>" . $user_name . "</b> does not exist in the system_users list";
    					$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 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 employeeName = '" . $fullN . "', employeePhoto = '" . $alreadyExistPath . "' WHERE employeeID IN (SELECT employeeID FROM system_users WHERE userID = '" . $_SESSION['userIdd'] . "')");
			if ($updateProfile) {
				$_SESSION['fullName'] = $fullN;
				$_SESSION['userPhoto'] = $alreadyExistPath;
				$data = json_encode(array('Status' => true, 'Message' => '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 employeeName = '" . $fullN . "', employeePhoto = '" . mysqli_real_escape_string($conn, $path) . "' WHERE employeeID IN (SELECT employeeID FROM system_users WHERE userID = '" . $_SESSION['userIdd'] . "')");
					if ($updateProfile) {
						$_SESSION['fullName'] = $fullN;
						$_SESSION['userPhoto'] = $path;
						$data = json_encode(array('Status' => true, 'Message' => '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 Search Products in Products Page ================================
		
	function search_restaurant_product_live_products_page($conn) {
		extract($_POST);
		$searched_product_name = mysqli_real_escape_string($conn, $searched_product_name);

		$getRestaurantCategories = mysqli_query($conn, "SELECT restaurant_products.categoryID, restaurant_categories.categoryName, working_areas.workingAreaName, restaurant_categories.categoryPhoto
		FROM restaurant_products
		JOIN restaurant_categories ON restaurant_products.categoryID = restaurant_categories.categoryID
		JOIN working_areas ON restaurant_categories.workingAreaID = working_areas.workingAreaID
		WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%'
		GROUP BY restaurant_categories.categoryID
		ORDER BY restaurant_categories.categoryName ASC") or die(mysqli_error($conn));
		if ($getRestaurantCategories) {
			if (mysqli_num_rows($getRestaurantCategories) > 0) {
				while ($rest_categories_rs = mysqli_fetch_array($getRestaurantCategories)) { ?>
					<div class="row mt-2 mx-auto">
						<div class="col-md-12 bg-primary pt-2 rounded-top">
							<h4 class="text-white"><img class="img-fluid rounded" src="<?php echo $rest_categories_rs[3]; ?>" width="25px" height="25px" /> <?php echo $rest_categories_rs[1]; ?> (<?php echo $rest_categories_rs[2]; ?>)</h4>
						</div>
						<div class="col-md-12 pt-2 rounded">
							<div class="row pt-2">
								<?php
									$getCategoryProducts = mysqli_query($conn, "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, working_areas.workingAreaName, restaurant_products.productStatus, restaurant_products.productPhoto
									FROM restaurant_products
									JOIN working_areas ON restaurant_products.workingAreaID = working_areas.workingAreaID
									WHERE categoryID = '". $rest_categories_rs[0] ."' AND productName LIKE '%". $searched_product_name ."%'
									ORDER BY restaurant_products.productName ASC") or die(mysqli_error($conn));
									if ($getCategoryProducts) {
										if (mysqli_num_rows($getCategoryProducts) > 0) {
											while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
												<div class="col-md-4 pb-3 rounded-lg">
													<div class="bs-component">
														<div class="card">
															<img class="rounded-top" style="height: 200px; width: 100%; display: block;" src="<?php echo $category_products_rs[5]; ?>" alt="Card image">
															<div class="card-body">
																<div class="row">
																	<div class="col-md-12"><h5 class="text-primary text-center"><?php echo $category_products_rs[1]; ?></h5></div>
																</div>
																<div class="row">
																	<div class="col-md-12"><h6 class="text-success text-center"><?php echo "$". number_format($category_products_rs[2], 2); ?></h6></div>
																</div>
																<div class="row pt-2">
																	<div class="col-md-4">
																		<span class="badge badge-success p-2"><i class="fa fa-star text-warning"></i> <?php echo $category_products_rs[3]; ?></span>
																	</div>
																	<div class="col-md-8">
																		<?php
																			if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003') || ($role_rs[4] == '1' && $role_rs[5] == '1')) {
																				?><div class="btn-group btn-group-sm pull-right" role="group" aria-label="Basic example">
																					<button type="button" class="btn btn-primary">
																						<span class="text-white btnUpdateRestaurantProduct" id="<?php echo "Update". $category_products_rs[0]; ?>" data-id="<?php echo $category_products_rs[0]; ?>" data-toggle="modal" data-target="#updateRestaurantProductModal"><i class="fa fa-pencil"></i>Edit</span>
																					</button>
																					<button type="button" class="btn btn-danger">
																						<span class="text-white btnDeleteRestaurantProduct" id="<?php echo "Delete". $category_products_rs[0]; ?>" data-id="<?php echo $category_products_rs[0]; ?>"><i class="fa fa-trash"></i>Delete</span>
																					</button>
																				</div><?php
																			} else if ($role_rs[4] == '1') {
																				?><div class="btn-group btn-group-sm pull-right" role="group" aria-label="Basic example">
																					<button type="button" class="btn btn-primary">
																						<span class="text-white btnUpdateRestaurantProduct" id="<?php echo "Update". $category_products_rs[0]; ?>" data-id="<?php echo $category_products_rs[0]; ?>" data-toggle="modal" data-target="#updateRestaurantProductModal"><i class="fa fa-pencil"></i>Edit</span>
																					</button>
																				</div><?php
																			} else if ($role_rs[5] == '1') {
																				?><div class="btn-group btn-group-sm pull-right" role="group" aria-label="Basic example">
																					<button type="button" class="btn btn-danger">
																						<span class="text-white btnDeleteRestaurantProduct" id="<?php echo "Delete". $category_products_rs[0]; ?>" data-id="<?php echo $category_products_rs[0]; ?>"><i class="fa fa-trash"></i>Delete</span>
																					</button>
																				</div><?php
																			}
																		?>
																	</div>
																</div>
															</div>
														</div>
													</div>
												</div><?php
											}
										}
									}
								?>
							</div>
						</div>
					</div><?php
				}
			}
		}

	}

	// ================ End of Search Products in Products Page ==================================

	// ================ START OF ADMIN POS MODULE ================================================

	// Fetch Restaurant Products by Category in Admin POS Page
	function fetch_restaurant_products_by_category_admin_pos($conn) {
		extract($_POST);
		$category_id_admin_pos = mysqli_real_escape_string($conn, $category_id_admin_pos);
		
		if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) {
			$fetch_criteria = ($category_id_admin_pos == "All") ? "WHERE restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_admin_pos ."' AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		} else {
			$fetch_criteria = ($category_id_admin_pos == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_admin_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		}

		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductAdminPOSPageArea" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Products Not Found</h5>
					</div>
				</div><?php
			}
		}

	}
	
	// Search Restaurant Product Live in Admin POS Page
	function search_restaurant_product_live_admin_pos($conn) {
		extract($_POST);
		$searched_product_name = mysqli_real_escape_string($conn, $searched_product_name);
		$category_id_admin_pos = mysqli_real_escape_string($conn, $category_id_admin_pos);


		if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) {
			if ($searched_product_name == "") $fetch_criteria = ($category_id_admin_pos == "All") ? "WHERE restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_admin_pos ."' AND restaurant_products.productStatus = 1";
			else $fetch_criteria = ($category_id_admin_pos == "All") ? "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.categoryID = '". $category_id_admin_pos ."' AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		} else {
			if ($searched_product_name == "") $fetch_criteria = ($category_id_admin_pos == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_admin_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
			else $fetch_criteria = ($category_id_admin_pos == "All") ? "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.categoryID = '". $category_id_admin_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		}
		
		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductAdminPOSPageArea" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?></div>
				<div class="col-md-12 text-center">
					<h5 class="text-danger font-weight-normal">Product Not Found</h5>
				</div><?php
			}
		}

	}

	// Register Restaurant Order - Admin POS Page
	function register_restaurant_order_admin_pos_page($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$ordered_products_list = $checked_order_products_list;

		if (isset($ordered_products_list["productsStatus"]) && $ordered_products_list["productsStatus"] == "false") {
			$errorList[] = $ordered_products_list["productsMessage"];
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if ($order_subtotal_amount <= $order_discount_amount) {
			$errorList[] = "Check discount amount";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if (($selected_waiter_id == "-") && ($selected_order_type != 'OT0003')) {
			$errorList[] = "Select serving waiter";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if (($selected_order_type == "OT0003") && ($selected_customer_id == "RegisterNewCustomer" || $selected_customer_id == "CU0001")) {
			$errorList[] = "Please select customer";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {

			//Generate New ID for the current inserted order ....
			$getMaxRestaurantOrderID = mysqli_query($conn, "SELECT MAX(rowNo) FROM restaurant_orders") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxRestaurantOrderID) > 0) {
				$maxRestaurantOrderID = mysqli_fetch_array($getMaxRestaurantOrderID);
				$curRestaurantOrderID = $maxRestaurantOrderID[0] + 1;
				$generatedRestaurantOrderID = "ORD" . sprintf("%04d", $curRestaurantOrderID);
			} else {
				$curRestaurantOrderID = 1;
				$generatedRestaurantOrderID = "ORD" . sprintf("%04d", $curRestaurantOrderID);
			}
			$register_restaurant_order_now = mysqli_query($conn, "INSERT INTO restaurant_orders(orderID, customerID, orderTypeID, workingAreaID, kitchenNote, orderSubtotal, orderDiscount, orderVAT, totalAmount, tableID, servedBy, orderStatus, deliveredBy, deliveryAddress, registeredBy, registerDate, updatedBy, updateDate) VALUES ('". mysqli_real_escape_string($conn, $generatedRestaurantOrderID) ."','". mysqli_real_escape_string($conn, $selected_customer_id) ."', '". mysqli_real_escape_string($conn, $selected_order_type) ."', '". $_SESSION['workingAreaID'] ."', '". mysqli_real_escape_string($conn, $kitchen_note_descript) ."', '". mysqli_real_escape_string($conn, $order_subtotal_amount) ."', '". mysqli_real_escape_string($conn, $order_discount_amount) ."', '". mysqli_real_escape_string($conn, $order_true_vat_amount) ."', '". mysqli_real_escape_string($conn, $order_total_amount) ."', '". mysqli_real_escape_string($conn, $selected_table_id) ."', '". mysqli_real_escape_string($conn, $selected_waiter_id) ."','1', '". mysqli_real_escape_string($conn, $selected_deliveryman_id) ."', '". mysqli_real_escape_string($conn, $selected_delivery_address) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."', '-', '-')");
			if ($register_restaurant_order_now) {
				foreach ($ordered_products_list["productsMessage"] as $product) {
					mysqli_query($conn, "INSERT INTO order_products_list (productID, Quantity, productPrice, totalPrice, orderID, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, $product[1]) ."', '". mysqli_real_escape_string($conn, $product[2]) ."', '". mysqli_real_escape_string($conn, $product[3]) ."', '". mysqli_real_escape_string($conn, $generatedRestaurantOrderID) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
					mysqli_query($conn, "INSERT INTO kitchen_orders_list (productID, Quantity, orderID, orderLevel, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, $product[1]) ."', '". mysqli_real_escape_string($conn, $generatedRestaurantOrderID) ."', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
				}
				$data = json_encode(array('Status' => true, 'Message' => $generatedRestaurantOrderID));
			} else {
				$errorList[] = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		}

		echo $data;
	}
	
	// ================ END OF ADMIN POS MODULE ==================================================

	// ================ START OF REMOVE ORDER LIST ITEM MODULE ===================================

	// Remove Order List Item - Edit POS Page
	function remove_order_list_item($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$update_restaurant_order_first = mysqli_query($conn, "UPDATE restaurant_orders SET orderSubtotal = '". mysqli_real_escape_string($conn, $order_subtotal_edit_order) ."', totalAmount = '". mysqli_real_escape_string($conn, $order_total_edit_order) ."' WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'");
		if ($update_restaurant_order_first) {
			$remove_order_item_now = mysqli_query($conn, "DELETE FROM order_products_list WHERE productID = '". mysqli_real_escape_string($conn, $selected_product_id) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'");
			if ($remove_order_item_now) {
				$remove_kitchen_order_item = mysqli_query($conn, "UPDATE kitchen_orders_list SET Quantity = -Quantity WHERE productID = '". mysqli_real_escape_string($conn, $selected_product_id) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'");
				if ($remove_kitchen_order_item) {
					$data = json_encode(array('Status' => true, 'Message' => 'Item has been removed'));
				} 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));
		}

		echo $data;
	}

	// ================ END OF REMOVE ORDER LIST ITEM MODULE =====================================
	
	// ================ START OF EDIT ORDER DMIN POS MODULE ======================================
	
	// Fetch Order Full Information to Edit
	function fetch_order_full_information_to_edit($conn) {
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$getOrderInformation = mysqli_query($conn, "SELECT restaurant_orders.orderID, order_types.orderTypeID, customers.customerID, restaurant_orders.deliveryAddress, restaurant_orders.servedBy, restaurant_orders.orderSubtotal, restaurant_orders.orderDiscount, restaurant_orders.orderVAT, restaurant_orders.totalAmount,  employees.employeePhoto, employees.employeeName, restaurant_orders.registerDate, ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount', restaurant_orders.kitchenNote
		FROM restaurant_orders
		JOIN customers ON restaurant_orders.customerID = customers.customerID
		JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID
		LEFT JOIN employees ON restaurant_orders.servedBy = employees.employeeID
		LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
		WHERE restaurant_orders.orderID = '$selected_order_id'") or die(mysqli_error($conn));
		if ($getOrderInformation) {
			if (mysqli_num_rows($getOrderInformation) > 0) {
				$order_info_rs = mysqli_fetch_array($getOrderInformation);
				?>
				
					<div class="row">

						<div class="col-md-8">

							<div class="row mb-4">
								<div class="col-md-12">
									<button class="btn btn-primary btn-lg mr-1 mb-2 shadow restaurant_categories_edit_order" id="all_category_name_admin_pos" category-id="All">
										<i class="fa fa-list-ul" style="font-size: 20px;"></i>
										<b>All</b>
									</button>
									<?php
										if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) {
											$restaurantCategories = "SELECT * FROM restaurant_categories ORDER BY categoryName ASC";
										} else {
											$restaurantCategories = "SELECT * FROM restaurant_categories WHERE workingAreaID = '". $_SESSION['workingAreaID'] ."' OR workingAreaID = 'WAR0001' ORDER BY categoryName ASC";
										}
										$getRestaurantCategories = mysqli_query($conn, $restaurantCategories) or die(mysqli_error($conn));
										while ($category_rs = mysqli_fetch_array($getRestaurantCategories)) { ?>
											<button class="btn btn-primary btn-lg mr-1 mb-2 shadow restaurant_categories_edit_order" id="<?php echo $category_rs[1]; ?>_category_name_admin_pos" category-id="<?php echo $category_rs[1]; ?>">
												<img class="img-fluid rounded" src="<?php echo $category_rs[9]; ?>" width="25px" height="25px" />
												<b><?php echo $category_rs[2]; ?></b>
											</button><?php
										}
									?>
								</div>
							</div>

							<div class="tile">
								<div class="tile-body">
									<div class="row">

										<div class="col-md-12">
											<div class="row mb-2 mt-1 pull-right">
												<div class="col-md-12">
													<div class="form-group has-search">
														<span class="fa fa-search form-control-feedback text-warning"></span>
														<input type="text" class="form-control rounded-pill" name="txtSearchRestaurantProductLiveEditOrderInformation" id="txtSearchRestaurantProductLiveEditOrderInformation" placeholder="Search product" autocomplete="off">
													</div>                                       
												</div>
											</div>
										</div>

										<div class="col-md-12" style="overflow: auto; height: 1200px;">

											<div class="row restaurantProductsEditOrderInformation">
												<?php


													if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) {
														$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products WHERE restaurant_products.productStatus = 1 ORDER BY restaurant_products.productName ASC";
													} else {
														$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products WHERE restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001' AND restaurant_products.productStatus = 1 ORDER BY restaurant_products.productName ASC";
													}

													$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
													if ($getCategoryProducts) {
														if (mysqli_num_rows($getCategoryProducts) > 0) {
															while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
																<div class="col-md-3">
																	<div class="bs-component mt-2 mb-3 singleProductEditOrderInformation" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
																		<div class="card rounded-lg">
																			<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
																			<div class="card-body">
																				<div class="row">
																					<div class="col-md-12">
																						<h5 class="text-primary text-center font-weight-normal">
																							<?php echo $category_products_rs[1]; ?>
																							<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
																						</h5>
																					</div>
																				</div>
																			</div>
																		</div>
																	</div>
																</div><?php
															}
														}
													}
												?>
											</div>
												
										</div>
									</div>
								</div>
							</div>
						</div>

						<div class="col-md-4">
							<div class="tile">
								<div class="tile-body">
									<div class="row">
										<div class="col-md-12 border-bottom border-primary mb-3">
											<h5 class="text-primary txtOrderIddEditOrderInformation" order-id-to-edit="<?php echo $order_info_rs[0]; ?>"><i class="fa fa-shopping-cart"></i> Edit Checkout - <?php echo $order_info_rs[0]; ?></h5>
										</div>
										<div class="col-md-12 pb-2">
											<?php
												if ($order_info_rs[1] == "OT0001") { ?>
													<button class="btn btn-success mr-1 btnOrderTypeEditOrderInformation" id="btnSeatInEditOrderInformation" order-type-edit-order="OT0001"><i class="fa fa-hotel"></i> Seat In</button>
													<button class="btn btn-outline-primary mr-1 btnTakeAwayEditOrderInformation" id="btnTakeAwayEditOrderInformation"><i class="fa fa-shopping-basket"></i> Take Away</button>
													<button class="btn btn-outline-dark mr-1 btnDeliveryEditOrderInformation" id="btnDeliveryEditOrderInformation"><i class="fa fa-motorcycle"></i> Delivery</button>
												<?php } else if ($order_info_rs[1] == "OT0002") { ?>
													<button class="btn btn-outline-success mr-1 btnSeatInEditOrderInformation" id="btnSeatInEditOrderInformation"><i class="fa fa-hotel"></i> Seat In</button>
													<button class="btn btn-primary mr-1 btnOrderTypeEditOrderInformation" id="btnTakeAwayEditOrderInformation" order-type-edit-order="OT0002"><i class="fa fa-shopping-basket"></i> Take Away</button>
													<button class="btn btn-outline-dark mr-1 btnDeliveryEditOrderInformation" id="btnDeliveryEditOrderInformation"><i class="fa fa-motorcycle"></i> Delivery</button>
												<?php } else if ($order_info_rs[1] == "OT0003") { ?>
													<button class="btn btn-outline-success mr-1 btnSeatInEditOrderInformation" id="btnSeatInEditOrderInformation"><i class="fa fa-hotel"></i> Seat In</button>
													<button class="btn btn-outline-primary mr-1 btnTakeAwayEditOrderInformation" id="btnTakeAwayEditOrderInformation"><i class="fa fa-shopping-basket"></i> Take Away</button>
													<button class="btn btn-dark mr-1 btnOrderTypeEditOrderInformation" id="btnDeliveryEditOrderInformation" order-type-edit-order="OT0003"><i class="fa fa-motorcycle"></i> Delivery</button>
												<?php }
											?>
										</div>
										<div class="form-group col-md-12 pt-3">
											<select id="cmbCustomerIddEditOrderInformation" name="cmbCustomerIddEditOrderInformation" class="form-control" style="width:100%" required />
											
											</select>
										</div>
										<script type="text/javascript">
								// 			$("#cmbCustomerIddEditOrderInformation").select2({ tags: true, dropdownParent: $("#editRestaurantOrderModal") })
											$.ajax({
												method: "POST", url: "api/main.php", data: { action: "fill_active_customers" }, dataType: "JSON",
												success: function (data) {
    												var Message = data.Message
    												var status = data.Status
    												var html = ""
    												html += `<option value="CU0001">Walking Customer - 000000000</option>`
    												if (status == true) {
    													Message.forEach(function (returned_data, i) {
    														html += `<option value="${returned_data["customerID"]}">${returned_data["customerName"]} - ${returned_data["customerMobile"]}</option>`
    													})
    													$("#cmbCustomerIddEditOrderInformation").html(html)
    													$("#cmbCustomerIddEditOrderInformation").select2().val(<?php echo json_encode($order_info_rs[2]); ?>).trigger("change")  
    													$("#cmbCustomerIddEditOrderInformation").select2({ tags: false, dropdownParent: $("#editRestaurantOrderModal") })
    
    												}
												}, error: function (data) { },
											})
										</script>
										<div class="form-group col-md-12">
											<input type="text" class="form-control" name="txtDeliveryAddressEditOrderInformation" id="txtDeliveryAddressEditOrderInformation" value="<?php echo $order_info_rs[3]; ?>"/>
										</div>
										<div class="form-group col-md-12 pt-1 pb-2 orderedProductsEditOrderInformation">
											<?php
												$getOrderProductsList = mysqli_query($conn, "SELECT restaurant_products.productID, restaurant_products.productName, order_products_list.Quantity, order_products_list.productPrice 'unitPrice', order_products_list.totalPrice 'totalPrice'
												FROM order_products_list
												JOIN restaurant_products ON order_products_list.productID = restaurant_products.productID
												JOIN restaurant_orders ON order_products_list.orderID = restaurant_orders.orderID
												WHERE order_products_list.orderID = '". $order_info_rs[0] ."'");
												if ($getOrderProductsList){
													if (mysqli_num_rows($getOrderProductsList) > 0) {
														while ($order_product_list = mysqli_fetch_array($getOrderProductsList)) {
															?>
																<div class="row align-items-center font-weight-bold pt-2 pb-2 border-bottom border-light" style="margin: 0px;" id="editOrderedProductId<?php echo $order_product_list[0]; ?>" ordered-product-id="<?php echo $order_product_list[0]; ?>" ordered-product-price="<?php echo $order_product_list[3]; ?>">
																	<div class="col-md-1 text-left"><i class="fa fa-trash fa-lg text-danger removeOrderedProductEditOrderInformation" style="cursor: pointer;"></i></div>
																	<div class="col-md-5"><?php echo $order_product_list[1]; ?></div>
																	<div class="col-md-4">
																		<button class="btn btn-outline-success rounded-pill btnIncrementProductQuantityEditOrderInformation"><span class="font-weight-bold">+</span></button><span class="pl-2 pr-2 orderedProductQuantityEditOrderInformation"><?php echo $order_product_list[2]; ?></span><button class="btn btn-outline-success rounded-pill btnDecrementProductQuantityEditOrderInformation"><span class="font-weight-bold">-</span></button>
																	</div>
																	<div class="col-md-2">$<span class="orderedProductPriceEditOrderInformation" ><?php echo number_format($order_product_list[4], 2); ?></div>
																</div>

															<?php
														}
													} else {
														?><p>Order List Not Found</p><?php
													}
												} else {
													?><p><?php echo mysqli_error($conn); ?></p><?php
												}
												
											?>
										</div>
										<div class="form-group col-md-12 pt-2 pb-1">
											<div class="row">
												<div class="col-md-12 pb-2 font-weight-bold">
													<p>Serving Waiter</p>
												</div>
											</div>
											<div class="row">
												<?php
													if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) $fetchCriteria = "WHERE employeePosition = 'PS0008' AND employeeStatus = '1'";
													else $fetchCriteria = "WHERE employeePosition = 'PS0008' AND workingAreaID = '". $_SESSION['workingAreaID'] ."' AND employeeStatus = '1'";
													$getWaiters = mysqli_query($conn, "SELECT employeeID, employeeName, employeePhoto
													FROM employees
													$fetchCriteria
													ORDER BY employeeName ASC") or die(mysqli_error($conn));
													if ($getWaiters) {
														if (mysqli_num_rows($getWaiters) > 0) {
															while ($waiters_rs = mysqli_fetch_array($getWaiters)) { 
																if ($waiters_rs[0] == $order_info_rs[4]) {
																	?><div class="col-md-3 mb-3 text-center">
																		<div class="custom-control custom-checkbox image-checkbox">
																			<input type="checkbox" checked class="custom-control-input cbxServingWaiterEditOrderInformation cbxSelectedWaiter" id="<?php echo $waiters_rs[0] ?>" serving-waiter-id="<?php echo $waiters_rs[0] ?>" current-selected-waiter-id="<?php echo $waiters_rs[0] ?>">
																			<label class="custom-control-label pb-2" for="<?php echo $waiters_rs[0] ?>">
																				<img src="<?php echo $waiters_rs[2] ?>" alt="#" class="img-fluid">
																			</label>
																			
																			<span><?php $get_name = explode(" ", $waiters_rs[1]); echo $get_name[0]; ?></span>
																		</div>
																	</div><?php
																} else {
																	?><div class="col-md-3 mb-3 text-center">
																		<div class="custom-control custom-checkbox image-checkbox">
																			<input type="checkbox" class="custom-control-input cbxServingWaiterEditOrderInformation" id="<?php echo $waiters_rs[0] ?>" serving-waiter-id="<?php echo $waiters_rs[0] ?>">
																			<label class="custom-control-label pb-2" for="<?php echo $waiters_rs[0] ?>">
																				<img src="<?php echo $waiters_rs[2] ?>" alt="#" class="img-fluid">
																			</label>
																			
																			<span><?php $get_name = explode(" ", $waiters_rs[1]); echo $get_name[0]; ?></span>
																		</div>
																	</div><?php
																}
																
															}
														} else {
															?><div class="row">
																<div class="col-md-12 ml-3">
																	<p>Waiters Not Found</p>
																</div>
															</div><?php
														}
													} else {
														?><div class="row">
															<div class="col-md-12 ml-3">
																<p><?php echo mysqli_error($conn); ?></p>
															</div>
														</div><?php
													}
												?>
											</div>
										</div>
										
										<div class="form-group col-sm-12">
        									<textarea class="form-control pt-2" style="resize: none;" rows="2" name="txtKitchenNoteEditOrderInformation" id="txtKitchenNoteEditOrderInformation" placeholder="Leave kitchen notes" required><?php echo $order_info_rs[12]; ?></textarea>
        								</div>

    									<div class="form-group col-md-12 pt-3 pb-1">
    										<div class="row align-items-center font-weight-bold pt-1 pb-1" style="margin: 0px;">
    											<div class="col-md-9"><h5 class="text-primary">Subtotal</h5></div>
    											<div class="col-md-3 text-center"><h5>$<span id="orderedProductsSubtotalEditOrderInformation"><?php echo number_format($order_info_rs[5], 2); ?></span><h5></div>
    										</div>
    										<div class="row align-items-center font-weight-bold pt-1 pb-1" style="margin: 0px;">
    											<div class="col-md-9"><h5 class="text-primary">Discount</h5></div>
    											<div class="col-md-3 text-center"><input type="number" class="form-control input-lg text-center font-weight-bold" name="txtOrderedProductsDiscountEditOrderInformation" id="txtOrderedProductsDiscountEditOrderInformation" value="<?php echo number_format($order_info_rs[6], 2); ?>" step="0.01" autocomplete="off" required /></div>
    										</div>
    										<div class="row align-items-center font-weight-bold pt-1 pb-1" style="margin: 0px;">
    											<div class="col-md-9"><h5 class="text-primary">VAT Tax (%5)</h5></div>
    											<div class="col-md-3 text-center"><input type="number" class="form-control input-lg text-center font-weight-bold" name="txtOrderedProductsVATEditOrderInformation" id="txtOrderedProductsVATEditOrderInformation" value="<?php echo number_format($order_info_rs[7], 2); ?>" step="0.01" autocomplete="off" required /></div>
    										</div>
    										<div class="row align-items-center font-weight-bold pt-2 pb-1" style="margin: 0px;">
    											<div class="col-md-9"><h5 class="text-primary">Total</h5></div>
    											<div class="col-md-3 text-center"><h5 class="text-success">$<span id="orderedProductsTotalEditOrderInformation"><?php echo number_format($order_info_rs[8], 2); ?></span><h5></div>
    										</div>
    									</div>

    									<div class="form-group col-md-12 pt-1 pb-1">
    										<div class="row pt-2 pull-right">
    											<div class="col-md-12">
    												<button class="btn btn-danger btn-lg pl-3 pr-3 mr-1" name="btnCancelOrderEditOrderInformation" id="btnCancelOrderEditOrderInformation" data-dismiss="modal" aria-label="Close"><i class="fa fa-times"></i>Cancel Editing</button>
    												<button class="btn btn-primary btn-lg pl-4 pr-4" name="btnEditAndPrintEditOrderInformation" id="btnEditAndPrintEditOrderInformation"><i class="fa fa-print"></i>Edit & Print</button>
    											</div>
    										</div>
    									</div>

    								</div>
    							</div>
    						</div>
						
    					</div>
    
    				</div>
				
				<?php
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Order Not Found</h5>
					</div>
				</div><?php
			}
		}
	}

	// Fetch Restaurant Products by Category - Edit Order
	function fetch_restaurant_products_by_category_edit_order($conn) {
		extract($_POST);
		$category_id_edit_order = mysqli_real_escape_string($conn, $category_id_edit_order);
		
		if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) {
			$fetch_criteria = ($category_id_edit_order == "All") ? "WHERE restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_edit_order ."' AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		} else {
			$fetch_criteria = ($category_id_edit_order == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_edit_order ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		}

		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductEditOrderInformation" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Products Not Found</h5>
					</div>
				</div><?php
			}
		}

	}

	// Search Restaurant Product Live in Admin POS Page
	function search_restaurant_product_live_edit_order($conn) {
		extract($_POST);
		$searched_product_name = mysqli_real_escape_string($conn, $searched_product_name);
		$category_id_edit_order = mysqli_real_escape_string($conn, $category_id_edit_order);


		if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) {
			if ($searched_product_name == "") $fetch_criteria = ($category_id_edit_order == "All") ? "WHERE restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_edit_order ."' AND restaurant_products.productStatus = 1";
			else $fetch_criteria = ($category_id_edit_order == "All") ? "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.categoryID = '". $category_id_edit_order ."' AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		} else {
			if ($searched_product_name == "") $fetch_criteria = ($category_id_edit_order == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_edit_order ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
			else $fetch_criteria = ($category_id_edit_order == "All") ? "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.categoryID = '". $category_id_edit_order ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
			$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";
		}
		
		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductEditOrderInformation" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?></div>
				<div class="col-md-12 text-center">
					<h5 class="text-danger font-weight-normal">Product Not Found</h5>
				</div><?php
			}
		}

	}

	// Edit Restaurant Order - Edit Order Information
	function edit_restaurant_order_information($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$ordered_products_list = $checked_order_products_list;

		if (isset($ordered_products_list["productsStatus"]) && $ordered_products_list["productsStatus"] == "false") {
			$errorList[] = $ordered_products_list["productsMessage"];
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if ($order_subtotal_amount <= $order_discount_amount) {
			$errorList[] = "Check discount amount";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if (($selected_waiter_id == "-") && ($selected_order_type != 'OT0003')) {
			$errorList[] = "Select serving waiter";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			$getOrderLevel = mysqli_query($conn, "SELECT MAX(orderLevel) + 1 FROM kitchen_orders_list WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
			$order_level_rs = mysqli_fetch_array($getOrderLevel);
			foreach ($ordered_products_list["productsMessage"] as $product) {
				$searchCurrentOrderItem = mysqli_query($conn,"SELECT * FROM order_products_list WHERE productID = '". mysqli_real_escape_string($conn, $product[0]) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
				if ($searchCurrentOrderItem) {
					if (mysqli_num_rows($searchCurrentOrderItem) > 0) {
						$order_item_rs = mysqli_fetch_array($searchCurrentOrderItem);
						if ($order_item_rs[2] > $product[1]) {
							// Order item has been decreased
							mysqli_query($conn, "UPDATE order_products_list SET Quantity ='". mysqli_real_escape_string($conn, $product[1]) ."', productPrice = '". mysqli_real_escape_string($conn, $product[2]) ."', totalPrice = '". mysqli_real_escape_string($conn, $product[3]) ."' WHERE productID = '". mysqli_real_escape_string($conn, $product[0]) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
						} else if ($order_item_rs[2] < $product[1]) {
							// Order item has been increased
							mysqli_query($conn, "UPDATE order_products_list SET Quantity ='". mysqli_real_escape_string($conn, $product[1]) ."', productPrice = '". mysqli_real_escape_string($conn, $product[2]) ."', totalPrice = '". mysqli_real_escape_string($conn, $product[3]) ."' WHERE productID = '". mysqli_real_escape_string($conn, $product[0]) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
							mysqli_query($conn, "INSERT INTO kitchen_orders_list (productID, Quantity, orderID, orderLevel, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, ($product[1] - $order_item_rs[2])) ."', '". mysqli_real_escape_string($conn, $selected_order_id) ."', '". mysqli_real_escape_string($conn, $order_level_rs[0]) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));}
					} else {
						// New order item added
						mysqli_query($conn, "INSERT INTO order_products_list (productID, Quantity, productPrice, totalPrice, orderID, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, $product[1]) ."', '". mysqli_real_escape_string($conn, $product[2]) ."', '". mysqli_real_escape_string($conn, $product[3]) ."', '". mysqli_real_escape_string($conn, $selected_order_id) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
						mysqli_query($conn, "INSERT INTO kitchen_orders_list (productID, Quantity, orderID, orderLevel, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, ($product[1])) ."', '". mysqli_real_escape_string($conn, $selected_order_id) ."', '". mysqli_real_escape_string($conn, $order_level_rs[0]) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
					}
				} else {
					$errorList[] = mysqli_error($conn);
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			}

			$update_restaurant_order_now = mysqli_query($conn, "UPDATE restaurant_orders SET customerID = '". mysqli_real_escape_string($conn, $selected_customer_id) ."', orderTypeID = '". mysqli_real_escape_string($conn, $selected_order_type) ."', kitchenNote = '". mysqli_real_escape_string($conn, $kitchen_note_descript) ."', orderSubtotal = '". mysqli_real_escape_string($conn, $order_subtotal_amount) ."', orderDiscount = '". mysqli_real_escape_string($conn, $order_discount_amount) ."', orderVAT = '". mysqli_real_escape_string($conn, $order_true_vat_amount) ."', totalAmount = '". mysqli_real_escape_string($conn, $order_total_amount) ."', servedBy = '". mysqli_real_escape_string($conn, $selected_waiter_id) ."', deliveryAddress = '". mysqli_real_escape_string($conn, $selected_delivery_address) ."', updatedBy = '". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."', updateDate = '". date("Y-m-d H:i:s") ."' WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'");
			if ($update_restaurant_order_now) {
				$data = json_encode(array('Status' => true, 'Message' => $selected_order_id));
			} else {
				$errorList[] = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
			
		}

		echo $data;
	}

	// ================ END OF EDIT ORDER ADMIN POS MODULE =======================================

	// ================ START OF EDIT WAITER  ORDER POS MODULE ===================================
	
	// Fetch Order Full Information to Edit
	function fetch_waiter_order_full_information_to_edit($conn) {
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$getOrderInformation = mysqli_query($conn, "SELECT restaurant_orders.orderID, order_types.orderTypeID, customers.customerID, restaurant_orders.deliveryAddress, restaurant_orders.servedBy, restaurant_orders.orderSubtotal, restaurant_orders.orderDiscount, restaurant_orders.orderVAT, restaurant_orders.totalAmount,  employees.employeePhoto, employees.employeeName, restaurant_orders.registerDate, ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount'
		FROM restaurant_orders
		JOIN customers ON restaurant_orders.customerID = customers.customerID
		JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID
		LEFT JOIN employees ON restaurant_orders.servedBy = employees.employeeID
		LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
		WHERE restaurant_orders.orderID = '$selected_order_id'") or die(mysqli_error($conn));
		if ($getOrderInformation) {
			if (mysqli_num_rows($getOrderInformation) > 0) {
				$order_info_rs = mysqli_fetch_array($getOrderInformation);
				?>
				
					<div class="row">

						<div class="col-md-8">

							<div class="row mb-4">
								<div class="col-md-12">
									<button class="btn btn-primary btn-lg mr-1 mb-2 shadow restaurant_categories_edit_waiter_order" id="all_category_name_admin_pos" category-id="All">
										<i class="fa fa-list-ul" style="font-size: 20px;"></i>
										<b>All</b>
									</button>
									<?php
										$getRestaurantCategories = mysqli_query($conn, "SELECT * FROM restaurant_categories WHERE workingAreaID = '". $_SESSION['workingAreaID'] ."' OR workingAreaID = 'WAR0001' ORDER BY categoryName ASC") or die(mysqli_error($conn));
										while ($category_rs = mysqli_fetch_array($getRestaurantCategories)) { ?>
											<button class="btn btn-primary btn-lg mr-1 mb-2 shadow restaurant_categories_edit_waiter_order" id="<?php echo $category_rs[1]; ?>_category_name_admin_pos" category-id="<?php echo $category_rs[1]; ?>">
												<img class="img-fluid rounded" src="<?php echo $category_rs[9]; ?>" width="25px" height="25px" />
												<b><?php echo $category_rs[2]; ?></b>
											</button><?php
										}
									?>
								</div>
							</div>

							<div class="tile">
								<div class="tile-body">
									<div class="row">

										<div class="col-md-12">
											<div class="row mb-2 mt-1 pull-right">
												<div class="col-md-12">
													<div class="form-group has-search">
														<span class="fa fa-search form-control-feedback text-warning"></span>
														<input type="text" class="form-control rounded-pill" name="txtSearchRestaurantProductLiveWaiterPOSEditOrderInformation" id="txtSearchRestaurantProductLiveWaiterPOSEditOrderInformation" placeholder="Search product" autocomplete="off">
													</div>                                       
												</div>
											</div>
										</div>

										<div class="col-md-12" style="overflow: auto; height: 1200px;">

											<div class="row restaurantProductsWaiterPOSEditOrderInformation">
												<?php

													$getCategoryProducts = mysqli_query($conn, "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products WHERE restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001' AND restaurant_products.productStatus = 1 ORDER BY restaurant_products.productName ASC") or die(mysqli_error($conn));
													if ($getCategoryProducts) {
														if (mysqli_num_rows($getCategoryProducts) > 0) {
															while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
																<div class="col-md-3">
																	<div class="bs-component mt-2 mb-3 singleProductWaiterPOSEditOrderInformation" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
																		<div class="card rounded-lg">
																			<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
																			<div class="card-body">
																				<div class="row">
																					<div class="col-md-12">
																						<h5 class="text-primary text-center font-weight-normal">
																							<?php echo $category_products_rs[1]; ?>
																							<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
																						</h5>
																					</div>
																				</div>
																			</div>
																		</div>
																	</div>
																</div><?php
															}
														}
													}
												?>
											</div>
												
										</div>
									</div>
								</div>
							</div>
						</div>

						<div class="col-md-4">
							<div class="tile">
								<div class="tile-body">
									<div class="row">
										<div class="col-md-12 border-bottom border-primary mb-3">
											<h5 class="text-primary txtOrderIddWaiterPOSEditOrderInformation" order-id-to-edit="<?php echo $order_info_rs[0]; ?>"><i class="fa fa-shopping-cart"></i> Edit Checkout - <?php echo $order_info_rs[0]; ?></h5>
										</div>
										<div class="col-md-12 pb-2">
											<?php
												if ($order_info_rs[1] == "OT0001") { ?>
													<button class="btn btn-success mr-1 btnOrderTypeWaiterPOSEditOrderInformation" id="btnSeatInWaiterPOSEditOrderInformation" order-type-edit-order="OT0001"><i class="fa fa-hotel"></i> Seat In</button>
													<button class="btn btn-outline-primary mr-1 btnTakeAwayWaiterPOSEditOrderInformation" id="btnTakeAwayWaiterPOSEditOrderInformation"><i class="fa fa-shopping-basket"></i> Take Away</button>
												<?php } else if ($order_info_rs[1] == "OT0002") { ?>
													<button class="btn btn-outline-success mr-1 btnSeatInWaiterPOSEditOrderInformation" id="btnSeatInWaiterPOSEditOrderInformation"><i class="fa fa-hotel"></i> Seat In</button>
													<button class="btn btn-primary mr-1 btnOrderTypeWaiterPOSEditOrderInformation" id="btnTakeAwayWaiterPOSEditOrderInformation" order-type-edit-order="OT0002"><i class="fa fa-shopping-basket"></i> Take Away</button>
												<?php }
											?>
										</div>
										<div class="form-group col-md-12 pt-3">
											<select id="cmbCustomerIddWaiterPOSEditOrderInformation" name="cmbCustomerIddWaiterPOSEditOrderInformation" class="form-control" style="width:100%" required />
											
											</select>
										</div>
										<script type="text/javascript">
											$("#cmbCustomerIddWaiterPOSEditOrderInformation").select2({ tags: true })
											$.ajax({
												method: "POST", url: "api/main.php", data: { action: "fill_active_customers" }, dataType: "JSON",
												success: function (data) {
												var Message = data.Message
												var status = data.Status
												var html = ""
												html += `<option value="CU0001">Walking Customer - 000000000</option>`
												if (status == true) {
													Message.forEach(function (returned_data, i) {
														html += `<option value="${returned_data["customerID"]}">${returned_data["customerName"]} - ${returned_data["customerMobile"]}</option>`
													})
													$("#cmbCustomerIddWaiterPOSEditOrderInformation").html(html)
													$("#cmbCustomerIddWaiterPOSEditOrderInformation").select2().val(<?php echo json_encode($order_info_rs[2]); ?>).trigger("change")  
												}
												}, error: function (data) { },
											})
										</script>

										<div class="form-group col-md-12 pt-1 pb-2 orderedProductsWaiterPOSEditOrderInformation">
											<?php
												$getOrderProductsList = mysqli_query($conn, "SELECT restaurant_products.productID, restaurant_products.productName, order_products_list.Quantity, order_products_list.productPrice 'unitPrice', order_products_list.totalPrice 'totalPrice'
												FROM order_products_list
												JOIN restaurant_products ON order_products_list.productID = restaurant_products.productID
												JOIN restaurant_orders ON order_products_list.orderID = restaurant_orders.orderID
												WHERE order_products_list.orderID = '". $order_info_rs[0] ."'");
												if ($getOrderProductsList){
													if (mysqli_num_rows($getOrderProductsList) > 0) {
														while ($order_product_list = mysqli_fetch_array($getOrderProductsList)) {
															?>
																<div class="row align-items-center font-weight-bold pt-2 pb-2 border-bottom border-light" style="margin: 0px;" id="editWaiterOrderedProductId<?php echo $order_product_list[0]; ?>" ordered-product-id="<?php echo $order_product_list[0]; ?>" ordered-product-name="<?php echo $order_product_list[1]; ?>" ordered-product-price="<?php echo $order_product_list[3]; ?>">
																	<div class="col-md-1 text-left"><i class="fa fa-trash fa-lg text-dark" style="cursor: pointer;"></i></div>
																	<div class="col-md-5"><?php echo $order_product_list[1]; ?></div>
																	<div class="col-md-4">
																		<button class="btn btn-outline-success rounded-pill btnIncrementProductQuantityWaiterPOSEditOrderInformation"><span class="font-weight-bold">+</span></button><span class="pl-2 pr-2 waiterOrderedProductQuantityEditOrderInformation"><?php echo $order_product_list[2]; ?></span><button class="btn btn-outline-danger rounded-pill btnDecrementProductQuantityWaiterPOSEditOrderInformation" original-product-quantity="<?php echo $order_product_list[2]; ?>"><span class="font-weight-bold">-</span></button>
																	</div>
																	<div class="col-md-2">$<span class="waiterOrderedProductPriceEditOrderInformation" ><?php echo number_format($order_product_list[4], 2); ?></div>
																</div>

															<?php
														}
													} else {
														?><p>Order List Not Found</p><?php
													}
												} else {
													?><p><?php echo mysqli_error($conn); ?></p><?php
												}
												
											?>
										</div>

									<div class="form-group col-md-12 pt-3 pb-1">
										<div class="row align-items-center font-weight-bold pt-1 pb-1" style="margin: 0px;">
											<div class="col-md-8"><h5 class="text-primary">Subtotal</h5></div>
											<div class="col-md-4 text-center"><h5>$<span id="waiterOrderedProductsSubtotalEditOrderInformation"><?php echo number_format($order_info_rs[5], 2); ?></span><h5></div>
										</div>
										<div class="row align-items-center font-weight-bold pt-1 pb-1" style="margin: 0px;">
    										<div class="col-md-8"><h5 class="text-danger">VAT Tax (%5)</h5></div>
                                            <div class="col-md-4 text-center"><h5 class="text-danger">$<span id="txtOrderedProductsVATWaiterPOSEditOrderInformation"><?php echo number_format($order_info_rs[7], 2); ?></span><h5></div>
                                        </div>
										<div class="row align-items-center font-weight-bold pt-2 pb-1" style="margin: 0px;">
											<div class="col-md-8"><h5 class="text-primary">Total</h5></div>
											<div class="col-md-4 text-center"><h5 class="text-success">$<span id="waiterOrderedProductsTotalEditOrderInformation"><?php echo number_format($order_info_rs[8], 2); ?></span><h5></div>
										</div>
									</div>

									<div class="form-group col-md-12 pt-1 pb-1">
										<div class="row pt-2 pull-right">
											<div class="col-md-12">
												<button class="btn btn-danger btn-lg pl-3 pr-3 mr-1" name="btnCancelWaiterOrderEditOrderInformation" id="btnCancelWaiterOrderEditOrderInformation" data-dismiss="modal" aria-label="Close"><i class="fa fa-times"></i>Cancel Editing</button>
												<button class="btn btn-primary btn-lg pl-4 pr-4" name="btnEditAndPrintWaiterOrderEditOrderInformation" id="btnEditAndPrintWaiterOrderEditOrderInformation"><i class="fa fa-print"></i>Edit & Print</button>
											</div>
										</div>
									</div>

								</div>
							</div>
						</div>
						
					</div>

				</div>
				
				<?php
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Order Not Found</h5>
					</div>
				</div><?php
			}
		}
	}

	// Fetch Restaurant Products by Category - Edit Waiter Order
	function fetch_restaurant_products_by_category_edit_waiter_order($conn) {
		extract($_POST);
		$category_id_edit_waiter_pos = mysqli_real_escape_string($conn, $category_id_edit_waiter_pos);
		
		$fetch_criteria = ($category_id_edit_waiter_pos == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_edit_waiter_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
		$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";

		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductWaiterPOSEditOrderInformation" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Products Not Found</h5>
					</div>
				</div><?php
			}
		}

	}

	// Search Restaurant Product Live - Waiter POS Edit Order Information
	function search_restaurant_product_live_edit_waiter_order($conn) {
		extract($_POST);
		$searched_product_name = mysqli_real_escape_string($conn, $searched_product_name);
		$category_id_edit_waiter_pos = mysqli_real_escape_string($conn, $category_id_edit_waiter_pos);

		if ($searched_product_name == "") $fetch_criteria = ($category_id_edit_waiter_pos == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_edit_waiter_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
		else $fetch_criteria = ($category_id_edit_waiter_pos == "All") ? "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.categoryID = '". $category_id_edit_waiter_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
		$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";

		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductWaiterPOSEditOrderInformation" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?></div>
				<div class="col-md-12 text-center">
					<h5 class="text-danger font-weight-normal">Product Not Found</h5>
				</div><?php
			}
		}

	}

	// Edit Restaurant Order - Edit Waiter Order Information
	function edit_restaurant_waiter_order_information($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$ordered_products_list = $checked_order_products_list;

		if (isset($ordered_products_list["productsStatus"]) && $ordered_products_list["productsStatus"] == "false") {
			$errorList[] = $ordered_products_list["productsMessage"];
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			$getOrderLevel = mysqli_query($conn, "SELECT MAX(orderLevel) + 1 FROM kitchen_orders_list WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
			$order_level_rs = mysqli_fetch_array($getOrderLevel);
			foreach ($ordered_products_list["productsMessage"] as $product) {
				$searchCurrentOrderItem = mysqli_query($conn,"SELECT * FROM order_products_list WHERE productID = '". mysqli_real_escape_string($conn, $product[0]) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
				if ($searchCurrentOrderItem) {
					if (mysqli_num_rows($searchCurrentOrderItem) > 0) {
						$order_item_rs = mysqli_fetch_array($searchCurrentOrderItem);
						if ($order_item_rs[2] > $product[1]) {
							// Order item has been decreased
							mysqli_query($conn, "UPDATE order_products_list SET Quantity ='". mysqli_real_escape_string($conn, $product[1]) ."', productPrice = '". mysqli_real_escape_string($conn, $product[2]) ."', totalPrice = '". mysqli_real_escape_string($conn, $product[3]) ."' WHERE productID = '". mysqli_real_escape_string($conn, $product[0]) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
						} else if ($order_item_rs[2] < $product[1]) {
							// Order item has been increased
							mysqli_query($conn, "UPDATE order_products_list SET Quantity ='". mysqli_real_escape_string($conn, $product[1]) ."', productPrice = '". mysqli_real_escape_string($conn, $product[2]) ."', totalPrice = '". mysqli_real_escape_string($conn, $product[3]) ."' WHERE productID = '". mysqli_real_escape_string($conn, $product[0]) ."' AND orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
							mysqli_query($conn, "INSERT INTO kitchen_orders_list (productID, Quantity, orderID, orderLevel, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, ($product[1] - $order_item_rs[2])) ."', '". mysqli_real_escape_string($conn, $selected_order_id) ."', '". mysqli_real_escape_string($conn, $order_level_rs[0]) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));}
					} else {
						// New order item added
						mysqli_query($conn, "INSERT INTO order_products_list (productID, Quantity, productPrice, totalPrice, orderID, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, $product[1]) ."', '". mysqli_real_escape_string($conn, $product[2]) ."', '". mysqli_real_escape_string($conn, $product[3]) ."', '". mysqli_real_escape_string($conn, $selected_order_id) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
						mysqli_query($conn, "INSERT INTO kitchen_orders_list (productID, Quantity, orderID, orderLevel, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, ($product[1])) ."', '". mysqli_real_escape_string($conn, $selected_order_id) ."', '". mysqli_real_escape_string($conn, $order_level_rs[0]) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));}
				} else {
					$errorList[] = mysqli_error($conn);
					$data = json_encode(array('Status' => false, 'Message' => $errorList));
				}
			}

			$update_restaurant_order_now = mysqli_query($conn, "UPDATE restaurant_orders SET customerID = '". mysqli_real_escape_string($conn, $selected_customer_id) ."', orderTypeID = '". mysqli_real_escape_string($conn, $selected_order_type) ."', orderSubtotal = '". mysqli_real_escape_string($conn, $order_subtotal_amount) ."', orderVAT = '". mysqli_real_escape_string($conn, $order_true_vat_amount) ."', totalAmount = '". mysqli_real_escape_string($conn, $order_total_amount) ."', updatedBy = '". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."', updateDate = '". date("Y-m-d H:i:s") ."' WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'");
			if ($update_restaurant_order_now) {
				$data = json_encode(array('Status' => true, 'Message' => $selected_order_id));
			} else {
				$errorList[] = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
			
		}

		echo $data;
	}

	// ================ END OF EDIT WAITER ORDER ADMIN POS MODULE ================================

	// ================ START OF VIEW AND PRINT ORDER ADMIN POS MODULE ===========================

	// View and Print Restaurant Order
	function view_and_print_order_receipt($conn) {
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$selected_btn_type = mysqli_real_escape_string($conn, $btn_type);

		if ($selected_btn_type == "Print") {
		    ?><div class="row">
        	    <div class="col-md-12 text-right">
        		    <button class="btn btn-success mr-1" id="printCurrentOrderReceipts"><i class="fa fa-print"></i> Print Receipts</button>
        	    </div>
            </div><?php

		    $getRelatedKitchens = mysqli_query($conn, "SELECT restaurant_products.kitchenID, kitchens.kitchenName
            FROM kitchen_orders_list
            JOIN restaurant_products ON kitchen_orders_list.productID = restaurant_products.productID
            JOIN kitchens ON restaurant_products.kitchenID = kitchens.kitchenID
            WHERE kitchen_orders_list.orderID = '". $selected_order_id ."' AND kitchen_orders_list.Quantity > 0 AND kitchen_orders_list.orderLevel = (SELECT MAX(orderLevel) FROM kitchen_orders_list WHERE orderID = '". $selected_order_id ."')
            GROUP BY restaurant_products.kitchenID");
            if ($getRelatedKitchens) {
                if (mysqli_num_rows($getRelatedKitchens) > 0) {
                    ?><div class="row">
    					<div class="col-md-12 text-right">
    						<button class="btn btn-success btn-sm mr-1 printOrderForKitchens" id="printOrderReceiptForChashier" div-to-print="orderReceiptForChashierPrintArea" style="display: none;"><i class="fa fa-print"></i> Cashier Print </button>
    						<?php
                                while ($kitchen_result = mysqli_fetch_array($getRelatedKitchens)) {
                                    ?><button class="btn btn-success btn-sm mr-2 printOrderForKitchens" id="printOrderReceiptFor<?php echo $kitchen_result[0]; ?>" div-to-print="orderReceiptFor<?php echo $kitchen_result[0]; ?>PrintArea" style="display: none;"><i class="fa fa-print"></i> <?php echo $kitchen_result[1]. " Print"; ?> </button><?php
                                    view_and_print_order_receipt_kitchens($conn, $selected_order_id, $kitchen_result[0], $kitchen_result[1]);
                                }
                            ?>
                        </div>
                    <?php
                } else {
                    ?><div class="row">
    					<div class="col-md-12 text-right">
    						<button class="btn btn-success btn-sm mr-1 printOrderForKitchens" id="printOrderReceiptForChashier" div-to-print="orderReceiptForChashierPrintArea" style="display: none;"><i class="fa fa-print"></i> Cashier Print </button>
                        </div>
                    <?php
                }
            } else {
                echo "<p>". mysqli_error($conn). "</p>";
            }
		}

		$getOrderInformation = mysqli_query($conn, "SELECT restaurant_orders.orderID, restaurant_orders.workingAreaID, restaurant_orders.orderTypeID, order_types.orderTypeName, customers.customerName, customers.customerMobile, restaurant_orders.deliveryAddress, tables.tableName, restaurant_orders.registerDate, served_waiter.employeeName 'WaiterName', served_waiter_user.Username 'WaiterUsername', delivered_man.employeeName 'DeliveryMan', restaurant_orders.orderSubtotal, restaurant_orders.orderDiscount, restaurant_orders.orderVAT, ROUND(IFNULL(restaurant_orders.totalAmount, 0), 2) 'OrderBalance', IFNULL(SUM(customer_payments.paidAmount), 0) 'PaidAmount', ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount'
		FROM restaurant_orders
		JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID
		JOIN customers ON restaurant_orders.customerID = customers.customerID
		LEFT JOIN tables ON restaurant_orders.tableID = tables.tableID
		LEFT JOIN employees served_waiter ON restaurant_orders.servedBy = served_waiter.employeeID
		LEFT JOIN system_users served_waiter_user ON served_waiter.employeeID = served_waiter_user.employeeID
		LEFT JOIN employees delivered_man ON restaurant_orders.deliveredBy = delivered_man.employeeID
	    LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
		JOIN system_users ON restaurant_orders.registeredBy = system_users.userID
		WHERE restaurant_orders.orderID = '". $selected_order_id ."'");
		if ($getOrderInformation) {
			if (mysqli_num_rows($getOrderInformation) > 0) {
				$order_result = mysqli_fetch_array($getOrderInformation); ?>
				
				<div class="mt-5" id="orderReceiptForChashierPrintArea">
					<div class="row">
						<div class="col-md-12 text-right">
							<h1 style="font-size: 55px"><span style="font-weight: normal;"><?php echo substr($order_result[8], 0, 16); ?></span></h1>
						</div>
					</div>
					<div class="row">
						<div class="col-md-12 text-center">
							<img src="img/report-black-and-white-logo.png" width="90%" height="400px" /><br>
							<h1 style="font-size: 100px">Cashier Receipt</h1>
						</div>
					</div>
					<hr style="border-top: 3px dashed black;">
					<?php
						if ($order_result[1] == "WAR0002") {
							// Waa Merchants-ka qeybta hoose
							?><div class="row pt-2 pb-2">
								<div class="col-md-12 text-center">
									<h1 style="font-size: 60px; font-weight: normal;">Merchant: *789*722022*<?php echo "$". number_format($order_result[15], 2)?>#</h1>
									<h1 style="font-size: 60px; font-weight: normal;">eDahab: *113*120891*<?php echo "$". number_format($order_result[15], 2)?>#</h1>
									<h1 style="font-size: 60px; font-weight: normal;">Premier Wallet: 218866</h1>
								</div>
							</div><?php
						} else if ($order_result[1] == "WAR0003") {
							// Waa Merchants-ka qeybta kore
							?><div class="row pt-2 pb-2">
								<div class="col-md-12 text-center">
									<h1 style="font-size: 60px; font-weight: normal;">Merchant: *789*730912*<?php echo "$". number_format($order_result[15], 2)?>#</h1>
									<h1 style="font-size: 60px; font-weight: normal;">eDahab: *113*120892*<?php echo "$". number_format($order_result[15], 2)?>#</h1>
									<h1 style="font-size: 60px; font-weight: normal;">Premier Wallet: 897720</h1>
								</div>
							</div><?php
						}
					?>
					
					<hr style="border-top: 3px dashed black;">
					<div class="row pt-2 pb-2">
						<div class="col-md-12">
						    <h1 style="font-size: 55px; font-weight: bold;">Ref No: <span style='font-weight: normal;'><?php echo $order_result[0]. "</span> - <span style='font-weight: bold;'>" .$order_result[3]; ?></span></h1>
						</div>
					</div>
					<div class="row pt-2 pb-2">
						<div class="col-md-12">
							<h1 style="font-size: 50px">Customer: <span style="font-weight: normal;"><?php echo $order_result[4]; ?></span></h1>
						</div>
						<?php
							if ($order_result[2] == "OT0003") {
								?><div class="col-md-12 pt-2">
									<h1 style="font-size: 50px">Mobile: <span style="font-weight: normal;"><?php echo $order_result[5]; ?></span></h1>
								</div>
								<div class="col-md-12 pt-2">
									<h1 style="font-size: 50px">Delivery Address: <span style="font-weight: normal;"><?php echo $order_result[6]; ?></span></h1>
								</div>
								<div class="col-md-12 pt-2">
									<h1 style="font-size: 50px">Deliverer: <span style="font-weight: normal;"><?php echo $order_result[11]; ?></span></h1>
								</div><?php
							} else {
								?><div class="col-md-12 pt-2">
									<h1 style="font-size: 50px">Waiter: <span style="font-weight: normal;"><?php echo $order_result[10]; ?></span></h1>
								</div><?php
							}
						?>
					</div>
	
					<div class="row pt-5">
						<div class="col-md-12">
							<div class="table-responsive">
								<table class="table" cellpadding="5" cellspacing="5">
									<thead>
										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
											<th><h1 style="font-size: 50px;">Product Name</h1></th>
											<th class="text-center"><h1 style="font-size: 50px;">Qty</h1></th>
											<th class="text-center"><h1 style="font-size: 50px;">Price</h1></th>
											<th class="text-center"><h1 style="font-size: 50px;">Total</h1></th>
										</tr>
									</thead>
									<tbody>
										<?php 
											$getOrderProductList = mysqli_query($conn, "SELECT restaurant_products.productName, order_products_list.Quantity, order_products_list.productPrice, order_products_list.totalPrice
											FROM order_products_list
											JOIN restaurant_products ON order_products_list.productID = restaurant_products.productID
											JOIN restaurant_orders ON order_products_list.orderID = restaurant_orders.orderID
											WHERE restaurant_orders.orderID = '". $selected_order_id ."'");
											if ($getOrderProductList) {
												if (mysqli_num_rows($getOrderProductList) > 0) {
													while ($prod_result = mysqli_fetch_array($getOrderProductList)) {
														?><tr>
															<td class="text-left"><h1 style="font-size: 50px; font-weight: normal;"><?php echo $prod_result[0];?></h1></td>
															<td class="text-center"><h1 style="font-size: 50px; font-weight: normal;"><?php echo $prod_result[1];?></h1></td>
															<td class="text-center"><h1 style="font-size: 50px; font-weight: normal;"><?php echo "$". number_format($prod_result[2], 2); ?></h1></td>
															<td class="text-center"><h1 style="font-size: 50px; font-weight: normal;"><?php echo "$". number_format($prod_result[3], 2); ?></h1></td>
														</tr><?php
													}
												} else {
													?><p>List Not Found</p><?php
												}
											} else {
												echo "<p>". mysqli_error($conn). "</p>";
											}		 			
											
										?>
									</tbody>
									<tfooter>
										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
											<td colspan="3" class="text-right"><h1 class="font-weight-normal" style="font-size: 50px;">Subtotal</h1></td>
											<td class="text-center"><h1 style="font-size: 50px;"><?php echo "$". number_format($order_result[12], 2); ?></h1></td>
										</tr>
										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
											<td colspan="3" class="text-right"><h1 class="font-weight-normal" style="font-size: 50px;">Discount</h1></td>
											<td class="text-center"><h1 style="font-size: 50px;"><?php echo "$". number_format($order_result[13], 2); ?></h1></td>
										</tr>
										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
											<td colspan="3" class="text-right"><h1 class="font-weight-normal" style="font-size: 50px;">VAT (%5)</h1></td>
											<td class="text-center"><h1 style="font-size: 50px;"><?php echo "$". number_format($order_result[14], 2); ?></h1></td>
										</tr>
										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
											<td colspan="3" class="text-right"><h1 class="font-weight-normal" style="font-size: 50px;">Total</h1></td>
											<td class="text-center"><h1 style="font-size: 50px;"><?php echo "$". number_format($order_result[15], 2); ?></h1></td>
										</tr>
										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
											<td colspan="3" class="text-right"><h1 class="font-weight-normal" style="font-size: 50px;">Paid Amount</h1></td>
											<td class="text-center"><h1 style="font-size: 50px;"><?php echo "$". number_format($order_result[16], 2); ?></h1></td>
										</tr>
										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
											<td colspan="3" class="text-right"><h1 class="font-weight-normal" style="font-size: 50px;">Resto</h1></td>
											<td class="text-center"><h1 style="font-size: 50px;"><?php echo "$". number_format($order_result[17], 2); ?></h1></td>
										</tr>
									</tfooter>
								</table>
							</div>
						</div>
					</div>
	
					<div class="row pt-4">
						<div class="col-md-12 text-center">
							<h1 style="font-size: 50px; font-style: italic; font-weight: normal;">Mahadsanid, soo noqosho wanaagsan</h1>
							<h1 style="font-size: 50px; font-style: italic; font-weight: normal;">Designed by <b>Hirgal Solutions</b></h1>
						</div>
					</div>
	
				</div><?php
			} else {
				?><p>Order Not Found</p><?php
			}
		} else {
			echo "<p>". mysqli_error($conn). "</p>";
		}

	}
	
	// View and Print Restaurant Order Receipt - Kitchens
	function view_and_print_order_receipt_kitchens($conn, $order_id_par, $kitchen_id_par, $kitchen_name_par) {
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $order_id_par);
		$selected_kitchen_id = mysqli_real_escape_string($conn, $kitchen_id_par);
		
		$getOrderInformation = mysqli_query($conn, "SELECT restaurant_orders.orderID, order_types.orderTypeName, restaurant_orders.registerDate, served_waiter.employeeName 'WaiterName', system_users.Username, restaurant_orders.kitchenNote
		FROM restaurant_orders
		JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID
		LEFT JOIN employees served_waiter ON restaurant_orders.servedBy = served_waiter.employeeID
		JOIN system_users ON restaurant_orders.registeredBy = system_users.userID
		WHERE restaurant_orders.orderID = '". $selected_order_id ."'");
		if ($getOrderInformation) {
			if (mysqli_num_rows($getOrderInformation) > 0) {
				$order_result = mysqli_fetch_array($getOrderInformation); ?>
				
				<div class="mt-5" id="orderReceiptFor<?php echo $kitchen_id_par; ?>PrintArea" style="display: none;">
				    
				    <?php
				        $getOrderCategories = mysqli_query($conn, "SELECT restaurant_products.categoryID, restaurant_categories.categoryName
                        FROM kitchen_orders_list
                        JOIN restaurant_products ON kitchen_orders_list.productID = restaurant_products.productID
                        JOIN restaurant_categories ON restaurant_products.categoryID = restaurant_categories.categoryID
                        WHERE kitchen_orders_list.orderID = '". $selected_order_id ."' AND restaurant_products.kitchenID = '". $selected_kitchen_id ."' AND kitchen_orders_list.Quantity > 0 AND kitchen_orders_list.orderLevel = (SELECT MAX(orderLevel) FROM kitchen_orders_list WHERE orderID = '". $selected_order_id ."')
                        GROUP BY restaurant_products.categoryID");
                        if ($getOrderCategories) {
                            if (mysqli_num_rows($getOrderCategories) > 0) {
                                while ($categories_rs = mysqli_fetch_array($getOrderCategories)) { 
                                    ?>
                                        <div class="mb-5">
                                            <div class="row">
                        						<div class="col-md-12 text-right">
                        							<h1 style="font-size: 55px"><span style="font-weight: normal;"><?php echo substr($order_result[2], 0, 16); ?></span></h1>
                        						</div>
                        				    </div>
                        				    <div class="row">
                        						<div class="col-md-12 text-center">
                        						    <img src="img/report-black-and-white-logo.png" width="70%" height="300px" /><br>
                        							<h1 style="font-size: 100px"><?php echo $kitchen_name_par. " Receipt"; ?></h1>
                        						</div>
                        				    </div>
                    					    <hr style="border-top: 3px dashed black;">
                    
                        					<div class="row pt-2 pb-2">
                        						<div class="col-md-7">
                        						    <h1 style="font-size: 55px; font-weight: bold;">Ref No: <span style='font-weight: normal;'><?php echo $order_result[0]. "</span> - <span style='font-weight: bold;'>" .$order_result[1]; ?></span></h1>
                        						</div>
                        					</div>
                        			        <div class="row pt-2 pb-2">
                        						<div class="col-md-12">
                        							<h1 style="font-size: 50px">Waiter: <span style="font-weight: normal;"><?php echo ($order_result[4] == "") ? "-" : $order_result[4]; ?></span></h1>
                        						</div>
                        				    </div>
	
                					        <div class="row pt-5">
                        						<div class="col-md-12">
                        							<div class="table-responsive">
                        								<table class="table" cellpadding="5" cellspacing="5">
                        									<thead>
                        										<tr style="border-top: 3px dashed black; border-bottom: 3px dashed black;">
                        											<th><h1 style="font-size: 50px;">Product Name</h1></th>
                        											<th class="text-center"><h1 style="font-size: 50px;">Qty</h1></th>
                        										</tr>
                        									</thead>
                        									<tbody>
                        										<?php 
                        											$getOrderProductList = mysqli_query($conn, "SELECT restaurant_products.productName, kitchen_orders_list.Quantity
                        											FROM kitchen_orders_list
                        											JOIN restaurant_products ON kitchen_orders_list.productID = restaurant_products.productID
                        											JOIN kitchens ON restaurant_products.kitchenID = kitchens.kitchenID
                        											JOIN restaurant_orders ON kitchen_orders_list.orderID = restaurant_orders.orderID
                        											WHERE restaurant_orders.orderID = '". $selected_order_id ."' AND restaurant_products.categoryID = '". $categories_rs[0] ."' AND restaurant_products.kitchenID = '". $selected_kitchen_id ."' AND kitchen_orders_list.Quantity > 0 AND kitchen_orders_list.orderLevel = (SELECT MAX(orderLevel) FROM kitchen_orders_list WHERE orderID = '". $selected_order_id ."')");
                        											if ($getOrderProductList) {
                        												if (mysqli_num_rows($getOrderProductList) > 0) {
                        													while ($prod_result = mysqli_fetch_array($getOrderProductList)) {
                        														?><tr>
                        															<td class="text-left"><h1 style="font-size: 50px; font-weight: normal;"><?php echo $prod_result[0];?></h1></td>
                        															<td class="text-center"><h1 style="font-size: 50px; font-weight: normal;"><?php echo $prod_result[1];?></h1></td>
                        														</tr><?php
                        													}
                        												} else {
                        													?><p>List Not Found</p><?php
                        												}
                        											} else {
                        												echo "<p>". mysqli_error($conn). "</p>";
                        											}		 			
                        											
                        										?>
                        									</tbody>
                        								</table>
                        							</div>
                        						</div>
                					        </div>
        	
                					        <div class="row pt-4 pb-4">
                        						<div class="col-md-12 text-justify">
                        						    <h1 style="font-size: 50px; font-style: italic; font-weight: bold;">Kitchen Note</h1>
                        							<h1 style="font-size: 50px; font-style: italic; font-weight: normal;"><?php echo $order_result[5];?></h1>
                        						</div>
                        					</div>
                        					
                        					
                					        <div class="row pt-4">
                        						<div class="col-md-12 text-center">
                        							<h1 style="font-size: 50px; font-style: italic; font-weight: normal;">Fadlan dalabka hala dedejiyo</h1>
                        							<h1 style="font-size: 50px; font-style: italic; font-weight: normal;">Designed by <b>Hirgal Solutions</b></h1>
                        						</div>
                        					</div>
                                            
                                        </div>
                                       
                    				<?php
                                }
                            } else {
							    ?><p>Categories Not Found</p><?php
                            }
                        } else {
                            echo "<p>". mysqli_error($conn). "</p>";
                        }
				    
				    ?>
	
				</div><?php
			} else {
				?><p>Order Not Found</p><?php
			}
		} else {
			echo "<p>". mysqli_error($conn). "</p>";
		}

	}

	// ================ END OF VIEW AND PRINT ORDER ADMIN POS MODULE =============================
	
	// ================ Start of Search Date Based Orders Page ===================================
		
	function search_date_based_orders($conn) {
		extract($_POST);
		$selected_order_status = mysqli_real_escape_string($conn, $selected_order_status);
		$selected_start_date = mysqli_real_escape_string($conn, $selected_start_date);
		$selected_end_date = mysqli_real_escape_string($conn, date("Y-m-d H:i", strtotime($selected_end_date. " + 1 days")));
		
		?><table class="table table-hover table-bordered table-sm display nowrap" id="ordersOfTodayTable">
            <thead>
                <tr class="text-light bg-primary text-center" style="height: 45px;">
                    <th class="align-middle">Edit</th>
                    <th class="align-middle">OrderID</th>
                    <th class="align-middle">Customer Name</th>
                    <th class="align-middle">Type</th>
                    <th class="align-middle">Orderer</th>
                    <th class="align-middle">Time</th>
                    <th class="align-middle">Balance</th>
                    <th class="align-middle">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                    if ($selected_order_status == "0") {
                        $fetchCriteria = "WHERE restaurant_orders.orderStatus != '4' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        GROUP BY restaurant_orders.orderID
                        ORDER BY restaurant_orders.registerDate ASC";
                    } else if ($selected_order_status == "1") {
                        $fetchCriteria = "WHERE restaurant_orders.orderStatus != '4' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        GROUP BY restaurant_orders.orderID
                        HAVING UnpaidAmount = 0
                        ORDER BY restaurant_orders.registerDate ASC";
                    } else if ($selected_order_status == "2") {
                        $fetchCriteria = "WHERE restaurant_orders.orderStatus != '4' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        GROUP BY restaurant_orders.orderID
                        HAVING UnpaidAmount > 0 AND UnpaidAmount < OrderBalance
                        ORDER BY restaurant_orders.registerDate ASC";
                    } else if ($selected_order_status == "3") {
                        $fetchCriteria = "WHERE restaurant_orders.orderStatus != '4' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        GROUP BY restaurant_orders.orderID
                        HAVING UnpaidAmount = OrderBalance
                        ORDER BY restaurant_orders.registerDate ASC";
                    }
                    $getTodayOrdersList = mysqli_query($conn, "SELECT restaurant_orders.orderID, customers.customerName, order_types.orderTypeName, orderer_employee.employeePhoto, orderer_user.Username, restaurant_orders.registerDate, ROUND(IFNULL(restaurant_orders.totalAmount, 0), 2) 'OrderBalance', ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount', receiver_cashier.Username
                    FROM restaurant_orders
                    LEFT JOIN customers ON restaurant_orders.customerID = customers.customerID
                    JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID
					LEFT JOIN system_users orderer_user ON restaurant_orders.registeredBy = orderer_user.userID
					JOIN employees orderer_employee ON orderer_user.employeeID = orderer_employee.employeeID
                    LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
                    LEFT JOIN system_users receiver_cashier ON customer_payments.registeredBy = receiver_cashier.userID
					$fetchCriteria") or die(mysqli_error($conn));
                    
                    $count_total_orders = 0;
                    $count_total_balance = 0;
                    $count_total_due_balance = 0;
                    while ($today_orders_rs = mysqli_fetch_array($getTodayOrdersList)) {?>
                        <tr>
                            <td class="align-middle text-center">
                                <?php
                                    if (($today_orders_rs[7] > 0) || ($today_orders_rs[2] == "Delivery")) { ?>
										<span class="bg-primary text-white p-2 rounded-lg font-weight-bold btnEditOrderInformation" style="cursor: pointer;" data-id="<?php echo $today_orders_rs[0]; ?>" data-toggle="modal" data-target="#editRestaurantOrderModal" title="Edit Order"><i class="fa fa-pencil fa-lg"></i></span>
										<span class="bg-success text-white p-2 rounded-lg font-weight-bold btnPrintOrderInformation" style="cursor: pointer;" data-id="<?php echo $today_orders_rs[0]; ?>" btn-type="Print" data-toggle="modal" data-target="#viewAndPrintOrderReceiptModal" title="Print Order"><i class="fa fa-print fa-lg"></i></span>
										<span class="bg-danger text-white p-2 rounded-lg font-weight-bold btnCancelOrderInformation" style="cursor: pointer;" data-id="<?php echo $today_orders_rs[0]; ?>" title="Cancel Order"><i class="fa fa-times fa-lg"></i></span>
									<?php } else if (($today_orders_rs[7] <= 0) && ($today_orders_rs[2] == "Seat In")) { ?>
										<span class="bg-success text-white p-2 rounded-lg font-weight-bold btnPrintOrderInformation" style="cursor: pointer;" data-id="<?php echo $today_orders_rs[0]; ?>" btn-type="View" data-toggle="modal" data-target="#viewAndPrintOrderReceiptModal" title="View Order"><i class="fa fa-eye fa-lg"></i> View</span>
									<?php } else if (($today_orders_rs[7] <= 0) && ($today_orders_rs[2] == "Take Away")) { ?>
									    <span class="bg-success text-white p-2 rounded-lg font-weight-bold btnPrintOrderInformation" style="cursor: pointer;" data-id="<?php echo $today_orders_rs[0]; ?>" btn-type="View" data-toggle="modal" data-target="#viewAndPrintOrderReceiptModal" title="View Order"><i class="fa fa-eye fa-lg"></i></span>
										<span class="bg-danger text-white p-2 rounded-lg font-weight-bold btnCancelOrderInformation" style="cursor: pointer;" data-id="<?php echo $today_orders_rs[0]; ?>" title="Cancel Order"><i class="fa fa-times fa-lg"></i></span>
                                    <?php }
                                ?>
                                
								
							</td>
                            <td class="align-middle text-center"><span class="text-primary font-weight-bold"><?php echo $today_orders_rs[0]; ?></td>
                            <td class="align-middle text-left"><?php echo $today_orders_rs[1]; ?></td>
                            <td class="align-middle text-left">
                                <?php 
                                    if ($today_orders_rs[2] == "Seat In") {
                                        ?><h6 class="text-success"><i class='fa fa-hotel'></i> <?php echo $today_orders_rs[2]; ?></h6><?php
                                    } else if ($today_orders_rs[2] == "Take Away") {
                                        ?><h6 class="text-primary"><i class='fa fa-shopping-basket'></i> <?php echo $today_orders_rs[2]; ?></h6><?php
                                    } else if ($today_orders_rs[2] == "Delivery") {
                                        ?><h6 class="text-danger"><i class='fa fa-motorcycle'></i> <?php echo $today_orders_rs[2]; ?></h6><?php
                                    }
                                ?>
                            </td>
							<td class="align-middle text-left"><img class="img-fluid rounded-circle pr-2" src="<?php echo $today_orders_rs[3]; ?> " width="40px" height="40px"/><?php echo $today_orders_rs[4]; ?></td>
							<td class="align-middle text-left font-weight-bold"><?php echo date('d F', strtotime($today_orders_rs[5])). "<br />" .date('h:i A', strtotime($today_orders_rs[5])); ?></td>
                            <td class="align-middle text-center"><h6 class="text-success"><?php echo "$". number_format($today_orders_rs[6], 2); ?></h6></td>
                            <td class="align-middle text-center">
                                <?php
                                    if ($today_orders_rs[7] > 0) {
                                        ?><button class="btn btn-lg btn-danger col-md-12 pt-3 pb-3 text-left font-weight-bold btnPuyNowCustomerPayment" id="<?php echo "Update". $today_orders_rs[0]; ?>" data-id="<?php echo $today_orders_rs[0]; ?>" data-toggle="modal" data-target="#registerCustomerPaymentModal">
                                            <span class="text-light font-weight-normal" style="font-size: 12px; display: block;">Due: <b><?php echo "$". number_format($today_orders_rs[7], 2); ?></b></span>
                                            <i class="fa fa-credit-card"></i> Pay Now
                                        </button><?php
                                    } else if ($today_orders_rs[7] <= 0) {
                                        ?><button class="btn btn-lg btn-success col-md-12 pt-3 pb-3 text-left font-weight-bold">
                                            <span class="font-weight-normal" style="font-size: 12px; display: block;">Cashier: <b><?php echo $today_orders_rs[8]; ?></b></span>
                                            <i class="fa fa-check"></i> Full Paid
                                        </button><?php
                                    }
                                
                                ?>
                                
                            </td>
                        </tr><?php
                        $count_total_balance += $today_orders_rs[6];
                        $count_total_due_balance += $today_orders_rs[7];
                        $count_total_orders++;
                    }
                ?>
            </tbody>
             <tfoot>
                <tr height="50px">
                    <th class="align-middle text-right" colspan="4"><h5 style="display: inline;">Total Orders</h5></th>
                    <th class="align-middle text-center"><h5 class="text-primary" style="display: inline;"><?php echo $count_total_orders; ?></h5></th>
                    <th class="align-middle text-center"><h5 style="display: inline;">Total</h5></th>
                    <th class="align-middle text-center"><h5 class="text-success" style="display: inline;"><?php echo "$". number_format($count_total_balance, 2); ?></h5></th>
                    <th class="align-middle text-center"><h5 class="text-danger" style="display: inline;"><?php echo "$". number_format($count_total_due_balance, 2); ?></h5></th>
                </tr>
            </tfoot>
        </table>
        <script type="text/javascript"> 
		    $("#ordersOfTodayTable").DataTable({"pageLength": 100, "order": []})
	    </script><?php

	}

	// ================ End of Search Date Based Orders Page =====================================
	
	// ================ Start of Search Date Based Delivery Orders Page ==========================
		
	function search_date_based_delivery_orders($conn) {
		extract($_POST);
		$selected_order_status = mysqli_real_escape_string($conn, $selected_order_status);
		$selected_start_date = mysqli_real_escape_string($conn, $selected_start_date);
		$selected_end_date = mysqli_real_escape_string($conn, date("Y-m-d H:i", strtotime($selected_end_date. " + 1 days")));
		
		?><table class="table table-bordered table-sm display nowrap" id="deliveryOrdersTable">
            <thead>
                <tr class="text-light bg-primary text-center" style="height: 45px;">
                    <th class="align-middle">View</th>
                    <th class="align-middle">Order ID</th>
                    <th class="align-middle" width="25%">Customer Information</th>
                    <th class="align-middle">Order Status</th>
                    <th class="align-middle">Orderer</th>
                    <th class="align-middle">Time</th>
                    <th class="align-middle">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                    $total_in_kitchen = 0;
                    $total_on_the_way = 0;
                    $total_delivered = 0;
                    $total_delivery_orders = 0;
                    if ($selected_order_status == "0") {
                        $fetchCriteria = "WHERE restaurant_orders.orderTypeID = 'OT0003' AND restaurant_orders.orderStatus != '4' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        ORDER BY restaurant_orders.registerDate ASC";
                    } else if ($selected_order_status == "1") {
                        $fetchCriteria = "WHERE restaurant_orders.orderTypeID = 'OT0003' AND restaurant_orders.orderStatus != '4' AND restaurant_orders.orderStatus = '1' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        ORDER BY restaurant_orders.registerDate ASC";
                    } else if ($selected_order_status == "2") {
                        $fetchCriteria = "WHERE restaurant_orders.orderTypeID = 'OT0003' AND restaurant_orders.orderStatus != '4' AND restaurant_orders.orderStatus = '2' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        ORDER BY restaurant_orders.registerDate ASC";
                    } else if ($selected_order_status == "3") {
                        $fetchCriteria = "WHERE restaurant_orders.orderTypeID = 'OT0003' AND restaurant_orders.orderStatus != '4' AND restaurant_orders.orderStatus = '3' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'
                        ORDER BY restaurant_orders.registerDate ASC";
                    }
                    $getDeliveryOrdersList = mysqli_query($conn, "SELECT restaurant_orders.orderID, customers.customerName, customers.customerMobile, restaurant_orders.deliveryAddress, restaurant_orders.orderStatus, employees.employeePhoto, orderer_user.Username, restaurant_orders.registerDate, delivery_employee.employeeName, delivery_employee.employeeMobileNo 'DeliverymanPhone', delivery_registerer.Username
                    FROM restaurant_orders
                    JOIN customers ON restaurant_orders.customerID = customers.customerID
					JOIN system_users orderer_user ON restaurant_orders.registeredBy = orderer_user.userID
                    JOIN employees ON orderer_user.employeeID = employees.employeeID
                    LEFT JOIN employees delivery_employee ON restaurant_orders.deliveredBy = delivery_employee.employeeID
                    LEFT JOIN delivery_orders ON restaurant_orders.orderID = delivery_orders.orderID
                    LEFT JOIN system_users delivery_registerer ON delivery_orders.registeredBy = delivery_registerer.userID
					$fetchCriteria") or die(mysqli_error($conn));
                    while ($delivery_orders_rs = mysqli_fetch_array($getDeliveryOrdersList)) {?>
                        <tr>
                            <td class="align-middle text-center">
                                <?php
									if ($delivery_orders_rs[4] == "1" || $delivery_orders_rs[4] == "3") {
								        ?><span class="bg-success btn-lg text-white pl-2 pt-1 pr-2 pb-1 rounded-lg font-weight-bold btnViewOrderInformation" style="cursor: pointer;" data-id="<?php echo $delivery_orders_rs[0]; ?>" btn-type="View" data-toggle="modal" data-target="#viewAndPrintOrderReceiptModal" title="View Order"><i class="fa fa-eye fa-md"></i></span><?php
									} else if ($delivery_orders_rs[4] == "2") {
									    ?>
									        <span class="bg-success btn-lg text-white pl-2 pt-1 pr-2 pb-1 rounded-lg font-weight-bold btnViewOrderInformation" style="cursor: pointer;" data-id="<?php echo $delivery_orders_rs[0]; ?>" btn-type="View" data-toggle="modal" data-target="#viewAndPrintOrderReceiptModal" title="View Order"><i class="fa fa-eye fa-md"></i></span>
    									    <span class="bg-primary btn-lg text-white pl-2 pt-1 pr-2 pb-1 rounded-lg font-weight-bold btnChangeDeliverymanModal" style="cursor: pointer;" data-id="<?php echo $delivery_orders_rs[0]; ?>" data-toggle="modal" data-target="#changeDeliverymanModal" title="Change Deliveryman"><i class="fa fa-refresh fa-md"></i></span>
									    <?php
									}
								?>
							</td>
                            <td class="align-middle text-center"><span class="text-primary font-weight-bold"><?php echo $delivery_orders_rs[0]; ?></span></td>
                            <td class="align-middle text-left" width="25%">
								<h6><?php echo $delivery_orders_rs[1]. " - ". $delivery_orders_rs[2]; ?></h6>
								<h6>Address: <span class="font-weight-normal"><?php echo $delivery_orders_rs[3]; ?></span></h6>
								<?php
								    if ($delivery_orders_rs[8] != "") {
								        ?><h6>Deliveryman: <br /><span class="font-weight-normal"><?php echo $delivery_orders_rs[8]. " <b>- ". $delivery_orders_rs[9] ."</b>"; ?></span></h6><?php
								    }
						        ?>
							</td>
                            <td class="align-middle text-center">
							    <?php
									if ($delivery_orders_rs[4] == "1") {
										?><h6 class="bg-primary text-white text-center p-2 rounded-lg col-md-10"><i class='fa fa-spinner fa-pulse fa-lg'></i> &nbsp; In Kitchen</h6><?php
										$total_in_kitchen += 1;
									} else if ($delivery_orders_rs[4] == "2") {
										?><h6 class="bg-dark text-white text-center p-2 rounded-lg col-md-10"><i class='fa fa-motorcycle fa-lg'></i> &nbsp; On the way</h6><?php
										$total_on_the_way += 1;
									} else if ($delivery_orders_rs[4] == "3") {
										?><h6 class="bg-success text-white text-center p-2 rounded-lg col-md-10"><i class='fa fa-check fa-lg'></i> &nbsp; Delivered</h6><?php
										$total_delivered += 1;
									}
								?>
							</td>
                            <td class="align-middle text-left"><img class="img-fluid rounded-circle pr-2" src="<?php echo $delivery_orders_rs[5]; ?> " width="40px" height="40px"/><?php $waiter_name = explode(" ", $delivery_orders_rs[6]); echo $waiter_name[0]; ?></td>
                            <td class="align-middle text-left font-weight-bold"><?php echo date('d F', strtotime($delivery_orders_rs[7])). "<br />" .date('h:i A', strtotime($delivery_orders_rs[7])); ?></td>
                            <td class="align-middle text-center">
                                <?php
									if ($delivery_orders_rs[4] == "1") {
                                        ?><button class="btn btn-lg btn-primary col-md-9 pt-3 pb-3 text-left font-weight-bold btnDeliverNowWaitingDeliveries" id="<?php echo "Update". $delivery_orders_rs[0]; ?>" data-id="<?php echo $delivery_orders_rs[0]; ?>" data-toggle="modal" data-target="#registerDeliveryOrderModal"><i class="fa fa-send"></i>Deliver Now</button><?php
									} else if ($delivery_orders_rs[4] == "2") {
                                        ?><button class="btn btn-lg btn-warning col-md-9 pt-3 pb-3 text-left font-weight-bold btnCompleteNowWaitingDeliveries" id="<?php echo "Complete". $delivery_orders_rs[0]; ?>" data-id="<?php echo $delivery_orders_rs[0]; ?>"><i class="fa fa-hourglass-1"></i>Complete Now</button><?php
									} else if ($delivery_orders_rs[4] == "3") {
									    ?>
                                            <button class="btn btn-lg btn-success col-md-9 pt-3 pb-3 text-left font-weight-bold">
                                                <span class="font-weight-normal" style="font-size: 12px; display: block;">Processed: <b><?php echo $delivery_orders_rs[10]; ?></b></span>
                                                <i class="fa fa-check fa-2x"></i>Delivered
                                            </button>
                                        <?php
									}
								?>
                            </td>
                        </tr><?php
                        $total_delivery_orders += 1;
                    }
                ?>
            </tbody>
            <tfoot>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td class="align-middle text-center pt-4 pb-3"><h4 class="text-primary">In Kitchen<br /><span class="text-dark"><?php echo $total_in_kitchen; ?></span></h4></td>
                    <td class="align-middle text-center pt-4 pb-3"><h4 class="text-warning">On the way<br /><span class="text-dark"><?php echo $total_on_the_way; ?></span></h4></td>
                    <td class="align-middle text-center pt-4 pb-3"><h4 class="text-success">Delivered<br /><span class="text-dark"><?php echo $total_delivered; ?></span></h4></td>
                    <td class="align-middle text-center pt-4 pb-3"><h4 class="text-dark">Total<br /><span class="text-dark"><?php echo $total_delivery_orders; ?></span></h2></h4>
                </tr>
            </tfoot>
        </table>
		
        <script type="text/javascript"> 
		    $("#deliveryOrdersTable").DataTable({"pageLength": 100, "order": []})
	    </script><?php

	}

	// ================ End of Search Date Based Delivery Orders Page ============================

	// ================ START OF CANCEL AND REMOVE ORDER ADMIN POS MODULE ========================
	
	// Cancel Order Now
	// Status 4 = Cancelled
	function cancel_restaurant_order_now($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$order_cance_purpose = mysqli_real_escape_string($conn, $cancel_purpose);

		// Cancel Order Now
		$cancel_order_now = mysqli_query($conn, "INSERT INTO cancelled_orders (orderID, reasonForCancel, cancelledBy, cancelDate) VALUES ( '". $selected_order_id ."', '". $order_cance_purpose ."',  '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')");
        if ($cancel_order_now) {
            $update_main_order = mysqli_query($conn, "UPDATE restaurant_orders SET orderStatus = '4' WHERE orderID = '". $selected_order_id ."'") or die(mysqli_error($conn));
    		if ($update_main_order) {
    		    $getAssociatedPayment = mysqli_query($conn, "SELECT paymentID FROM customer_payments WHERE orderID = '". $selected_order_id ."'");
        		if ($getAssociatedPayment) {
        		    if (mysqli_num_rows($getAssociatedPayment) > 0) {
        		        while ($assoc_pay = mysqli_fetch_array($getAssociatedPayment)) mysqli_query($conn, "DELETE FROM account_transactions WHERE referenceID = '". $assoc_pay[0] ."'") or die(mysqli_error($conn));
        		    }
        		} else {
        		    $errorList[] = mysqli_error($conn);
        			$data = json_encode(array('Status' => false, 'Message' => $errorList));
        		}
        		mysqli_query($conn, "DELETE FROM customer_payments WHERE orderID = '". $selected_order_id ."'") or die(mysqli_error($conn));
    			$successMsg = "Order has been cancelled successfully";
    			$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));
        }
		
		echo $data;
	}
	
	// Delete Order Now
	function delete_cancelled_order_permenantly($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);

		// Delete Order Now
		$delete_order_now = mysqli_query($conn, "DELETE FROM cancelled_orders WHERE orderID = '". $selected_order_id ."'");
        if ($delete_order_now) {
            $delete_main_order = mysqli_query($conn, "DELETE FROM restaurant_orders WHERE orderID = '". $selected_order_id ."' AND orderStatus = '4'") or die(mysqli_error($conn));
    		if ($delete_main_order) {
        		$successMsg = "Order has been deleted successfully";
    			$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));
        }
		
		echo $data;
	}

	// ================ END OF CANCEL AND REMOVE ORDER ADMIN POS MODULE ==========================


	// ================ START OF CUSTOMER PAYMENT MODULE =========================================
	
	// Fetch Order Information
	function fetch_order_information($conn) {
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$getOrderInformation = mysqli_query($conn, "SELECT restaurant_orders.orderID, customers.customerID, customers.customerName, customers.customerMobile, order_types.orderTypeName, employees.employeePhoto, employees.employeeName, restaurant_orders.registerDate, ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount'
		FROM restaurant_orders
		JOIN customers ON restaurant_orders.customerID = customers.customerID
		JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID
		LEFT JOIN employees ON restaurant_orders.servedBy = employees.employeeID
		LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
		WHERE restaurant_orders.orderID = '$selected_order_id'") or die(mysqli_error($conn));
		if ($getOrderInformation) {
			if (mysqli_num_rows($getOrderInformation) > 0) {
				$order_info_rs = mysqli_fetch_array($getOrderInformation);
				?><div class="row">
					<div class="col-md-2">
						<h6>Order ID</h6>
						<h6 class="font-weight-normal" id="txtOrderIddRegisterCustomerPayment"><?php echo $order_info_rs[0]; ?></h6>
					</div>
					<div class="col-md-4">
						<h6>Customer Name</h6>
						<h6 class="font-weight-normal" id="txtCustomerIddRegisterCustomerPayment" customer-id="<?php echo $order_info_rs[1]; ?>"><?php echo $order_info_rs[2]; ?></h6>
					</div>
					<?php
						if ($order_info_rs[4] == "Delivery") {
							?><div class="col-md-2">
								<h6>Mobile</h6>
						        <h6 class="font-weight-normal"><?php echo $order_info_rs[3]; ?></h6>
							</div><?php
						}
					?>
					<div class="col-md-2">
						<h6>Order Type</h6>
						<h6 class="font-weight-normal">
							<?php 
								if ($order_info_rs[4] == "Seat In") {
									?><h6 class="font-weight-normal text-success"><i class='fa fa-hotel'></i> <?php echo $order_info_rs[4]; ?></h6><?php
								} else if ($order_info_rs[4] == "Take Away") {
									?><h6 class="font-weight-normal text-primary"><i class='fa fa-shopping-basket'></i> <?php echo $order_info_rs[4]; ?></h6><?php
								} else if ($order_info_rs[4] == "Delivery") {
									?><h6 class="font-weight-normal text-danger"><i class='fa fa-motorcycle'></i> <?php echo $order_info_rs[4]; ?></h6><?php
								}
							?>
						</h6>
					</div>
					<?php
						if ($order_info_rs[4] != "Delivery") {
						    ?><div class="col-md-3">
								<h6>Served Waiter</h6>
								<h6 class="font-weight-normal"><img class="img-fluid rounded-circle pr-2" src="<?php echo $order_info_rs[5]; ?> " width="35px" height="35px"/><?php $waiter_name = explode(" ", $order_info_rs[6]); echo $waiter_name[0]; ?></h6>
							</div><?php
						}
					?>
					<div class="col-md-3 mt-3">
						<h6>Order Date</h6>
						<h6 class="font-weight-normal"><?php echo substr($order_info_rs[7], 0, 16); ?></h6>
					</div>
					<div class="col-md-3 mt-3">
						<h6>Order Balance</h6>
						<h6 class="text-success"><?php echo "$". number_format($order_info_rs[8], 2); ?></h6>
					</div>	
				</div><?php
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Order Not Found</h5>
					</div>
				</div><?php
			}
		}
	}

	//Register Customer Payment
	function register_customer_payment($conn) {
		global $errorList;
		$payment_details = array();
		$data = array();
		extract($_POST);

		$deposit_accounts_list = $deposit_accounts_list_customer_payment;
		foreach($deposit_accounts_list as $payment_information) {
			if ($payment_information[0] == "") {$payment_details = array('paymentStatus' => false, 'paymentMessage' => 'Select Account'); break;}
			else if ($payment_information[1] == "") {$payment_details = array('paymentStatus' => false, 'paymentMessage' => 'Enter Paid Amount'); break;}
			else if ($payment_information[2] == "") {$payment_details = array('paymentStatus' => false, 'paymentMessage' => 'Enter Description'); break;}
			else $payment_details = array('paymentStatus' => true, 'paymentMessage' => 'Account details are ok');
		}

		if ($selected_order_id == "") {
			$errorList[] = "Please select an order";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if (isset($payment_details['paymentStatus']) && $payment_details['paymentStatus'] == false) {
			$errorList[] = $payment_details['paymentMessage'];
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			// Fetch Order Balance
			$getOrderBalance = mysqli_query($conn, "SELECT restaurant_orders.orderID, restaurant_orders.orderVAT 'OrderVAT', ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount'
			FROM restaurant_orders
			LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
			WHERE restaurant_orders.orderID = '$selected_order_id'");
			if ($getOrderBalance) {
				if (mysqli_num_rows($getOrderBalance) > 0) {
					$order_balace_rs = mysqli_fetch_array($getOrderBalance);
					// Compare order balance with paid amount
					if (($total_customer_paid_amount > $order_balace_rs[2]) || ($total_customer_paid_amount < 0.01)) {
						$errorList[] = "Check Total Paid Amount";
						$data = json_encode(array('Status' => false, 'Message' => $errorList));
					} else {
						// Register the payments now
						foreach($deposit_accounts_list as $payment_info) {
							//Generate New ID for the current inserted customer payment ....
							$getMaxCustomerPaymentID = mysqli_query($conn, "SELECT MAX(rowNo) FROM customer_payments") or die(mysqli_error($conn));
							if (mysqli_num_rows($getMaxCustomerPaymentID) > 0) {
								$maxCustomerPaymentID = mysqli_fetch_array($getMaxCustomerPaymentID);
								$curCustomerPaymentID = $maxCustomerPaymentID[0] + 1;
								$generatedCustomerPaymentID = "CPY" . sprintf("%04d", $curCustomerPaymentID);
							} else {
								$curCustomerPaymentID = 1;
								$generatedCustomerPaymentID = "CPY" . sprintf("%04d", $curCustomerPaymentID);
							}
							$register_payment_now = mysqli_query($conn, "INSERT INTO customer_payments(paymentID, orderID, customerID, accountNoID, paidAmount, paymentDescription, registeredBy, registerDate, updatedBy, updateDate) VALUES ('". mysqli_real_escape_string($conn, $generatedCustomerPaymentID) ."', '". mysqli_real_escape_string($conn, $selected_order_id) ."', '". mysqli_real_escape_string($conn, $selected_customer_id) ."', '". mysqli_real_escape_string($conn, $payment_info[0]) ."', '". mysqli_real_escape_string($conn, $payment_info[1]) ."', '". mysqli_real_escape_string($conn, (($payment_info[2] == "") ? "-" : $payment_info[2])) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."', '-', '-')");
							if ($register_payment_now) {
							    
							    // First Insert the Payment into Account Transactions
							    
								//Generate New ID for the current inserted account 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);
								}
								$registerAccountTransaction = mysqli_query($conn, "INSERT INTO account_transactions VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedTransactionID) . "', '" . mysqli_real_escape_string($conn, $payment_info[0]) . "', '0', '" . mysqli_real_escape_string($conn, $payment_info[1]) . "', '" . mysqli_real_escape_string($conn, $generatedCustomerPaymentID) . "', '" . mysqli_real_escape_string($conn, $payment_info[2]) . "', '1', '". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
								if ($registerAccountTransaction) {
								     
								    // Second Deduct the VAT Tax into Account Transactions
								    
								    if ($payment_info[0] != "ACC0002" && $payment_info[0] != "ACC0007" && $payment_info[0] != "ACC0008" && $payment_info[0] != "ACC0010" && $payment_info[0] != "ACC0011" && $payment_info[0] != "ACC0012") {
								        //Generate New ID for the current inserted account 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) . "', '" . mysqli_real_escape_string($conn, $payment_info[0]) . "', '". mysqli_real_escape_string($conn, $order_balace_rs[1]) ."', '0', '" . mysqli_real_escape_string($conn, $generatedCustomerPaymentID) . "', '" . mysqli_real_escape_string($conn, "VAT-".$order_balace_rs[0]) . "', '1', '". mysqli_real_escape_string($conn, $_SESSION['userIdd']) ."', '". date("Y-m-d H:i") ."', '-', '-')") or die(mysqli_error($conn));
								    }
    							
								} 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));
							}
						}
						$successMsg = $selected_order_id. "####Payment has been registered successfully";
						$data = json_encode(array('Status' => true, 'Message' => $successMsg));
					}
				}
			} else {
				$errorList[] = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		}

		echo $data;
	}

	// ================ END OF CUSTOMER PAYMENT MODULE ===========================================	

	// ================ START OF WAITING DELIVERIES MODULE =======================================

	// Fetch Delivery Order Information
	function fetch_delivery_order_information($conn) {
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$getOrderInformation = mysqli_query($conn, "SELECT restaurant_orders.orderID, customers.customerID, customers.customerName, customers.customerMobile, restaurant_orders.deliveryAddress, employees.employeePhoto, employees.employeeName, restaurant_orders.registerDate, ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount'
		FROM restaurant_orders
		JOIN customers ON restaurant_orders.customerID = customers.customerID
		JOIN system_users ON restaurant_orders.registeredBy = system_users.userID
		JOIN employees ON system_users.employeeID = employees.employeeID
		LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
		WHERE restaurant_orders.orderID = '$selected_order_id'") or die(mysqli_error($conn));
		if ($getOrderInformation) {
			if (mysqli_num_rows($getOrderInformation) > 0) {
				$order_info_rs = mysqli_fetch_array($getOrderInformation);
				?><div class="row">
					<div class="col-md-2">
						<h6>Order ID</h6>
						<h6 class="font-weight-normal" id="txtOrderIddDeliverOrderNow"><?php echo $order_info_rs[0]; ?></h6>
					</div>
					<div class="col-md-5">
						<h6>Customer Name</h6>
						<h6 class="font-weight-normal" id="txtCustomerIddDeliverOrderNow" customer-id="<?php echo $order_info_rs[1]; ?>"><?php echo $order_info_rs[2]. " - <b>". $order_info_rs[3] ."</b>"; ?></h6>
					</div>	
					<div class="col-md-5">
						<h6>Delivery Address</h6>
						<h6 class="font-weight-normal" id="txtDeliveryAddressDeliverOrderNow"><?php echo $order_info_rs[4]; ?></h6>
					</div>	
				</div>
				<div class="row mt-2">
					<div class="col-md-3">
						<h6>Orderer</h6>
						<h6 class="font-weight-normal"><img class="img-fluid rounded-circle" src="<?php echo $order_info_rs[5]; ?>" width="30px" height="30px"/><?php $waiter_name = explode(" ", $order_info_rs[6]); echo " ". $waiter_name[0]; ?></h6>
					</div>
					<div class="col-md-3">
						<h6>Order Date</h6>
						<h6 class="font-weight-normal"><?php echo substr($order_info_rs[7], 0, 16); ?></h6>
					</div>
					<div class="col-md-3">
						<h6>Order Balance</h6>
						<h6 class="text-success"><?php echo "$". number_format($order_info_rs[8], 2); ?></h6>
					</div>	
				</div><?php
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Order Not Found</h5>
					</div>
				</div><?php
			}
		}
	}

	// Register Deliver Order
	function register_deliver_waiting_order($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$selected_delivery_address = mysqli_real_escape_string($conn, $selected_delivery_address);
		$selected_deliveryman_id = mysqli_real_escape_string($conn, $selected_deliveryman_id);
		if ($selected_order_id == "") {
			$errorList[] = "Please select an order";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if ($selected_delivery_address == "") {
			$errorList[] = "Enter delivery address";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if ($selected_deliveryman_id == "-") {
			$errorList[] = "Please select delivery man";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			// Register Deliver Now
			$register_deliver_order_now = mysqli_query($conn, "INSERT INTO delivery_orders(orderID, deliveredBy, deliveryAddress, deliveryStatus, registeredBy, registerDate, updatedBy, updateDate) VALUES ('". mysqli_real_escape_string($conn, $selected_order_id) ."', '". mysqli_real_escape_string($conn, $selected_deliveryman_id) ."', '". mysqli_real_escape_string($conn, $selected_delivery_address) ."', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."', '-', '-')");
			if ($register_deliver_order_now) {
				$update_main_order_now = mysqli_query($conn, "UPDATE restaurant_orders SET orderStatus = '2', deliveredBy = '". mysqli_real_escape_string($conn, $selected_deliveryman_id) ."', deliveryAddress = '". mysqli_real_escape_string($conn, $selected_delivery_address) ."' WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
				if ($register_deliver_order_now) {
					$successMsg = "Order has been submitted for delivery";
					$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));
			}
		}
		echo $data;
	}
	
	// Complete Delivery Order Now - Delivery Orders
	function complete_delivery_order_now($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);

		// Complete Delivery Order Now
		$complete_delivery_order_now = mysqli_query($conn, "UPDATE restaurant_orders SET orderStatus = '3' WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
		if ($complete_delivery_order_now) {
			$successMsg = "Order has been delivered successfully";
			$data = json_encode(array('Status' => true, 'Message' => $successMsg));
		} else {
			$errorList[] = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		}
		
		echo $data;
	}
	
	// Fetch Delivery and Deliveryman Information
	function fetch_delivery_and_deliveryman_information($conn) {
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$getOrderInformation = mysqli_query($conn, "SELECT restaurant_orders.orderID, customers.customerID, customers.customerName, customers.customerMobile, restaurant_orders.deliveredBy, restaurant_orders.deliveryAddress, employees.employeePhoto, employees.employeeName, restaurant_orders.registerDate, ROUND(IFNULL(restaurant_orders.totalAmount, 0) - IFNULL(SUM(customer_payments.paidAmount), 0), 2) 'UnpaidAmount'
		FROM restaurant_orders
		JOIN customers ON restaurant_orders.customerID = customers.customerID
		JOIN system_users ON restaurant_orders.registeredBy = system_users.userID
		JOIN employees ON system_users.employeeID = employees.employeeID
		LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
		WHERE restaurant_orders.orderID = '$selected_order_id'") or die(mysqli_error($conn));
		if ($getOrderInformation) {
			if (mysqli_num_rows($getOrderInformation) > 0) {
				$order_info_rs = mysqli_fetch_array($getOrderInformation);
				?><div class="tile mb-3">
				    <div class="row">
    					<div class="col-md-2">
    						<h6>Order ID</h6>
    						<h6 class="font-weight-normal" id="txtOrderIddChangeDeliveryman"><?php echo $order_info_rs[0]; ?></h6>
    					</div>
    					<div class="col-md-5">
    						<h6>Customer Name</h6>
    						<h6 class="font-weight-normal" customer-id="<?php echo $order_info_rs[1]; ?>"><?php echo $order_info_rs[2]. " - <b>". $order_info_rs[3] ."</b>"; ?></h6>
    					</div>	
    					<div class="col-md-5">
    						<h6>Delivery Address</h6>
    						<h6 class="font-weight-normal"><?php echo $order_info_rs[5]; ?></h6>
    					</div>	
    				</div>
    				<div class="row mt-2">
    					<div class="col-md-3">
    						<h6>Orderer</h6>
    						<h6 class="font-weight-normal"><img class="img-fluid rounded-circle" src="<?php echo $order_info_rs[6]; ?>" width="30px" height="30px"/><?php $waiter_name = explode(" ", $order_info_rs[7]); echo " ". $waiter_name[0]; ?></h6>
    					</div>
    					<div class="col-md-3">
    						<h6>Order Date</h6>
    						<h6 class="font-weight-normal"><?php echo substr($order_info_rs[8], 0, 16); ?></h6>
    					</div>
    					<div class="col-md-3">
    						<h6>Order Balance</h6>
    						<h6 class="text-success"><?php echo "$". number_format($order_info_rs[9], 2); ?></h6>
    					</div>	
    				</div>
    			</div>
    		    <div class="tile mb-3">
					<div class="row">
						<div class="col-md-12 pb-2 font-weight-bold">
							<h5>Pick Deliveryman </h5>
						</div>
					</div>
					<div class="row">
						<?php
							$fetchCriteria = "WHERE employeePosition = 'PS0007' AND employeeStatus = '1'";
							$getDeliveryMen = mysqli_query($conn, "SELECT employeeID, employeeName, employeePhoto
							FROM employees
							$fetchCriteria
							ORDER BY employeeName ASC") or die(mysqli_error($conn));
							if ($getDeliveryMen) {
								if (mysqli_num_rows($getDeliveryMen) > 0) {
									while ($deliverymen_rs = mysqli_fetch_array($getDeliveryMen)) {
									    if ($deliverymen_rs[0] == $order_info_rs[4]) { ?>
    										<div class="col-md-2 mb-3 text-center">
    											<div class="custom-control custom-checkbox image-checkbox">
    												<input type="checkbox" checked class="custom-control-input cbxDeliveryManChangeDeliveryman" id="<?php echo $deliverymen_rs[0]. "_1"; ?>" current-selected-deliverymen-id="<?php echo $deliverymen_rs[0] ?>">
    												<label class="custom-control-label pb-2" for="<?php echo $deliverymen_rs[0]. "_1"; ?>">
    													<img src="<?php echo $deliverymen_rs[2] ?>" alt="#" class="img-fluid">
    												</label>
    												
    												<span><?php $get_name = explode(" ", $deliverymen_rs[1]); echo $get_name[0]; ?></span>
    											</div>
    										</div><?php
									    } else { ?>
									        <div class="col-md-2 mb-3 text-center">
    											<div class="custom-control custom-checkbox image-checkbox">
    												<input type="checkbox" class="custom-control-input cbxDeliveryManChangeDeliveryman" id="<?php echo $deliverymen_rs[0]. "_1"; ?>" current-selected-deliverymen-id="<?php echo $deliverymen_rs[0] ?>">
    												<label class="custom-control-label pb-2" for="<?php echo $deliverymen_rs[0]. "_1"; ?>">
    													<img src="<?php echo $deliverymen_rs[2] ?>" alt="#" class="img-fluid">
    												</label>
    												
    												<span><?php $get_name = explode(" ", $deliverymen_rs[1]); echo $get_name[0]; ?></span>
    											</div>
    										</div><?php
									    }
									}
								} else {
									?><div class="row">
										<div class="col-md-12">
											<h6>Deliveryman Not Found</h6>
										</div>
									</div><?php
								}
							} else {
								?><div class="row">
									<div class="col-md-12">
										<p><?php echo mysqli_error($conn); ?></p>
									</div>
								</div><?php
							}
						?>
					</div>
				</div><?php
			} else {
				?><div class="tile mb-3">
				    <div class="row">
    					<div class="col-md-12 text-center">
    						<h5 class="text-danger">Order Not Found</h5>
    					</div>
    				</div>
    			</div><?php
			}
		}
	}
	
	// Change Deliveryman - Delivery Order
	function change_deliveryman_delivery_order($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$selected_order_id = mysqli_real_escape_string($conn, $selected_order_id);
		$selected_deliveryman_id = mysqli_real_escape_string($conn, $selected_deliveryman_id);
		if ($selected_order_id == "") {
			$errorList[] = "Please select an order";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if ($selected_deliveryman_id == "-") {
			$errorList[] = "Please select delivery man";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			// Register Deliver Now
			$register_deliver_order_now = mysqli_query($conn, "UPDATE delivery_orders SET deliveredBy = '". mysqli_real_escape_string($conn, $selected_deliveryman_id) ."', updatedBy = '". $_SESSION['userIdd'] ."', updateDate = '". date("Y-m-d H:i:s") ."' WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'");
			if ($register_deliver_order_now) {
				$update_main_order_now = mysqli_query($conn, "UPDATE restaurant_orders SET deliveredBy = '". mysqli_real_escape_string($conn, $selected_deliveryman_id) ."' WHERE orderID = '". mysqli_real_escape_string($conn, $selected_order_id) ."'") or die(mysqli_error($conn));
				if ($register_deliver_order_now) {
					$successMsg = "Deliveryman has been changedsuccessfully";
					$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));
			}
		}
		echo $data;
	}
	
	// ================ END OF WAITING DELIVERIES MODULE =========================================

	

	// ================ START OF WAITER POS MODULE ===============================================

	// Fetch Restaurant Products by Category - Waiter POS Page
	function fetch_restaurant_products_by_category_waiter_pos($conn) {
		extract($_POST);
		$category_id_waiter_pos = mysqli_real_escape_string($conn, $category_id_waiter_pos);

		$fetch_criteria = ($category_id_waiter_pos == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_waiter_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
		$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";

		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));

		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductWaiterPOSPageArea" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?><div class="row">
					<div class="col-md-12 text-center">
						<h5 class="text-danger">Products Not Found</h5>
					</div>
				</div><?php
			}
		}

	}
	
	// Search Restaurant Product Live - Waiter POS Page
	function search_restaurant_product_live_waiter_pos($conn) {
		extract($_POST);
		$searched_product_name = mysqli_real_escape_string($conn, $searched_product_name);
		$category_id_waiter_pos = mysqli_real_escape_string($conn, $category_id_waiter_pos);

		if ($searched_product_name == "") $fetch_criteria = ($category_id_waiter_pos == "All") ? "WHERE (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.categoryID = '". $category_id_waiter_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
		else $fetch_criteria = ($category_id_waiter_pos == "All") ? "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1" : "WHERE restaurant_products.productName LIKE '%". $searched_product_name ."%' AND restaurant_products.categoryID = '". $category_id_waiter_pos ."' AND (restaurant_products.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_products.workingAreaID = 'WAR0001') AND restaurant_products.productStatus = 1";
		$restaurantProducts = "SELECT restaurant_products.productID, restaurant_products.productName, restaurant_products.productPrice, restaurant_products.productStatus, restaurant_products.productPhoto FROM restaurant_products $fetch_criteria ORDER BY restaurant_products.productName ASC";

		$getCategoryProducts = mysqli_query($conn, $restaurantProducts) or die(mysqli_error($conn));
		
		if ($getCategoryProducts) {
			if (mysqli_num_rows($getCategoryProducts) > 0) {
				while ($category_products_rs = mysqli_fetch_array($getCategoryProducts)) { ?>
					<div class="col-md-3 mt-2 mb-3">
						<div class="bs-component mt-2 mb-3 singleProductWaiterPOSPageArea" style="cursor: pointer;" product-id="<?php echo $category_products_rs[0]; ?>" product-name="<?php echo $category_products_rs[1]; ?>" product-price="<?php echo $category_products_rs[2]; ?>">
							<div class="card rounded-lg">
								<img class="rounded-top rounded-lg" style="height: 140px; width: 100%; display: block;" src="<?php echo $category_products_rs[4]; ?>" alt="Card image">
								<div class="card-body">
									<div class="row">
										<div class="col-md-12">
											<h5 class="text-primary text-center font-weight-normal">
												<?php echo $category_products_rs[1]; ?>
												<span class="text-success font-weight-bold mt-1" style="display: block"><?php echo "$". number_format($category_products_rs[2], 2); ?></span>
											</h5>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div><?php
				}
			} else {
				?></div>
				<div class="col-md-12 text-center">
					<h5 class="text-danger font-weight-normal">Product Not Found</h5>
				</div><?php
			}
		}

	}

	// Register Restaurant Order - Waiter POS Page
	function register_restaurant_order_waiter_pos_page($conn) {
		global $errorList;
		$data = array();
		extract($_POST);
		$ordered_products_list = $checked_order_products_list;

		if (isset($ordered_products_list["productsStatus"]) && $ordered_products_list["productsStatus"] == "false") {
			$errorList[] = $ordered_products_list["productsMessage"];
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if ($selected_customer_id == "RegisterNewCustomer") {
			$errorList[] = "Please select customer";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {

			//Generate New ID for the current inserted order ....
			$getMaxRestaurantOrderID = mysqli_query($conn, "SELECT MAX(rowNo) FROM restaurant_orders") or die(mysqli_error($conn));
			if (mysqli_num_rows($getMaxRestaurantOrderID) > 0) {
				$maxRestaurantOrderID = mysqli_fetch_array($getMaxRestaurantOrderID);
				$curRestaurantOrderID = $maxRestaurantOrderID[0] + 1;
				$generatedRestaurantOrderID = "ORD" . sprintf("%04d", $curRestaurantOrderID);
			} else {
				$curRestaurantOrderID = 1;
				$generatedRestaurantOrderID = "ORD" . sprintf("%04d", $curRestaurantOrderID);
			}
			$register_restaurant_order_now = mysqli_query($conn, "INSERT INTO restaurant_orders(orderID, customerID, orderTypeID, workingAreaID, kitchenNote, orderSubtotal, orderDiscount, orderVAT, totalAmount, tableID, servedBy, orderStatus, deliveredBy, deliveryAddress, registeredBy, registerDate, updatedBy, updateDate) VALUES ('". mysqli_real_escape_string($conn, $generatedRestaurantOrderID) ."','". mysqli_real_escape_string($conn, $selected_customer_id) ."', '". mysqli_real_escape_string($conn, $selected_order_type) ."', '". $_SESSION['workingAreaID'] ."', '". mysqli_real_escape_string($conn, $kitchen_note_descript) ."', '". mysqli_real_escape_string($conn, $order_subtotal_amount) ."', '0.00', '". mysqli_real_escape_string($conn, $order_true_vat_amount) ."', '". mysqli_real_escape_string($conn, $order_total_amount) ."', '-', '". mysqli_real_escape_string($conn, $_SESSION['waiterIdd']) ."','1', '-', '-', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."', '-', '-')");
			if ($register_restaurant_order_now) {
				foreach ($ordered_products_list["productsMessage"] as $product) {
					mysqli_query($conn, "INSERT INTO order_products_list (productID, Quantity, productPrice, totalPrice, orderID, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, $product[1]) ."', '". mysqli_real_escape_string($conn, $product[2]) ."', '". mysqli_real_escape_string($conn, $product[3]) ."', '". mysqli_real_escape_string($conn, $generatedRestaurantOrderID) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
					mysqli_query($conn, "INSERT INTO kitchen_orders_list (productID, Quantity, orderID, orderLevel, registeredBy, registerDate) VALUES ('". mysqli_real_escape_string($conn, $product[0]) ."', '". mysqli_real_escape_string($conn, $product[1]) ."', '". mysqli_real_escape_string($conn, $generatedRestaurantOrderID) ."', '1', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."')") or die(mysqli_error($conn));
				}
				$data = json_encode(array('Status' => true, 'Message' => $generatedRestaurantOrderID));
			} else {
				$errorList[] = mysqli_error($conn);
				$data = json_encode(array('Status' => false, 'Message' => $errorList));
			}
		}

		echo $data;
	}

	// ================ END OF WAITER POS MODULE =================================================

	// ================ START OF WAITER CHANGE PASSWORD MODULE ===================================
	function change_waiter_password($conn) {
		global $ereyFure;
		global $errorList;

		$data = array();
		extract($_POST);
		$weak_passcode_list = array("123456", "123123", "654321", "000000", "111111", "222222", "333333", "444444", "555555", "666666", "777777", "888888", "999999", "001122", "112233", "223344", "334455", "445566", "556677", "66778899", "778899", "889900", "000111", "111222", "222333", "333444", "444555", "555666", "666777", "777888", "888999", "999000");

		if ($waiter_new_password != $waiter_confirm_password) {
			$errorList[] = "Confirm passcode failed";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if (strlen($waiter_new_password) < 6) {
			$errorList[] = "Passcode must be at least six digits";
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else if (in_array($waiter_new_password, $weak_passcode_list)) {
			$errorList[] = "Passcode is so weak, try another";
			$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 = $waiter_old_password;
					$user_stored_enc_pass = $user_pass_details[4];
					$stored_dec_password = kuceliAsalka($user_stored_enc_pass, $ereyFure);
					if ($entered_user_password === $stored_dec_password) {
						$changePassword = mysqli_query($conn, "UPDATE system_users SET Passcode = '" . mysqli_real_escape_string($conn, bedelXogta($waiter_new_password, $ereyFure)) . "' WHERE userID = '" . $_SESSION['userIdd'] . "'");
						if ($changePassword) {
							$data = json_encode(array('Status' => true, 'Message' => 'Passcode has been changed successfully'));
						} else {
							$errorMsg = mysqli_error($conn);
							$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
						}
					} else {
						$errorList[] = "Current passcode is incorrect";
						$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 WAITER CHANGE PASSWORD MODULE =====================================


	// ================ START OF SYSTEM REPORTS MODULE ===========================================

	// Fill Order Report Parameter Types
	function fill_order_report_parameter_type($conn) {
		$returned_data = array();
		$data = array();
		extract($_POST);
		$selected_report_type = mysqli_real_escape_string($conn, $selected_report_type);
		if ($selected_report_type == "generalReport") {
			$getReportType = "";
		} else if ($selected_report_type == "orderType") {
			$getReportType = "SELECT order_types.orderTypeID, order_types.orderTypeName FROM order_types";
		} else if ($selected_report_type == "categoryID") {
			$getReportType = "SELECT restaurant_categories.categoryID, restaurant_categories.categoryName FROM restaurant_categories";
		} else if ($selected_report_type == "productID") {
			$getReportType = "SELECT restaurant_products.productID, restaurant_products.productName FROM restaurant_products";
		} else if ($selected_report_type == "servedBy") {

		} else if ($selected_report_type == "registeredBy") {

		}

		$reportTypeQuery = mysqli_query($conn, $getReportType) or die(mysqli_error($conn));
		if ($reportTypeQuery) {
			if (mysqli_num_rows($reportTypeQuery) > 0) {
				while ($row = mysqli_fetch_array($reportTypeQuery)) {
					$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;
	}
	
	
	// ================ Start of General Order Report ============================================
	
	// General Report
	function restaurant_general_report($conn) {
		extract($_POST);
		$selected_date_type = mysqli_real_escape_string($conn, $selected_date_type);
		$selected_start_date = mysqli_real_escape_string($conn, $selected_start_date);
		$selected_end_date = mysqli_real_escape_string($conn, $selected_end_date);
		
		if ($selected_date_type == "1") {
		    $selected_start_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		    $selected_end_date = date("Y-m-d H:i");
		} else if ($selected_date_type == "2") {
		    $selected_start_date = (date("H") > 6) ? date('Y-m-d 06:00', strtotime("-1 days")) : date('Y-m-d 06:00', strtotime("-2 days"));
		    $selected_end_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		} else if ($selected_date_type == "11") {
            // $selected_end_date = date("Y-m-d H:i");
		}

		$fetch_criteria = ($selected_date_type == "0") ? "WHERE restaurant_orders.orderStatus != '4'" : "WHERE restaurant_orders.orderStatus != '4' AND restaurant_orders.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'";
		$fetch_criteria_cashiers = ($selected_date_type == "0") ? "" : "WHERE customer_payments.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'";
		$fetch_criteria_accounts = ($selected_date_type == "0") ? "" : "WHERE account_transactions.registerDate BETWEEN '". $selected_start_date ."' AND '". $selected_end_date ."'";

		?><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="printGeneralReport"><i class="fa fa-print"></i> Print </button><br /><br />
					</div>
				</div>
				<div class="row" style="margin-left: 0px; margin-right: 0px;" id="generalReportPrintArea">
					<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">General 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 7 Days";
											$report_start_date = $selected_start_date;
											$report_end_date = $selected_end_date;
										} else if ($selected_date_type == 6) {
											$date_type_label = "Last 10 Days";
											$report_start_date = $selected_start_date;
											$report_end_date = $selected_end_date;
										} else if ($selected_date_type == 7) {
											$date_type_label = "This Month";
											$report_start_date = $selected_start_date;
											$report_end_date = $selected_end_date;
										} else if ($selected_date_type == 8) {
											$date_type_label = "Last Month";
											$report_start_date = $selected_start_date;
											$report_end_date = $selected_end_date;
										} else if ($selected_date_type == 9) {
											$date_type_label = "This Year";
											$report_start_date = $selected_start_date;
											$report_end_date = $selected_end_date;
										} else if ($selected_date_type == 10) {
											$date_type_label = "Last Year";
											$report_start_date = $selected_start_date;
											$report_end_date = $selected_end_date;
										} else if ($selected_date_type == 11) {
											$date_type_label = "Customized 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">Report Type</h5>
										<h6 class="font-weight-normal">General Report</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, 16); ?></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, 16); ?></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>
								<?php
    								$generatedOrderTypeReport= mysqli_query($conn, "SELECT restaurant_orders.orderID, order_types.orderTypeName, COUNT(restaurant_orders.orderID) 'TotalOrders'
                                    FROM restaurant_orders
                                    JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID 
                            		". $fetch_criteria ."
                            		GROUP BY order_types.orderTypeName
                                    ORDER BY TotalOrders DESC") or die(mysqli_error($conn));
                            		if (mysqli_num_rows($generatedOrderTypeReport) > 0) { ?>
    									<div class="table-responsive mt-4">
    										<table class="table table-bordered table-sm">
    										    <tr class="text-center" height="45px">
    												<th class="align-middle" colspan="3"><h5 class="mt-2">Order Type Report</h5></th>
    											</tr>
												<tr class="text-center">
													<th width="6%">No</th>
													<th>Order Type</th>
													<th width="15%">Total</th>
												</tr>
												<?php
													$count = 1;
													$total_order_types = 0;
													while ($result = mysqli_fetch_array($generatedOrderTypeReport)) { ?>
														<tr>
															<td class="text-center"><?php echo $count; ?></td>
															<td class="text-left"><?php echo $result[1]; ?></td>
															<td class="text-center"><?php echo $result[2]; ?></td>
                                                        </tr><?php
														$total_order_types += $result[2];
														$count++;
													}
												?>
												<tr class="font-weight-bold">
													<td class="text-right pr-5" colspan="2">Total Orders</td>
													<td class="text-center"><?php echo $total_order_types; ?></td>
												</tr>
    										</table>
    									</div><?php
                            		}
                            	?>
                            	<?php
    								$generatedUserOrdersReport= mysqli_query($conn, "SELECT system_users.Username, COUNT(restaurant_orders.orderID) 'TotalOrder', IFNULL(SUM(restaurant_orders.totalAmount), 0) 'OrderBalance', IFNULL(SUM(customer_payments.paidAmount), 0) 'PaidBalance'
                                    FROM restaurant_orders
                                    LEFT JOIN customer_payments ON restaurant_orders.orderID = customer_payments.orderID
                                    JOIN system_users ON restaurant_orders.registeredBy = system_users.userID
                            		". $fetch_criteria ."
                            		GROUP BY restaurant_orders.registeredBy
                                    ORDER BY TotalOrder DESC") or die(mysqli_error($conn));
                                    
                            		if (mysqli_num_rows($generatedUserOrdersReport) > 0) { ?>
    									<div class="table-responsive mt-4">
    										<table class="table table-bordered table-sm">
    										    <tr class="text-center" height="45px">
    												<th class="align-middle" colspan="5"><h5 class="mt-2">User Orders Report</h5></th>
    											</tr>
												<tr class="text-center">
													<th width="6%">No</th>
													<th>Username</th>
													<th width="15%">Total Order</th>
													<th width="15%">Total Balance</th>
													<th width="15%">Paid Balance</th>
												</tr>
												<?php
													$count = 1;
													$total_user_orders = 0;
													$total_paid_user_orders = 0;
													$total_unpaid_user_orders = 0;
													while ($result = mysqli_fetch_array($generatedUserOrdersReport)) { ?>
														<tr>
															<td class="text-center"><?php echo $count; ?></td>
															<td class="text-left"><?php echo $result[0]; ?></td>
															<td class="text-center"><?php echo $result[1]; ?></td>
															<td class="text-center"><?php echo "$". number_format($result[2], 2); ?></td>
															<td class="text-center"><?php echo "$". number_format($result[3], 2); ?></td>
                                                        </tr><?php
														$total_user_orders += $result[1];
														$total_paid_user_orders += $result[2];
														$total_unpaid_user_orders += $result[3];
														$count++;
													}
												?>
												<tr class="font-weight-bold">
													<td class="text-right pr-5" colspan="2">Total Orders</td>
													<td class="text-center"><?php echo $total_order_types; ?></td>
	                                                <td class="text-center"><?php echo "$". number_format($total_paid_user_orders, 2); ?></td>
													<td class="text-center"><?php echo "$". number_format($total_unpaid_user_orders, 2); ?></td>
												</tr>
    										</table>
    									</div><?php
                            		}
                            	?>
                            	
                            	<?php
    								$generatedCashirCollectionsReport= mysqli_query($conn, "SELECT system_users.Username, SUM(IFNULL(customer_payments.paidAmount, 0)) 'TotalCollected'
                                    FROM customer_payments
                                    JOIN system_users ON customer_payments.registeredBy = system_users.userID
                            		". $fetch_criteria_cashiers ."
                            		GROUP BY customer_payments.registeredBy
                                    ORDER BY TotalCollected DESC") or die(mysqli_error($conn));
                                    
                            		if (mysqli_num_rows($generatedCashirCollectionsReport) > 0) { ?>
    									<div class="table-responsive mt-4">
    										<table class="table table-bordered table-sm">
    										    <tr class="text-center" height="45px">
    												<th class="align-middle" colspan="3"><h5 class="mt-2">Cashier Collections Report</h5></th>
    											</tr>
												<tr class="text-center">
													<th width="6%">No</th>
													<th>Username</th>
													<th width="15%">Collected Balance</th>
												</tr>
												<?php
													$count = 1;
													$total_user_orders = 0;
													$total_paid_user_orders = 0;
													$total_unpaid_user_orders = 0;
													while ($result = mysqli_fetch_array($generatedCashirCollectionsReport)) { ?>
														<tr>
															<td class="text-center"><?php echo $count; ?></td>
															<td class="text-left"><?php echo $result[0]; ?></td>
															<td class="text-center"><?php echo "$". number_format($result[1], 2); ?></td>
                                                        </tr><?php
														$total_collected_amount += $result[1];
														$count++;
													}
												?>
												<tr class="font-weight-bold">
													<td class="text-right pr-5" colspan="2">Total Amount</td>
	                                                <td class="text-center"><?php echo "$". number_format($total_collected_amount, 2); ?></td>
												</tr>
    										</table>
    									</div><?php
                            		}
                            	?>
                            	
                            	<?php
    								$generatedAccountBalancesReport= mysqli_query($conn, "SELECT payment_gateways.gatewayType, payment_gateways.gatewayLogo, payment_gateways.gatewayName, account_numbers.accountNoName, account_numbers.accountNumber, SUM(account_transactions.depositedAmount) 'TotalDeposit'
                                    FROM account_transactions 
                                    JOIN account_numbers ON account_transactions.accountNoID = account_numbers.accountNoID 
                                    JOIN payment_gateways ON account_numbers.gatewayID = payment_gateways.gatewayID
                                    ". $fetch_criteria_accounts ."
                                    GROUP BY account_transactions.accountNoID
                                    ORDER BY TotalDeposit DESC") or die(mysqli_error($conn));
                                    
                            		if (mysqli_num_rows($generatedAccountBalancesReport) > 0) { ?>
    									<div class="table-responsive mt-4">
    										<table class="table table-bordered table-sm">
    										    <tr class="text-center" height="45px">
    												<th class="align-middle" colspan="3"><h5 class="mt-2">Account Deposit Report</h5></th>
    											</tr>
												<tr class="text-center">
													<th width="6%">No</th>
													<th>Account Number</th>
													<th width="15%">Total Balance</th>
												</tr>
												<?php
													$count = 1;
													$total_account_balance = 0;
													while ($result = mysqli_fetch_array($generatedAccountBalancesReport)) { ?>
														<tr>
															<td class="text-center"><?php echo $count; ?></td>
															<td class="text-left">
    															<?php
    															    if ($result[0] == 1) {
                														?><span><img class="img-fluid" src="<?php echo $result[1]; ?>" width="25px"/> <?php echo $result[2]; ?>(<?php echo $result[4]; ?>)</span><?php
                													} else if ($result[0] == 2) {
                														?><span><img src="<?php echo $result[1]; ?>" width="25px" /> <?php echo $result[2]. " ". $result[3]; ?>(<?php echo $result[4]; ?>)</span><?php
                													} else if ($result[0] == 3) {
                														?><span><img src="<?php echo $result[1]; ?>" width="25px" /> <?php echo $result[3]; ?>(<?php echo $result[4]; ?>)</span><?php
                													}
                    															
                    										    ?>
															</td>
															<td class="text-center"><?php echo "$". number_format($result[5], 2); ?></td>
                                                        </tr><?php
														$total_account_balance += $result[5];
														$count++;
													}
												?>
												<tr class="font-weight-bold">
													<td class="text-right pr-5" colspan="2">Total Amount</td>
	                                                <td class="text-center"><?php echo "$". number_format($total_account_balance, 2); ?></td>
												</tr>
    										</table>
    									</div><?php
                            		}
                            	?>
                            	<?php
    								$generatedPeakTimeReport = mysqli_query($conn, "SELECT HOUR(restaurant_orders.registerDate) 'HourlyOrders', COUNT(restaurant_orders.orderID) 'TotalOrders', SUM(restaurant_orders.totalAmount) 'TotalAmount', restaurant_orders.registerDate
                                    FROM restaurant_orders
                                    JOIN order_types ON restaurant_orders.orderTypeID = order_types.orderTypeID 
                                    ". $fetch_criteria ."
                                    GROUP BY HourlyOrders
                                    ORDER BY TotalOrders DESC") or die(mysqli_error($conn));
                            		if (mysqli_num_rows($generatedPeakTimeReport) > 0) { ?>
    									<div class="table-responsive mt-4">
    										<table class="table table-bordered table-sm">
    										    <tr class="text-center" height="45px">
    												<th class="align-middle" colspan="3"><h5 class="mt-2">Peak Time Report</h5></th>
    											</tr>
												<tr class="text-center">
													<th width="70%">Hour</th>
													<th width="15%">Total Orders</th>
													<th width="15%">Total Balance</th>
												</tr>
												<?php
													$count = 1;
													$total_hour_orders = 0;
													$total_order_balance = 0;
													while ($result = mysqli_fetch_array($generatedPeakTimeReport)) { ?>
														<tr>
															<td class="text-center font-weight-bold"><?php echo date('h A', strtotime($result[3])); ?></td>
															<td class="text-center"><?php echo $result[1]; ?></td>
															<td class="text-center"><?php echo "$". number_format($result[2], 2); ?></td>
                                                        </tr><?php
														$total_hour_orders += $result[1];
														$total_order_balance += $result[2];
														$count++;
													}
												?>
												<tr class="font-weight-bold">
													<td class="text-right pr-5" colspan="1">Total</td>
													<td class="text-center"><?php echo $total_hour_orders; ?></td>
													<td class="text-center"><?php echo "$". number_format($total_order_balance, 2); ?></td>
												</tr>
    										</table>
    									</div><?php
                            		}
                            	?>
    					    </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
	}
	
	// ================ End of General Order Report ==============================================



	// ================ END OF SYSTEM REPORTS MODULE =============================================

	// ================ START OF DASHBOARD DESIGN MODULE =========================================
	
	// Search Waiter Analytics - Dashboard
	function search_waiter_analytics_dashboard($conn) {
		extract($_POST);
		$first_start_date = mysqli_real_escape_string($conn, $first_start_date);
		$first_end_date = mysqli_real_escape_string($conn, $first_end_date);
		$second_start_date = mysqli_real_escape_string($conn, $second_start_date);
		$second_end_date = mysqli_real_escape_string($conn, $second_end_date);
		$analytic_type = mysqli_real_escape_string($conn, $analytic_type);
		$analytic_end_used_word = mysqli_real_escape_string($conn, $analytic_end_used_word);

        $getWaitersFirst = mysqli_query($conn, "SELECT employees.employeeID, system_users.Username, employees.employeePhoto, COUNT(restaurant_orders.orderID) 'TotalOrders'
        FROM restaurant_orders
        JOIN employees ON restaurant_orders.servedBy = employees.employeeID
        JOIN system_users ON employees.employeeID = system_users.employeeID
        WHERE (restaurant_orders.orderTypeID = 'OT0001' OR restaurant_orders.orderTypeID = 'OT0002') AND restaurant_orders.orderStatus != '4' AND restaurant_orders.registerDate BETWEEN '$first_start_date' AND '$first_end_date'
        GROUP BY servedBy
        ORDER BY TotalOrders DESC");
        if ($getWaitersFirst) {
            if (mysqli_num_rows($getWaitersFirst) > 0) {
                
                // Declare array to get random value
                $collout_colors = ["bd-callout-primary", "bd-callout-success", "bd-callout-info", "bd-callout-danger", "bd-callout-warning", "bd-callout-default"];
                $icon_colors = ["bg-light-primary####bg-strong-primary####text-white", "bg-light-success####bg-strong-success####text-primary", "bg-light-info####bg-strong-info####text-primary", "bg-light-warning####bg-strong-warning####text-primary"];

                while ($served_waiters_rs = mysqli_fetch_array($getWaitersFirst)) {
                    $selected_collout_colors = $collout_colors[rand(0,5)];
                    $selected_icon_colors = $icon_colors[rand(0,3)];
                    $icon_color_info = explode("####", $selected_icon_colors);
                    ?><div class="col-lg-3">
        				<div class="btn bg-white bd-callout <?php echo $selected_collout_colors; ?> bg-white p-4 shadow">
        					<div class="row mb-3">
        						<div class="col-md-3">
        						    <img class="img-fluid p-1 rounded-circle shadow" src="<?php echo $served_waiters_rs[2]; ?>" width="90%" height="90%" />
        						</div>
        						<div class="col-md-9">
        							<h5 class="text-left"><small class="font-weight-bold"><?php echo $served_waiters_rs[1]; ?></small></h5>
        						</div>
        					</div>
        					<div class="row <?php echo $icon_color_info[0]; ?> ml-0 mr-0 pl-0 pt-3 pb-1 rounded-lg shadow-sm">
        						<div class="col-md-4 pl-0 pb-1">
        						    <i class="fa fa-shopping-cart text-white <?php echo $icon_color_info[1]; ?> p-3 rounded-lg shadow-sm" style="font-size: 17px;"></i> 
        						</div>
        						<div class="col-md-8 pl-1">
            						<h5 class="<?php echo $icon_color_info[2]; ?>">
        								<small class="font-weight-bold pb-1" style="display: block;">TOTAL ORDERS</small>
        								<?php
        									// Growth increase or decrease ratio formula$todays_total_orders_rs[0]. " - ".$yesterday_total_orders_rs[0] . " = ". (($todays_total_orders_rs[0]-$yesterday_total_orders_rs[0])/($yesterday_total_orders_rs[0]) * 100)
        									$waiter_yesterday_total_orders = mysqli_query($conn, "SELECT IFNULL(COUNT(orderID), 0) FROM restaurant_orders WHERE servedBy = '$served_waiters_rs[0]' AND orderStatus != '4' AND registerDate BETWEEN '$second_start_date' AND '$second_end_date'") or die(mysqli_error($conn));
        									$waiter_yesterday_total_orders_rs = mysqli_fetch_array($waiter_yesterday_total_orders); 
        									$waiter_todays_total_orders = mysqli_query($conn, "SELECT IFNULL(COUNT(orderID), 0) FROM restaurant_orders WHERE servedBy = '$served_waiters_rs[0]' AND orderStatus != '4' AND registerDate BETWEEN '$first_start_date' AND '$first_end_date'") or die(mysqli_error($conn));
        									$waiter_todays_total_orders_rs = mysqli_fetch_array($waiter_todays_total_orders);
        								?>
        								<span class="font-weight-normal" style="font-size: 0.85rem; display: block;"><?php echo $waiter_todays_total_orders_rs[0]; ?></span>
        								<span>
        								    
    								    	<?php
    								    	    if ($analytic_type == "custom-date") {
    								    	        if ($waiter_todays_total_orders_rs[0] > $waiter_yesterday_total_orders_rs[0]) { 
    								    	            ?><span class="text-white bg-strong-success pt-1 pb-1 pl-2 pr-2 rounded-lg" style="font-size: 0.80rem;"><i class="fa fa-long-arrow-up text-white"></i><?php echo abs((float)$waiter_todays_total_orders_rs[0] - (float)$waiter_yesterday_total_orders_rs[0]); ?></span><?php
            										} else if ($waiter_todays_total_orders_rs[0] < $waiter_yesterday_total_orders_rs[0]) {
            											?><span class="text-white bg-strong-danger pt-1 pb-1 pl-2 pr-2 rounded-lg" style="font-size: 0.80rem;"><i class="fa fa-long-arrow-down text-white"></i><?php echo abs((float)$waiter_todays_total_orders_rs[0] - (float)$waiter_yesterday_total_orders_rs[0]); ?></span><?php
            										}
    								    	    } else {
            										 if ($waiter_todays_total_orders_rs[0] > $waiter_yesterday_total_orders_rs[0]) { 
            										    ?><span class="text-white bg-strong-success pt-1 pb-1 pl-2 pr-2 rounded-lg" style="font-size: 0.80rem;"><i class="fa fa-long-arrow-up text-white"></i><?php echo abs((float)$waiter_todays_total_orders_rs[0] - (float)$waiter_yesterday_total_orders_rs[0]); ?></span>
            											<span class="font-weight-normal <?php echo $icon_color_info[2]; ?>" style="font-size: 0.80rem;"> <?php echo $analytic_end_used_word; ?></span><?php
            										} else if ($waiter_todays_total_orders_rs[0] < $waiter_yesterday_total_orders_rs[0]) {
            										    ?><span class="text-white bg-strong-danger pt-1 pb-1 pl-2 pr-2 rounded-lg" style="font-size: 0.80rem;"><i class="fa fa-long-arrow-down text-white"></i><?php echo abs((float)$waiter_todays_total_orders_rs[0] - (float)$waiter_yesterday_total_orders_rs[0]); ?></span>
            											<span class="font-weight-normal <?php echo $icon_color_info[2]; ?>" style="font-size: 0.80rem;"> <?php echo $analytic_end_used_word; ?></span><?php
            										}
    								    	    }
        										
        									?>
        								</span>
        							</h5>
        						</div>
        					</div>
        				</div>
        			</div> <?php
                }
            } else {
                ?><div class="col-md-12 bg-white p-3 mt-3">
                    <h6 class="text-center text-danger font-weight-normal">Data Not Found</h6>
                </div><?php
            }
        } else {
            ?><div class="col-md-12 bg-white p-3 mt-3">
                <h6 class="text-center text-danger font-weight-normal"><?php echo mysqli_error($conn); ?></h6>
            </div><?php
        }

	}
	
	
	// ================ END OF DASHBOARD DESIGN MODULE ===========================================
	
	// ================ START OF FINANCE MODULE ==================================================

    // 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 == 'PS0003' || $user_type == 'PS0004') {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseTypeID, expenseAmount, accountNoID, paymentDate, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $selected_payment_date ."', '". $expense_remarks ."', '2', '". $_SESSION['userIdd'] ."', '". mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) ."', '". $_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 {
    				$errorList[] = mysqli_error($conn);
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}
    		} else {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseTypeID, expenseAmount, accountNoID, paymentDate, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $selected_payment_date ."', '". $expense_remarks ."', '1', '". $_SESSION['userIdd'] ."', '". mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) ."', -', '-', '-', '-')") or die(mysqli_error($conn));
    			if ($register_expense) {
    				$data = json_encode(array('Status' => true, 'Message' => 'Expense has been registered successfully'));
    			} else {
    				$errorList[] = mysqli_error($conn);
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}
    		}
    	} else if ($expense_amount > 300) {
    		if ($user_type == 'PS0001' || $user_type == 'PS0002' || $user_type == 'PS0003') {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseTypeID, expenseAmount, accountNoID, paymentDate, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $selected_payment_date ."', '". $expense_remarks ."', '2', '". $_SESSION['userIdd'] ."', '". mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) ."', '". $_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 {
    				$errorList[] = mysqli_error($conn);
    				$data = json_encode(array('Status' => false, 'Message' => $errorList));
    			}
    		} else {
    			$register_expense = mysqli_query($conn, "INSERT INTO expenses (rowNo, expenseID, expenseTypeID, expenseAmount, accountNoID, paymentDate, expenseRemarks, expenseStatus, registeredBy, registerDate, approvedBy, approvedDate, cancelledBy, cancelDate) VALUES (NULL, '" . mysqli_real_escape_string($conn, $generatedExpenseID) . "', '". $expense_type_name ."', '". $expense_amount ."', '". $selectedAccountNo ."', '". $selected_payment_date ."', '". $expense_remarks ."', '1', '". $_SESSION['userIdd'] ."', '". mysqli_real_escape_string($conn, date("Y-m-d H:i:s")) ."', '-', '-', '-', '-')") or die(mysqli_error($conn));
    			if ($register_expense) {
    				$data = json_encode(array('Status' => true, 'Message' => 'Expense has been registered successfully'));
    			} else {
    				$errorList[] = mysqli_error($conn);
    				$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 {
							$errorList[] = mysqli_error($conn);
    						$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 ====================================================

	// 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 Employee Working Areas
	function fill_working_areas($conn) {
		$returned_data = array();
		$data = array();
		$readInformation = mysqli_query($conn, "SELECT * FROM working_areas ORDER BY workingAreaID ASC") or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				while ($row = mysqli_fetch_array($readInformation)) {
					$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 Expense Types
	function fill_expense_types($conn) {
		$returned_data = array();
		$data = array();
		$readInformation = mysqli_query($conn, "SELECT * FROM expense_types ORDER BY expenseTypeID ASC") or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				while ($row = mysqli_fetch_array($readInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Expense Types Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

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

	// Fill Restaurant Categories
	function fill_restaurant_categories($conn) {
		$returned_data = array();
		$data = array();
		if (($_SESSION['userTypeID'] == 'PS0001') || ($_SESSION['userTypeID'] == 'PS0002') || ($_SESSION['userTypeID'] == 'PS0003')) {
			$prepareInforamtion = "SELECT restaurant_categories.categoryID, restaurant_categories.categoryName, working_areas.workingAreaName FROM restaurant_categories JOIN working_areas ON restaurant_categories.workingAreaID = working_areas.workingAreaID ORDER BY restaurant_categories.categoryName ASC";
		} else {
			$prepareInforamtion = "SELECT restaurant_categories.categoryID, restaurant_categories.categoryName, working_areas.workingAreaName FROM restaurant_categories JOIN working_areas ON restaurant_categories.workingAreaID = working_areas.workingAreaID WHERE restaurant_categories.workingAreaID = '". $_SESSION['workingAreaID'] ."' OR restaurant_categories.workingAreaID = 'WAR0001' ORDER BY restaurant_categories.categoryName ASC";

			$prepareInforamtion = "SELECT * FROM restaurant_categories WHERE workingAreaID = '". $_SESSION['workingAreaID'] ."' OR workingAreaID = 'WAR0001' ORDER BY categoryName ASC";
		}
		$readInformation = mysqli_query($conn, $prepareInforamtion) or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				while ($row = mysqli_fetch_array($readInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Categories Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Active Customers
	function fill_active_customers($conn) {
		$returned_data = array();
		$data = array();
		$readInformation = mysqli_query($conn, "SELECT * FROM customers WHERE customerID != 'CU0001' AND customerStatus = '1' ORDER BY customerID ASC") or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				while ($row = mysqli_fetch_array($readInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Customers Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Customer Information
	function fill_customer_information($conn) {
		extract($_POST);
		$returned_data = array();
		$data = array();
		$selected_customer_id = mysqli_real_escape_string($conn, $selected_customer_id);
		$readInformation = mysqli_query($conn, "SELECT * FROM customers WHERE customerID = '". $selected_customer_id ."'") or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				while ($row = mysqli_fetch_array($readInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Customer Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}
	
	// ================ START OF STOCK MANAGEMENT MODULE ==============================================
	
	// Fill Stock Categories in items
	function fill_stock_categories($conn) {
		$returned_data = array();
		$data = array();
		$readInformation = mysqli_query($conn, "SELECT * FROM stock_categories ORDER BY categoryName ASC") or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				while ($row = mysqli_fetch_array($readInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Categories Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	// Fill Item Units
	function fill_item_units($conn) {
		$returned_data = array();
		$data = array();
		$readInformation = mysqli_query($conn, "SELECT * FROM item_units ORDER BY unitName ASC") or die(mysqli_error($conn));
		if ($readInformation) {
			if (mysqli_num_rows($readInformation) > 0) {
				while ($row = mysqli_fetch_array($readInformation)) {
					$returned_data[] = $row;
				}
				$data = json_encode(array('Status' => true, 'Message' => $returned_data));
			} else {
				$data = json_encode(array('Status' => false, 'Message' => "Units Not Found"));
			}    
		} else {
			$errorMsg = mysqli_error($conn);
			$data = json_encode(array('Status' => false, 'Message' => $errorMsg));
		}
		echo $data;
	}

	//Register Stock Items
	function register_stock_items($conn) {
		global $errorList;
		$item_details = array();
		$data = array();
		extract($_POST);

		$all_items = $stock_items_list;
		foreach($all_items as $item_information) {
			if ($item_information[0] == "") {$item_details = array('itemStatus' => false, 'itemMessage' => 'Enter Item Name'); break;}
			else if ($item_information[1] == "") {$item_details = array('itemStatus' => false, 'itemMessage' => 'Select Category'); break;}
			else if ($item_information[2] == "") {$item_details = array('itemStatus' => false, 'itemMessage' => 'Select Unit'); break;}
			else if ($item_information[3] == "") {$item_details = array('itemStatus' => false, 'itemMessage' => 'Enter Item Remarks'); break;}
			else $item_details = array('itemStatus' => true, 'itemMessage' => 'Items are Ok');
		}

		if (isset($item_details['itemStatus']) && $item_details['itemStatus'] == false) {
			$errorList[] = $item_details['itemMessage'];
			$data = json_encode(array('Status' => false, 'Message' => $errorList));
		} else {
			// Register the items now
			foreach($all_items as $item_information) {
				//Generate New ID for the current inserted item ....
				$getMaxItemID = mysqli_query($conn, "SELECT MAX(rowNo) FROM stock_items") or die(mysqli_error($conn));
				if (mysqli_num_rows($getMaxItemID) > 0) {
					$maxItemID = mysqli_fetch_array($getMaxItemID);
					$curItemID = $maxItemID[0] + 1;
					$generatedItemID = "PT" . sprintf("%04d", $curItemID);
				} else {
					$curItemID = 1;
					$generatedItemID = "PT" . sprintf("%04d", $curItemID);
				}
				mysqli_query($conn, "INSERT INTO stock_items(itemID, itemName, categoryID, unitID, itemRemarks, registeredBy, registerDate, `updatedBy`, updateDate) VALUES ('". mysqli_real_escape_string($conn, $generatedItemID) ."', '". mysqli_real_escape_string($conn, $item_information[0]) ."', '". mysqli_real_escape_string($conn, $item_information[1]) ."', '". mysqli_real_escape_string($conn, $item_information[2]) ."', '". mysqli_real_escape_string($conn, $item_information[3]) ."', '". $_SESSION['userIdd'] ."', '". date("Y-m-d H:i:s") ."', '-', '-')");
			}
			$successMsg = "Items has been registered";
			$data = json_encode(array('Status' => true, 'Message' => $successMsg));
		}
		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("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
			$selected_end_date = date("Y-m-d H:i");
		} else if ($selected_date_type == 2) {
		    $selected_start_date = (date("H") > 6) ? date("Y-m-d 06:00", strtotime("-1 days")) : date('Y-m-d 06:00', strtotime("-2 days"));
	        $selected_end_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		} else if ($selected_date_type == 3) {
			$selected_start_date = date('Y-m-d 06:00', strtotime("-3 days"));
	        $selected_end_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		} else if ($selected_date_type == 4) {
			$selected_start_date = date('Y-m-d 06:00', strtotime('last Saturday'));
	        $selected_end_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		} else if ($selected_date_type == 5) {
			$selected_start_date = date('Y-m-d 06:00', strtotime("-10 days"));
	        $selected_end_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		} else if ($selected_date_type == 6) {
			$selected_start_date = date("Y-m-01 06:00");
	        $selected_end_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		} else if ($selected_date_type == 7) {
			$selected_start_date = date("Y-01-01 06:00");
	        $selected_end_date = (date("H") > 6) ? date("Y-m-d 06:00") : date('Y-m-d 06:00', strtotime("-1 days"));
		} else if ($selected_date_type == 8) {
			$selected_start_date = mysqli_real_escape_string($conn, substr($selected_start_date, 0, 10) . " 06:00");
			$selected_end_date = mysqli_real_escape_string($conn, date("Y-m-d H:i", strtotime($selected_end_date. " + 1 days")));
		}
		$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, 16); ?></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, 16); ?></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 width="25%">Remarks</th>
													<th>Account Information</th>
													<th>Username</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="7">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, 16); ?></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-left"> <?php echo $result[10]; ?></td>
															<td class="text-center"> <?php echo ($result[8] > 0) ? "<span class='text-danger font-weight-bold'>$". number_format($result[8], 2) ."</span>" : "" ?></td>
															<td class="text-center"> <?php echo ($result[9] > 0) ? "<span class='text-success font-weight-bold'>$". number_format($result[9], 2) ."</span>" : "" ?></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="5">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="8">&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="7">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 Advanced salaries report group --------------------
	function advanced_salaries_report($conn) {
		extract($_POST);
		$selected_employee_id = mysqli_real_escape_string($conn, $selected_employee_id);
		$selected_payment_month = mysqli_real_escape_string($conn, $selected_payment_month);
		$qry_code = "";
		if ($selected_employee_id == "All") {
		   	$qry_code = "SELECT advanced_salaries.paymentID, advanced_salaries.employeeID, employees.employeeName, employees.employeeMobileNo, advanced_salaries.paymentType, advanced_salaries.paymentMonth, system_users.Username, advanced_salaries.registerDate, IFNULL(SUM(advanced_salaries.paidAmount), 0) 'TotalAdvanced'
            FROM advanced_salaries
            JOIN employees ON advanced_salaries.employeeID = employees.employeeID
            JOIN system_users ON advanced_salaries.registeredBy = system_users.userID
            WHERE advanced_salaries.paymentMonth = '". $selected_payment_month ."'
            GROUP BY advanced_salaries.employeeID
            ORDER BY TotalAdvanced DESC";
		} else {
		    $qry_code = "SELECT advanced_salaries.paymentID, advanced_salaries.employeeID, employees.employeeName, employees.employeeMobileNo, advanced_salaries.paymentType, advanced_salaries.paymentMonth, system_users.Username, advanced_salaries.registerDate, advanced_salaries.paidAmount
            FROM advanced_salaries
            JOIN employees ON advanced_salaries.employeeID = employees.employeeID
            JOIN system_users ON advanced_salaries.registeredBy = system_users.userID
            WHERE advanced_salaries.employeeID = '". $selected_employee_id ."' AND advanced_salaries.paymentMonth = '". $selected_payment_month ."'
            ORDER BY advanced_salaries.registerDate DESC";	
		}
		$qry = mysqli_query($conn, $qry_code) or die(mysqli_error($conn));
		if (mysqli_num_rows($qry) > 0) { ?>
			<div class="tile mt-4">
				<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="printAdvancedSalariesReport"><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="advancedSalariesPrintArea">
						<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;">Advanced Salaries Report</h2></center>
								</div>
							</div>
							<br />
							<?php
								if ($selected_employee_id != "All") {
									$get_emp_name = mysqli_query($conn, "SELECT employeeName from employees WHERE employeeID = '" . $selected_employee_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-4">
									        <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 class="col-md-4">
									        <h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Advanced Payment Of:</b><?php echo $selected_payment_month; ?> </h5>
                                        </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>
										</div>
									</div><?php
								} else {
									?><div class="row">
										<div class="col-md-4"> &nbsp;</div>
									    <div class="col-md-4">
									        <h5 class="text-left" style="font-size: 15px; font-family: 'century gothic'; font-weight: normal; padding-left: 15px;"><b>Advanced Payment Of:</b><?php echo $selected_payment_month; ?> </h5>
                                        </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>
										</div>
									</div><?php
								}
							?>
							<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>Payment Type</center></th>
													<th style="border-bottom: 1px solid black;"><center>Payment Month</center></th>
													<th style="border-bottom: 1px solid black;"><center>Paid By</center></th>
													<th style="border-bottom: 1px solid black;"><center>Payment Date</center></th>
													<th style="border-bottom: 1px solid black;"><center>Amount</center></th>
												</tr>
											</thead>
											<tbody>
												<?php
													$i = 1;
													$totalAdvancedAmount = 0;
													while ($result = mysqli_fetch_array($qry)) { ?>
														<tr>
															<td align="center"><?php echo $i; ?></td>
															<td align="left"><?php echo $result[2]. " (". $result[3]. ")"; ?></td>
															<td align="center"><?php echo $result[4]; ?></td>
															<td align="center"><?php echo $result[5]; ?></td>
															<td align="center"><?php echo $result[6]; ?></td>
															<td align="center"><?php echo substr($result[7], 0, 10); ?></td>
															<td align="center"><?php echo "$" . number_format($result[8], 2); ?></td>
														</tr><?php
														$totalAdvancedAmount += $result[8];
														$i++;
													}
												?>
												<tr>
													<td align="right" colspan="6"><b>Total:</b></td>
													<td align="center"><b><?php echo "$ " . number_format($totalAdvancedAmount, 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 mt-4">
				<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">Advanced Salaries 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.paymentDate, expenses.expenseTypeID, 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.expenseTypeID = '". $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, 16); ?></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 ============================
	


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

?>