<?php
error_reporting (E_ERROR | 0);
date_default_timezone_set('Africa/Lagos');
include 'constants.php';
include 'mail.php';
include 'ImageManipulator.php';
include '../PHPExcel/PHPExcel.php';
include '../PHPExcel/PHPExcel/IOFactory.php';

//PHPMailer CSS
$cssFile = "mail.css";
//echo "<link rel='stylesheet' href='" . $cssFile . "'>";

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';



	if(isset($_GET['log_out'])) {
		$Login_Process = new Login_Process;
		$Login_Process->log_out($_SESSION['email'], $_SESSION['password'], $_SESSION['level']);
	}

	if(isset($_GET['clearurl'])) {
		$Login_Process = new Login_Process;
		$Login_Process->clearNotifications($_GET['clearurl'],$_GET['nt']);
	}

class Login_Process {

	var $cookie_user = BCUS;
	var $cookie_pass = BCPS;

	function connect_db() {
		//$conn_str = mysql_connect(DBHOST, DBUSER, DBPASS);
		//mysql_select_db(DBNAME, $conn_str) or die ('Could not select Database.');

		try {
			$conn = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME."", DBUSER, DBPASS);
			// set the PDO error mode to exception
			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
			return $conn;
		}catch(PDOException $e){
			echo "Connection failed: " . $e->getMessage();
		}
	}

	function RunQuery($query,$dbLink) {
		$queryString = $dbLink->prepare($query);
		$queryString->execute();
		return $queryString;
	}

	function mysql_prepare_value($value) {
		/*check if get_magic_quotes_gpc is turned on.
		$magic_quotes_active = get_magic_quotes_gpc();
		$new_version_php = function_exists("mysql_real_escape_string");

		if($new_version_php){
			//undo any magic quote effects so mysql_real_escape_string can do the work
			if($magic_quotes_active) { $value = stripslashes($value); }
			$value = mysql_real_escape_string($value);
		}else {
				//if magic quotes aren't already on then add slashes manually
				if( !$magic_quotes_active ) { $values = addslashes( $value ); }
				//if magic quotes are active, then the slashes already exist
		}*/
		return htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
	}

	function limit_words($string, $word_limit) {
		$words = explode(" ",$string);
		return implode(" ",array_splice($words,0,$word_limit));
	}



	function check_login($page) {

		ini_set("session.gc_maxlifetime", Session_Lifetime);
		session_start();

		if(isset($_COOKIE[$this->cookie_user]) && isset($_COOKIE[$this->cookie_pass])){
			$this->log_in($_COOKIE[$this->cookie_user], $_COOKIE[$this->cookie_pass], 'true', $page, 'cookie');
		} else if(isset($_SESSION['username'])) {
			if(!$page) { $page = Script_Path; }
					header("Location: https://".$_SERVER['HTTP_HOST'].$page);
		} else {
		    return true;
		}
	}

	function check_status($page) {

		ini_set("session.gc_maxlifetime", Session_Lifetime);
		session_start();

		if(!isset($_SESSION['userid'])){
			header("Location: http://".$_SERVER['HTTP_HOST'].Script_Path."account-login.php?ref=$page");
		}
		$_SESSION['accessData'] = $this->getAccessRoleInfo($_SESSION['access']);
	}

	function log_in($email, $password, $page, $submit) {
		$dbLink = $this->connect_db();

		if(isset($submit)) {

			if($submit !== "cookie") {
				$password = md5($password);
			}

			$query = $this->RunQuery("SELECT * FROM apl_employees WHERE cooperate_email = '$email' AND password='$password'",$dbLink);
			$rowCount = $query->rowCount();

			if($rowCount == 1) {

				$fetchData = $query->fetch();

				if ($fetchData->status == "suspended") {
					header("Location: http://".$_SERVER['HTTP_HOST']."account-login.php?ref=$page&invld=3");
				}

				if ($fetchData->status == "pending") {
					header("Location: http://".$_SERVER['HTTP_HOST']."account-login.php?ref=$page&invld=2");
				}

				$this->set_session($email, $password);

			} else {

					header("Location: https://".$_SERVER['HTTP_HOST']."account-login.php?ref=$page&invld=1");
			}

			$this->RunQuery("UPDATE apl_employees SET last_loggedin = '".time()."' WHERE cooperate_email = '$username'",$dbLink);

			if($fetchData->changed_password=="No") {
				$page = Script_Path."change-passsword.php";
			}else{
				$page = Script_Path."$page";
			}

			header("Location: https://".$_SERVER['HTTP_HOST'].$page);

		}
	}

	function set_session($email, $password) {
		$dbLink = $this->connect_db();

		$query = $this->RunQuery("SELECT * FROM apl_employees WHERE cooperate_email='$email' AND password='$password'",$dbLink);
		$fetchData = $query->fetch();

		ini_set("session.gc_maxlifetime", Session_Lifetime);
		session_start();

		$_SESSION['userid']    	  	= $fetchData->id;
		$_SESSION['username']		= $fetchData->firstname;
		$_SESSION['email']			= $fetchData->cooperate_email;
		$_SESSION['gender']			= $fetchData->gender;
		$_SESSION['access']			= $fetchData->access_role;
		$_SESSION['station_id']		= $fetchData->station_id;
		$_SESSION['dept_id']		= $fetchData->department_id;
		$_SESSION['time_created']   = date("M. Y",$fetchData->time_created);

		$_SESSION['accessData'] = $this->getAccessRoleInfo($_SESSION['access']);
		$_SESSION['userAccessModules'] = explode(",",$_SESSION['accessData']->modules);
		$_SESSION['privileges'] = explode(",",$_SESSION['accessData']->privileges);
	}

	function set_cookie($email, $password, $set) {

			if($set == "+")
				{ $cookie_expire = time()+60*60*24*30; }
			else
				{ $cookie_expire = time()-60*60*24*30; }

			setcookie($this->cookie_user, $email, $cookie_expire, '/');
			setcookie($this->cookie_pass, $password, $cookie_expire, '/');

	}

	function log_out($username, $password) {
		session_start();
		session_unset();
		session_destroy();
		$this->set_cookie($username, $password, '-');

		header('Location: ../index.php');
	}

	function changePassword($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$newPassword = md5(trim($post['pass1']));
			$runQ = $this->RunQuery("update apl_employees set password='$newPassword', changed_password='Yes' where id = '".$_SESSION['userid']."'",$dbLink);
			if($runQ) {
				header("Location: ./");
			}
		}
	}

	function checkEmpID($empID,$type,$id=NULL) {
		$dbLink = $this->connect_db();
		if($type=="add") {
			$runQ = $this->RunQuery("select * from apl_employees where emp_id = '$empID'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 1;
			}else{
				return 0;
			}
		}if($type=="update") {
			$runQ = $this->RunQuery("select * from apl_employees where id !='$id' and emp_id = '$empID'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 0;
			}else{
				return 1;
			}
		}
	}

	function checkEmpEmail($email,$type,$id=NULL) {
		$dbLink = $this->connect_db();
		if($type=="add") {
			$runQ = $this->RunQuery("select * from apl_employees where cooperate_email = '$email'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 1;
			}else{
				return 0;
			}
		}if($type=="update") {
			$runQ = $this->RunQuery("select * from apl_employees where id!='$id' and cooperate_email = '$email'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 0;
			}else{
				return 1;
			}
		}
	}

	function checkDepartment($dept_name,$type,$dept_id=NULL) {
		$dbLink = $this->connect_db();
		if($type=="add") {
			$runQ = $this->RunQuery("select * from apl_departments where dept_name = '$dept_name'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 1;
			}else{
				return 0;
			}
		}if($type=="update") {
			$runQ = $this->RunQuery("select * from apl_departments where dept_name = '$dept_name' and dept_id!='$dept_id'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 1;
			}else{
				return 0;
			}
		}
	}

	function checkDesignation($dept_id,$desig_name,$type,$desig_id) {
		if($type=="add") {
			$dbLink = $this->connect_db();
			$runQ = $this->RunQuery("select dept_id,designations from apl_designations where dept_id = '$dept_id' and designations = '$desig_name'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 1;
			}else{
				return 0;
			}
		}elseif($type=="update") {
			$dbLink = $this->connect_db();
			$runQ = $this->RunQuery("select dept_id,designations from apl_designations where designation_id != '$desig_id' and dept_id = '$dept_id' and designations = '$desig_name'",$dbLink);
			$count = $runQ->rowCount();
			if($count>0) {
				return 1;
			}else{
				return 0;
			}
		}
	}

	function getDeptDesignations($deptID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_designations where dept_id = '$deptID'",$dbLink);
		return $runQ;
	}

	function listEmployee($emp_id=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_employees order by firstname",$dbLink);
		while($EmpData = $runQ->fetch()) {
			$empID = $EmpData->id;
			$firstname = $EmpData->firstname;
			echo"<option value=\"$empID\"";
			if($emp_id!=null && $emp_id==$empID) {echo" selected ";}
			echo">$firstname</option>";
		}
	}

	function listDepartment($dept_id=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_departments order by dept_name",$dbLink);
		while($deptData = $runQ->fetch()) {
			$deptID = $deptData->dept_id;
			$deptName = $deptData->dept_name;
			echo"<option value=\"$deptID\"";
			if($dept_id!=null && $dept_id==$deptID) { echo" selected "; }
			echo">$deptName</option>";
		}
	}

	function sendEmailtoDeptMembers($deptID,$logID) {
		$dbLink = $this->connect_db();

		$deptData = $this->getDepartmentInfo($deptID);
		$deptName = $deptData->dept_name;
		$deptEmail = $deptData->dept_email;

		$dept_sql = $this->RunQuery("select department_id,cooperate_email from apl_employees where department_id ='$deptID'",$dbLink);
		if($dept_sql) {
			
			$caseData = $this->getCaseInfo($logID);
			$logRef = $caseData->log_id;
			$caseCategory = $caseData->log_category;
			$caseDescription = $caseData->case_description;

			while($empData = $dept_sql->fetch()) {

				$staffEmail = $empData->cooperate_email ;

				$msg = "Hi, $deptName Department<br /><br />";
				$msg .= "A Case has been Forwarded to your department for further action<br /><br />";
				$msg .= "*************************<br />";
				$msg .= "<strong>Case Category:</strong> $caseCategory<br />";
				$msg .= "<strong>Case Description:</strong> $caseDescription<br /><br />";
				$msg .= "***************************<br />";
				$msg .= "<a href=\"http://support.flyairpeace.com/open-case-log.php?lid=$logID\" class=\"btn btn-primary\">Open Case</a><br /><br />";
				$msg .= "Regards";

				$emailMessage = $this->emailTemplate($msg);

				$headers = "From: ".$_SESSION['email']." \r\n ";
				$headers .=	"Reply-To: ".Non_Reply." \r\n ";
				$headers .= "MIME-Version: 1.0\r\n";
				$headers .= "Content-type: text/html\r\n";

				$sendMail = mail($staffEmail, "Pax Case Forwarded to $deptName - [$logRef]", $emailMessage, $headers);
			}
		}
	}

	function getDeptments() {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_departments order by dept_name",$dbLink);
		return $runQ;
	}

	function addDepartment($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$time = time();

			$dept_name  		= trim($post['dept_name']);
			$dept_email  		= $post['dept_email'];
			$designations  		= $post['designation'];

			$checkDepartment = $this->checkDepartment($dept_name,"add");
			if($checkDepartment==0) {
				$dept_sql = $this->RunQuery("insert into apl_departments values(default,'$dept_name','$dept_email','".$_SESSION['userid']."','$time')",$dbLink);
				$dept_id = $dbLink->lastInsertId();
				if($dept_sql) {
					//add designations
					foreach($designations as $designation) {
						if(!empty($designation)) {
							$checkDesignation = $this->checkDesignation($dept_id,$designation,"add");
							if($checkDesignation==0) {
								$desgn_sql = $this->RunQuery("insert into apl_designations values(default,'$dept_id','$designation')",$dbLink);
							}
						}
					}
					if($desgn_sql) {
						return '<div class="alert alert-success">
							<i class="fa fa-check"></i>
							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
							Department Created Successfully
						</div>';
					}
				}
			}else{
				return '<div class="alert alert-danger">
							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
							<i class="fa fa-times"></i>
							Department name alreay exists!
						</div>';
			}
		}
	}

	function updateDepartment($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$time = time();

			$dept_id  			= trim($post['dept_id']);
			$dept_name  		= trim($post['dept_name']);
			$designation_id		= $post['designation_id'];
			$designation_old  		= $post['designation_old'];
			$designations_new  		= $post['designation'];

			$countDesignationID = count($designation_id);
			$countDesignations_new = count($designations_new);

			$checkDepartment = $this->checkDepartment($dept_name,"update",$dept_id);
			if($checkDepartment==0) {
				$dept_sql = $this->RunQuery("update apl_departments set dept_name = '$dept_name' where dept_id = '$dept_id'",$dbLink);
				if($dept_sql) {
					//update existing designations
					for($i=0;$i<$countDesignationID;$i++) {
						if(!empty($designation_old[$i])) {
							$checkDesignation = $this->checkDesignation($dept_id,$designation_old[$i],"update",$designation_id[$i]);
							if($checkDesignation==0) {
								$desgn_sql1 = $this->RunQuery("update apl_designations set designations = '".$designation_old[$i]."' where designation_id='".$designation_id[$i]."'",$dbLink);
							}
						}else {
							//delete designation
							$this->RunQuery("update apl_employees set department = 'NULL', designation = 'NULL' where designation_id='".$designation_id[$i]."'",$dbLink);
							$desgn_sql1 = $this->RunQuery("delete from  apl_designations where designation_id='".$designation_id[$i]."'",$dbLink);
						}
					}

					if($countDesignations_new>0) {
						//add new designations if any
						foreach($designations_new as $designation) {
							if(!empty($designation)) {
								$checkDesignation = $this->checkDesignation($dept_id,$designation,"add");
								if($checkDesignation==0) {
									$desgn_sq2 = $this->RunQuery("insert into apl_designations values('','$dept_id','$designation')",$dbLink);
								}
							}
						}
					}

					if($desgn_sql1 || $desgn_sql2) {
						return '<div class="alert alert-success">
							<i class="fa fa-check"></i>
							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
							Department Updated Successfully
						</div>';
					}
				}
			}else{
				return '<div class="alert alert-danger">
							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
							<i class="fa fa-times"></i>
							Department name alreay exists!
						</div>';
			}
		}
	}

	function getDepartments() {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT  * FROM apl_departments ORDER BY dept_name",$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0){
			echo"
				<table class=\"table table-bordered table-striped table-hover\" id=\"example\">
               <thead>
                    <tr>
						<th>Sn</th>
						<th>Department Name</th>
						<th>Email</th>
						<th>Designations</th>
						<th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$deptID 	= $fetchData->dept_id;
				$deptName	= $fetchData->dept_name;
				$deptEmail	= $fetchData->dept_email;

				$fetchDesignation	= $this->getDeptDesignations($deptID);

				echo"<tr>
                        <td>$sn</td>
                        <td>$deptName</td>
                        <td>$deptEmail</td>
                        <td>";
						while($Data = $fetchDesignation->fetch()) {
							$designation = $Data->designations;
							echo"<div class=\"label label-primary\">$designation</div> ";
						}
						echo"</td>
                        <td><a href=\"edit-dept.php?did=$deptID\" data-toggle=\"modal\" data-target=\"#editDepartment\"><i class=\"fa fa-edit\"></i> Edit</a>
						<a href=\"delete-dept.php?did=$deptID\" data-toggle=\"modal\" data-target=\"#deleteDepartment\"><i class=\"fa fa-trash\"></i> Delete</a></td>
					</tr>";
			 }
			 echo"</tbody></table>";

	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Department Created Yet.</div>';
	   }
	}

	function getEmployees() {
		$dbLink = $this->connect_db();
		$query = "SELECT id,emp_id,surname,first_name,other_names,department,designation,status FROM apl_employees where dropped='0' ORDER BY surname";
		$runQ = $this->RunQuery($query,$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0) {
			echo"
				<table class=\"table table-bordered table-striped table-hover\" id=\"example\">
               <thead>
                    <tr>
						<th>Employee ID</th>
						<th>Image</th>
						<th>Name</th>
						<th>Department</th>
						<th>Designations</th>
						<th>At Work</th>
						<th>Status</th>
						<th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$id 	= $fetchData->id;
				$empID 	= $fetchData->emp_id;
				$deptID 	= $fetchData->department;
				$desigID 	= $fetchData->designation;
				$surname	= $fetchData->surname;
				$first_name	= $fetchData->first_name;
				$other_names	= $fetchData->other_names;
				$status			= $fetchData->status;

				$deptData	= $this->getDepartmentInfo($deptID);
				$deptName = $deptData->dept_name;
				$desigData	= $this->getDesignationInfo($desigID);
				$designation = $desigData->designations;

				echo"<tr>
                        <td>$empID</td>
                        <td><img src=\"view-images.php?eid=$id\" width=\"100\" /></td>
                        <td>$surname $first_name $other_names</td>
                        <td>$deptName</td>
                        <td>$designation</td>
                        <td>0</td>
                        <td>$status</td>
                        <td><a href=\"edit-employee.php?eid=$id\" class=\"btn btn-success\"><i class=\"fa fa-edit\"></i> View/Edit</a>
						<a href=\"delete-employee.php?eid=$id\" class=\"btn btn-danger\"  data-toggle=\"modal\" data-target=\"#deleteEmp\"><i class=\"fa fa-trash\"></i> Delete</a></td>
					</tr>";
			 }
			 echo"</tbody></table>";

	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Employee Added Yet.</div>';
	   }
	}

	function checkPilotIsAdded($userid) {
		$dbLink = $this->connect_db();
		$sql = "SELECT  employee_id FROM apl_pilots where employee_id = '$userid'";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();
		if($num_rows>0) {
			return 1;
		}else {
			return 0;
		}
	}

	function addPilot($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$time = time();

			$user_id	= trim($post['user_id']);
			$code_nmae	= trim($post['code_nmae']);
			$pilot_type	= trim($post['pilot_type']);

			//check if tis user has been added before
			if($this->checkPilotIsAdded($user_id)==1){
				return '<div class="alert alert-danger"><i class="fa fa-times"></i> Pilot Already Exists</div>';
			};

			$query = $this->RunQuery("insert into apl_pilots values(default,'$user_id','$code_name','$pilot_type','Active','$time')",$dbLink);
			if($query) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Pilot Added</div>';
			}
		}
	}

	function getPilots() {
		$dbLink = $this->connect_db();
		$query = "SELECT * FROM apl_pilots ORDER BY time_created";
		$runQ = $this->RunQuery($query,$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0){
			echo"
				<table class=\"table table-bordered table-striped table-hover\" id=\"example\">
               <thead>
                    <tr>
						<th>Name</th>
						<th>Pilot Type</th>
						<th>FT Hours</th>
						<th>Status</th>
						<th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$pilotID = $fetchData->pilot_id;
				$empID 	= $fetchData->employee_id;
				$piloType = $fetchData->pilot_type ;
				$status = $fetchData->pilot_status ;

				$empData	= $this->getEmployeeInfo($empID);
				$pilotName  = $empData->firstname;

				echo"<tr>
                        <td>$pilotName</td>
                        <td>$piloType</td>
                        <td>0000 hours</td>
                        <td>$status</td>
                        <td>
						<a href=\"#?eid=$id\" class=\"btn btn-success btn-xs\"><i class=\"fa fa-edit\"></i> Edit</a>
						<a href=\"#?eid=$id\" class=\"btn btn-warning btn-xs\"><i class=\"fa fa-bars\"></i> Fligh History</a>
						<a href=\"#?eid=$id\" class=\"btn btn-danger btn-xs\"  data-toggle=\"modal\" data-target=\"#deleteEmp\"><i class=\"fa fa-times-circle\"></i> Delete</a></td>
					</tr>";
			 }
			 echo"</tbody></table>";

	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Pilot Added Yet.</div>';
	   }
	}


	function getDepartmentInfo($deptID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_departments where dept_id = '$deptID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getDesignationInfo($desigID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_designations where designation_id = '$desigID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function deleteEmployee($post, $delete) {
		$dbLink = $this->connect_db();
		if(isset($delete)) {
			$id = $post['staff_id'];
			$runQ = $this->RunQuery("update apl_employees set dropped = '1' WHERE id = '$id'",$dbLink);
			if($runQ) {
				return  '<div class="alert alert-success">
							<i class="fa fa-check"></i>
							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
							Employee Deleted Successfully
						</div>';
			}
		}
	}

	function deleteDepartment($post, $delete) {
		$dbLink = $this->connect_db();
		if(isset($delete)) {
			$id = $post['dept_id'];
			$runQ1 = $this->RunQuery("delete from apl_departments WHERE dept_id = '$id'",$dbLink);
			$runQ2 = $this->RunQuery("delete from apl_designations WHERE dept_id = '$id'",$dbLink);
			$runQ3 = $this->RunQuery("update apl_employees set department = 'NULL', designation = 'NULL' WHERE department = '$id'",$dbLink);
			if($runQ1 && $runQ2 && $runQ3) {
				return  '<div class="alert alert-success">
							<i class="fa fa-check"></i>
							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
							Department Deleted Successfully
						</div>';
			}
		}
	}

	function getCaseInfo($caseID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_case_log where log_id = '$caseID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function addModule($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$time = time();

			$name	  		= trim($post['module_name']);
			$page			= trim($post['module_page']);
			$position		= trim($post['module_position']);
			$parent			= $post['parent_id'];
			$status			= trim($post['module_status']);

			$query = $this->RunQuery("insert into apl_app_module values(default,'$name','$page','$parent','$position','$status')",$dbLink);
			if($query) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Module Saved</div>';
			}
		}
	}

	function updateModule($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$moduleid    	= $post['module_id'];
			$name	  		= trim($post['module_name']);
			$page			= trim($post['module_page']);
			$position		= $post['module_position'];
			$status			= $post['module_status'];

			$query = "update apl_app_module set
			module_name = '$name',
			module_link = '$page',
			position = '$position',
			status = '$status'
			where module_id = '$moduleid'";

			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Project Updated Successful</div>';
			}
		}
	}

	function deleteModule($post, $delete) {
		$dbLink = $this->connect_db();
		if(isset($delete)) {
			$id = $post['module_id'];
			$query = "delete from apl_app_module WHERE module_id = '$id'";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return  "<div class=\"alert alert-success\">Module deleted Successfully.</div>";
			}
		}
	}

	function getModules() {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT  * FROM apl_app_module ORDER BY position",$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0){
			echo"
				<table class=\"table table-bordered table-striped table-hover\" id=\"example\">
               <thead>
                    <tr>
						<th>Sn</th>
						<th>Module Name</th>
						<th>Module Page name</th>
						<th>Position</th>
						<th>Status</th>
						<th width=\"12%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$id 			= $fetchData->module_id;
				$moduleName		= $fetchData->module_name;
				$pageLink		= $fetchData->module_link;
				$position		= $fetchData->position;
				$status			= $fetchData->status;


				echo"<tr>
                        <td>$sn</td>
                        <td>$moduleName</td>
                        <td>$pageLink</td>
                        <td>$position</td>
                        <td><span class=\"label label-";
							if($status=="Active") { echo "success"; }else{ echo "danger"; }
						echo"\">$status</span></td>
                        <td>
							<a href=\"".$_SERVER['PHP_SELF']."?module_id=$id&ed=$sn\"><i class=\"fa fa-edit\"></i></a>
							<a href=\"".$_SERVER['PHP_SELF']."?module_id=$id&del=$sn\" onclick=\"return confirm('Are you sure you want to delete $moduleName Module');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
					</tr>";
			 }
			 echo"</tbody></table>";

	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Module Created Yet.</div>';
	   }
	}

	function addAsset($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$time = time();

			$asset_user			= htmlspecialchars(trim($post['asset_user']), ENT_QUOTES, 'UTF-8');
			$designation		= htmlspecialchars(trim($post['designation']) , ENT_QUOTES, 'UTF-8');
			$user_location		= trim($post['user_location']);
			$device_id 			= trim($post['device_id']);
			$brand_id			= trim($post['brand_id']);
			$model_product_no	= htmlspecialchars(trim($post['model_product_no']) , ENT_QUOTES, 'UTF-8');
			$asset_tag			= htmlspecialchars(trim($post['asset_tag']) , ENT_QUOTES, 'UTF-8');
			$barcode_number		= $post['barcode_number'];
			$tag_no_posted				= htmlspecialchars(trim($post['tag_no']) , ENT_QUOTES, 'UTF-8');
			
			$date_requested		= trim($post['date_requested']);
			$date_received		= trim($post['date_received']);
			$date_issued		= trim($post['date_issued']);
			$asset_status		= trim($post['asset_status']);
			$remark				= htmlspecialchars(trim($post['remark']), ENT_QUOTES, 'UTF-8');
			
			/* ***Get the Brand from Database*** */
			
			
				$runQ = $this->RunQuery("SELECT  brand_id, brand_name FROM apl_asset_brand WHERE brand_id = $brand_id",$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0){
			
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$id 				= $fetchData->asset_id;
				
				$brand_id			= $fetchData->brand_id;
				
				
				
				
				$brandData = $this->getBrandInfo($brand_id);
				$brand_name = $brandData->brand_name;

    			$tag_no = $brand_name. '-' .$tag_no_posted;
			 }
	   }

/* *** End get Brand Name from Database*** */
			
			if(empty($barcode_number)) 
            {
           //Do my PHP code
            $barcode_number = "No Value";
           
            }

			$query = $this->RunQuery("insert into apl_asset values(default,'$asset_user','$designation','$user_location','$device_id','$brand_id','$model_product_no',
			'$asset_tag','$barcode_number','$tag_no','$date_requested','$date_received','$date_issued','$asset_status','$remark','".$_SESSION['userid']."','$time')",$dbLink);
			if($query) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Asset Saved</div>';
			}
		}
	}

	function updateAsset($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {
            $locationErr = "";
            
			$asset_id    		= $post['asset_id'];
			$asset_user			= htmlspecialchars(trim($post['asset_user']) , ENT_QUOTES, 'UTF-8');
			$designation		= htmlspecialchars(trim($post['designation']) , ENT_QUOTES, 'UTF-8');
			
			$device_id 			= trim($post['device_id']);
			$brand_id			= trim($post['brand_id']);
			$model_product_no	= htmlspecialchars(trim($post['model_product_no']) , ENT_QUOTES, 'UTF-8');
			$asset_tag			= htmlspecialchars(trim($post['asset_tag']) , ENT_QUOTES, 'UTF-8');
			$tag_no				= htmlspecialchars(trim($post['tag_no']) , ENT_QUOTES, 'UTF-8');
			$date_requested		= trim($post['date_requested']);
			$date_received		= trim($post['date_received']);
			$date_issued		= trim($post['date_issued']);
			$asset_status		= trim($post['asset_status']);
			$remark				= htmlspecialchars($post['remark'], ENT_QUOTES, 'utf-8');  
			
           
                 if (empty($post['user_location'])) {
                   
                    echo ("<SCRIPT LANGUAGE='JavaScript'>
           window.alert('User Location is required')
           window.location.href='https://support.flyairpeace.com/asset.php';
       </SCRIPT>
       <NOSCRIPT>
           <a href='https://support.flyairpeace.com/asset.php'>User Location is required. Click here if you are not redirected.</a>
       </NOSCRIPT>");
            } else {
                    $user_location		= trim($post['user_location']);
            }

			$query = "update apl_asset set
			asset_user = '$asset_user',
			designation = '$designation',
			user_location = '$user_location',
			device_id = '$device_id',
			brand_id = '$brand_id',
			model_product_no = '$model_product_no',
			asset_tag = '$asset_tag',
			tagging_no = '$tag_no',
			date_requested = '$date_requested',
			date_received = '$date_received',
			date_issued = '$date_issued',
			asset_status = '$asset_status',
			remarks = '$remark'
			where asset_id = '$asset_id'";

			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Asset Updated Successful</div>';
			}
		}
	}

	function getAssets() {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT  * FROM apl_asset ORDER BY time_created desc",$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0){
			echo"
				<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"20\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
               <thead>
                    <tr>
						<th>Sn</th>
						<th>Assigned</th>
						<th>Device Name</th>
						<th>Brand name</th>
						<th>Model / Prod.#</th>
						<th>Asset Tag</th>
						<th>Tag No.</th>
						<th>Date Requested</th>
						<th>Date Recevied</th>
						<th width=\"12%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$id 				= $fetchData->asset_id;
				$asset_user			= $fetchData->asset_user;
				$device_id			= $fetchData->device_id;
				$brand_id			= $fetchData->brand_id;
				$model_product_no	= $fetchData->model_product_no;
				$asset_tag			= $fetchData->asset_tag;
				$tag_no				= $fetchData->tagging_no;
				$date_requested		= $fetchData->date_requested;
				$date_received		= $fetchData->date_received;
				
				$deviceData = $this->getDeviceInfo($device_id);
				$device_name = $deviceData->device_name;
				
				$brandData = $this->getBrandInfo($brand_id);
				$brand_name = $brandData->brand_name;

				echo"<tr>
                        <td>$sn</td>
                        <td>$asset_user</td>
                        <td>$device_name</td>
                        <td>$brand_name</td>
                        <td>$model_product_no</td>
                        <td>$asset_tag</span></td>
                        <td>$tag_no</span></td>
                        <td>$date_requested</span></td>
                        <td>$date_received</span></td>
                        <td>
							<a href=\"view_asset.php?asset_id=$id&ed=$sn\" data-toggle=\"modal\" data-target=\"#viewAsset\"><i class=\"fa fa-folder-o\"></i></a>
							<a href=\"edit_asset.php?asset_id=$id&ed=$sn\" data-toggle=\"modal\" data-target=\"#editAsset\"><i class=\"fa fa-edit\"></i></a>
							<a href=\"".$_SERVER['PHP_SELF']."?asset_id=$id&del=$sn\" onclick=\"return confirm('Are you sure you want to delete');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
					</tr>";
			 }
			 echo"</tbody></table>";

	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Asset Added Yet.</div>';
	   }
	}

	function getAssetInfo($assetID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_asset where asset_id = '$assetID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}
	
	
	/* STOP GAP */
	
	
		function addStopgap($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$time = time();

			$stopgap_user			= trim($post['stopgap_user']);
			$designation		= trim($post['designation']);
			$user_location		= trim($post['user_location']);
			$device_id 			= trim($post['device_id']);
			$brand_id			= trim($post['brand_id']);
			$model_product_no	= trim($post['model_product_no']);
			$stopgap_tag			= $post['stopgap_tag'];
			$tag_no				= trim($post['tag_no']);
			$date_returned		= $post['date_returned'];
			$date_given		=     $post['date_given'];
			$stopgap_status		= trim($post['stopgap_status']);
			$remark				= trim($post['remark']);
			
				if($stopgap_status=="Returned") { 
							//$date_returned = $post['date_returned'];
				$date_returned = mysql_real_escape_string($post['date_returned']);
                $date_returned = strtotime($date_returned);

                $date_returned = date('Y-m-d', $date_returned);
						}else{
							$date_returned = "0001-01-01";
						}

			$query = $this->RunQuery("insert into apl_stopgap values(default,'$stopgap_user','$designation','$user_location','$device_id','$brand_id','$model_product_no',
			'$stopgap_tag','$tag_no','$date_returned','$date_given','$stopgap_status','$remark','".$_SESSION['userid']."','$time')",$dbLink);
			if($query) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Stopgap Recorded</div>';
			}
		}
	}

	function updateStopgap($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$stopgap_id    		= $post['stopgap_id'];
			$stopgap_user			= trim($post['stopgap_user']);
			$designation		= trim($post['designation']);
			$user_location		= trim($post['user_location']);
			$device_id 			= trim($post['device_id']);
			$brand_id			= trim($post['brand_id']);
			$model_product_no	= trim($post['model_product_no']);
			$stopgap_tag			= $post['stopgap_tag'];
			$tag_no				= trim($post['tag_no']);
			$date_returned		= trim($post['date_returned']);
			$date_given		= trim($post['date_given']);
			$stopgap_status		= trim($post['stopgap_status']);
			$remark				= trim($post['remark']);
			$remarks				= trim($post['remark']);

			$query = "update apl_stopgap set
			stopgap_user = '$stopgap_user',
			designation = '$designation',
			user_location = '$user_location',
			device_id = '$device_id',
			brand_id = '$brand_id',
			model_product_no = '$model_product_no',
			stopgap_tag = '$stopgap_tag',
			tagging_no = '$tag_no',
			date_returned = '$date_returned',
			date_given = '$date_given',
			stopgap_status = '$stopgap_status',
			remarks = '$remarks'
			where stopgap_id = '$stopgap_id'";

			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Stopgap Updated Successful</div>';
			}
		}
	}

	function getStopgap() {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT  * FROM apl_stopgap ORDER BY time_created desc",$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0){
			echo"
				<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"20\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
               <thead>
                    <tr>
						<th>Sn</th>
						<th>Assigned</th>
						<th>Device Name</th>
						<th>Brand name</th>
						<th>Model / Prod.#</th>
						<th>Stopgap Tag</th>
						<th>Tag No.</th>
						<th>Date Given</th>
						<th>Date Returned</th>
						<th width=\"12%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$id 				= $fetchData->stopgap_id;
				$stopgap_user		= $fetchData->stopgap_user;
				$device_id			= $fetchData->device_id;
				$brand_id			= $fetchData->brand_id;
				$model_product_no	= $fetchData->model_product_no;
				$stopgap_tag			= $fetchData->stopgap_tag;
				$tag_no				= $fetchData->tagging_no;
				$date_given		= $fetchData->date_given;
				$date_returned		= $fetchData->date_returned;
				$deviceData = $this->getDeviceInfo($device_id);
				$device_name = $deviceData->device_name;
				
				$brandData = $this->getBrandInfo($brand_id);
				$brand_name = $brandData->brand_name;

				echo"<tr>
                        <td>$sn</td>
                        <td>$stopgap_user</td>
                        <td>$device_name</td>
                        <td>$brand_name</td>
                        <td>$model_product_no</td>
                        <td>$stopgap_tag</span></td>
                        <td>$tag_no</span></td>
                        <td>$date_given</span></td>
                        <td>$date_returned</span></td>
                        <td>
							<a href=\"view_stopgap.php?stopgap_id=$id&ed=$sn\" data-toggle=\"modal\" data-target=\"#viewStopgap\"><i class=\"fa fa-folder-o\"></i></a>
							<a href=\"edit_stopgap.php?stopgap_id=$id&ed=$sn\" data-toggle=\"modal\" data-target=\"#editStopgap\"><i class=\"fa fa-edit\"></i></a>
							<a href=\"".$_SERVER['PHP_SELF']."?stopgap_id=$id&del=$sn\" onclick=\"return confirm('Are you sure you want to delete');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
					</tr>";
			 }
			 echo"</tbody></table>";

	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Stopgap Added Yet.</div>';
	   }
	}

	function getStopgapInfo($stopgapID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_stopgap where stopgap_id = '$stopgapID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	
	/* END STOP GAP */

	
	
	
	function addRepair($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$time = time();

			$item_name			= $this->mysql_prepare_value(trim($post['item_name']));
			$serial_number		= $this->mysql_prepare_value(trim($post['serial_number']));
			$station_id			= $this->mysql_prepare_value(trim($post['station_id']));
			$date_sent_in 		= $this->mysql_prepare_value(trim($post['date_sent_in']));
			$item_issue			= $this->mysql_prepare_value(trim($post['item_issue']));
			$date_sent_out 		= $this->mysql_prepare_value(trim($post['date_sent_out']));
			$status 			= $this->mysql_prepare_value(trim($post['status']));
			$prompt				= 3;
			$default_date       = '0001-01-01';
			$received_by_default = '0';
			
				$stmt = $dbLink->prepare('SELECT item_prompt FROM apl_repair_list WHERE item_prompt = :prompt');
				$stmt->execute(array(
					':prompt' => $prompt
					));
				$data = $stmt->fetch(PDO::FETCH_ASSOC);
                $data = 1;
                $prompt				= 1;
				if($data = $prompt){
				//	Insert Query;
			
		    $prompt				= 1;
			
			$query  = "insert into apl_repair_list values(default,'$item_name','$serial_number','$station_id','$date_sent_in','$prompt','$item_issue',
			'$date_sent_out','','$default_date','$default_date','','$status','".$_SESSION['userid']."','$received_by_default','$time')";
			
			$runQ = $this->RunQuery($query,$dbLink);
			
			$stationData = $this->getStationInfo($_SESSION['station_id']);	
			$empData = $this->getEmployeeInfo($_SESSION['userid']);
			$x = 0;
			$sn = 0;
			// start
			
			

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = off;                      // Enable verbose debug output SMTP::DEBUG_SERVER
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.office365.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'itsupportdesk@flyairpeace.com';                     // SMTP username
    $mail->Password   = 'Y3z!W3@r30v3r@llB3st';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('itsupportdesk@flyairpeace.com', 'ICT Team');
    $mail->addAddress('admin.procurement@flyairpeace.com', 'Procurement Department');     // Add a recipient
    //$mail->addAddress('emmanuel.nwankwo@flyairpeace.com');               // Name is optional
    $mail->addReplyTo('itsupportdesk@flyairpeace.com', 'Information Communication Department');
    $mail->addCC('itsupportdesk@flyairpeace.com');
    //$mail->addBCC('');

    // Attachments
  //  $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Repair Items::..HQ Station';
    $mail->Body = $this->emailTempOne();
    $mail->Body   .= 'Dear Procurement Team<br /><br />';
	$mail->Body .= "Please, kindly note that the repair item stated below that              was delivered to you on $date_sent_in, has been added in our             repair list.<br /><br />";
	$mail->Body .= "*************************<br />";
	$mail->Body .= $item_issue.'<br />';
	$mail->Body .= "*************************<br />";
	$mail->Body .="<table class=\"table table-striped table-bordered table                  -hover\" border=\"1\">
					<thead>
						<tr>
						<th>SN</th>
						<th>Item Name</th>
						<th>Repair Status</th>
						<th>Serial Number</th>
						<th>Date</th>
						</tr>
					</thead>
					<tbody>";
					
			$sn += 1;	
				if(!empty($item_name) && !empty($serial_number)) {

					//$itemData = $this->getItemInfo($item[$x]);

				$mail->Body .="<tr>
							<td>$sn</td>
							<td>$item_name</td>
							<td>$status</td>
							<td>$serial_number</td>
							<td>$date_sent_in</td>
						</tr>";
				}
			
	$mail->Body .= "</tbody></table><br /><br />";
	$mail->Body .= "$remark<br /><br />";
	$mail->Body .= " <a href=\"http://aplextracts.flyairpeace.com\" class=\"btn             btn-primary\">Go to Air Peace Blog</a><br /><br />";
	$mail->Body .= $empData->firstname . " " . $empData->lastname . "<br/>";
	$mail->Body .= "Regards";

	$mail->Body .= $this->emailTempTwo();
    
   // $mail->AltBody = 'This is a test message. Thank you';

    $mail->send();
    //echo 'Message has been sent';
} catch (Exception $e) {
    //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
		
			
			
			// end
			
			
			/*
			
			$msg = "Dear Procurement Team<br /><br />";
			$msg .= "Please, kindly note that the repair item stated below that was delivered to you on $date_sent_in, has been added in our repair list.<br /><br />";
			$msg .= "*************************<br />";
			$msg .= $item_issue;
			$msg .= "*************************<br />";
			$msg .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
					<thead>
						<tr>
						<th>SN</th>
						<th>Item Name</th>
						<th>Repair Status</th>
						<th>Serial Number</th>
						<th>Date</th>
						</tr>
					</thead>
					<tbody>";
					
			$sn += 1;	
				if(!empty($item_name) && !empty($serial_number)) {

					//$itemData = $this->getItemInfo($item[$x]);

					$msg .="<tr>
							<td>$sn</td>
							<td>$item_name</td>
							<td>$status</td>
							<td>$serial_number</td>
							<td>$date_sent_in</td>
						</tr>";
				}
			
			$msg .= "</tbody></table><br /><br />";
			$msg .= "$remark<br /><br />";
			$msg .= " <a href=\"http://aplextracts.flyairpeace.com\" class=\"btn btn-primary\">Go to Air Peace Blog</a><br /><br />";
			$msg .= $empData->firstname . " " . $empData->lastname . "<br/>";
			$msg .= "Regards";

			$emailMessage = $this->emailTemplate($msg);

			$headers[] = 'MIME-Version: 1.0';
			$headers[] = 'Content-type: text/html; charset=iso-8859-1';
			$headers[] = 'From: ' . $_SESSION['username'] . ' ' . $_SESSION['email'];
			$headers[] = 'Cc: ' . 'itsupportdesk@flyairpeace.com';

			$sendMail = mail("admin.procurement@flyairpeace.com", "Repair Items::..".$stationData->station_name." Station", $emailMessage, implode("\r\n",$headers));
		

			*/
			
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Repair Item Saved</div>';
		                     }
				    
				        }
				        else{
				            
			
	           
				return '<div class="alert alert-danger"><i class="fa fa-check"></i> Danger! Item have been added three times. </div>';
				
				        
				    
				    
				}
		}
	}

	
	
	
	
	
	function updateRepairSecond($post, $process) {
		
		$dbLink = $this->connect_db();
	
		if(isset($process)) {

			$serial_number		= $this->mysql_prepare_value(trim($post['serial_number']));
			
			
			/*
			$prompt				= 3;
			
			$runQ = $this->RunQuery("SELECT  * FROM apl_repair_list WHERE item_prompt = '$prompt'",$dbLink);
			$fetchData = $runQ->fetch();

	   if($prompt = $fetchData->item_prompt){
				return '<div class="alert alert-danger"><i class="fa fa-check"></i> Alert: Repair Item have been added two times </div>';
				}
				else {
					*/
			$query = "update apl_repair_list set
			item_prompt  = item_prompt + 1 WHERE serial_number = '$serial_number'";
			
			//return $query;

			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Repair Item Updated Successful</div>';
				
				}
		}
	}


	function updateRepair($post, $process) {
		
		$dbLink = $this->connect_db();
	
		if(isset($process)) {

			$repair_id    		= $post['repair_id'];
			$item_name			= htmlspecialchars($post['item_name']);
			$serial_number		= trim($post['serial_number']);
			$station_id 		= trim($post['station_id']);
			$date_sent_in		= trim($post['date_sent_in']);
			$item_issue			= htmlspecialchars($post['item_issue']);
			$date_sent_out		= trim($post['date_sent_out']);
			$status				= trim($post['status']);
			$remark				= trim($post['remark']);
			$work_done			= trim($post['work_done']);
			$proc_return_date	= trim($post['proc_return_date']);
			$return_date		= trim($post['station_return_date']);

            //echo $date_sent_out; 
            
            
			$query = "update apl_repair_list set
			item_name  = '$item_name',
			serial_number  = '$serial_number ',
			originating_station = '$station_id',
			date_in  = '$date_sent_in',
			item_issue = '$item_issue',
			repair_sent_date = '$date_sent_out',
			work_done = '$work_done',
			repair_date_returned  = '$proc_return_date',
			station_return_date  = '$return_date',
			remark = '$remark',
			status = '$status',
			return_receivced_by = '".$_SESSION['userid']."'
			where repair_id = '$repair_id'";
			
			//return $query;

			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Repair Item Updated Successful</div>';
			}
		}
	}

	function getRepair() {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT  * FROM apl_repair_list ORDER BY time_created desc",$dbLink);
		$numRows = $runQ->rowCount();

	   if($numRows > 0){
			echo"
				<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"20\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
               <thead>
                    <tr>
						<th>#</th>
						<th>Item Name</th>
						<th>Serial Number</th>
						<th>Station</th>
						<th>Date to Procument</th>
						<th>Procument return</th>
						<th>Status</th>
						<th>Station return</th>
						<th width=\"12%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($fetchData = $runQ->fetch()) {
				$sn += 1;
				$repair_id 				= $fetchData->repair_id;
				$item_name			= $fetchData->item_name;
				$serial_number		= $fetchData->serial_number;
				$station_id			= $fetchData->originating_station;
				$repair_sent_date	= $fetchData->repair_sent_date ;
				$repair_returned 	= $fetchData->repair_date_returned;
				$status				= $fetchData->status;
				$station_return		= $fetchData->station_return_date;
				
				$stationData = $this->getStationInfo($station_id);
				$station_name = $stationData->station_name;
				

				echo"<tr>
                        <td>$sn</td>
                        <td>$item_name</td>
                        <td>$serial_number</td>
                        <td>$station_name</td>
                        <td>$repair_sent_date</td>
                        <td>";
						if($repair_returned=="0000-00-00" || $repair_returned== "0001-01-01") { 
						//if($repair_returned=="0000-00-00")
							echo "Not Returned";
						}else{
							echo $repair_returned;
						}
						echo"</td>
                        <td><span class=\"label label-";
							if($status=="Sent for Repair") { 
								echo "danger"; 
							}elseif($status=="Returned From Repair") { 
								echo "warning"; 
							}elseif($status=="Sent Back to Station") { 
								echo "success"; 
							}
						echo"\">$status</span></td>
                        <td>";
						if($station_return=="0000-00-00" || $station_return== "0001-01-01") { 
							echo "Not Returned";
						}else{
							echo $station_return;
						}
						echo"</td>
                        <td>
							<a href=\"update-repair.php?rid=$repair_id&ed=$sn\" data-toggle=\"modal\" data-target=\"#editRepair\"><i class=\"fa fa-edit\"></i></a>
							<a href=\"".$_SERVER['PHP_SELF']."?rid=$repair_id&del=$sn\" onclick=\"return confirm('Are you sure you want to delete');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
					</tr>";
			 }
			 echo"</tbody></table>";

	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Repairs Added Yet.</div>';
	   }
	}

	function getRepairInfo($repairID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_repair_list where repair_id = '$repairID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getDeviceInfo($deviceID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_device_asset where device_id = '$deviceID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getBrandInfo($brandID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_asset_brand where brand_id = '$brandID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getModuleInfo($moduleID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_app_module where module_id = '$moduleID'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function listModules($module_id=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT module_id, module_name FROM apl_app_module ORDER BY position",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($module = $runQ->fetch()) {
				$mid = $module->module_id;
				$moduleName = $module->module_name;

				echo"<option value=\"$mid\" ";
				if($mid==$module_id) { echo"selected"; }
				echo">$moduleName</option>\n";
			}
		}
	}

	function listDevice($deviceID=NULL) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT device_id, device_name FROM apl_device_asset ORDER BY device_name",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($device = $runQ->fetch()) {
				$did = $device->device_id;
				$deviceName = $device->device_name;

				echo"<option value=\"$did\"";
				if($deviceID==$did){ echo " selected"; }
				echo">$deviceName</option>\n";
			}
		}
	}

	function listBrand($brandID=NULL) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT brand_id, brand_name FROM apl_asset_brand ORDER BY brand_name",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($brand = $runQ->fetch()) {
				$bid = $brand->brand_id;
				$brandName = $brand->brand_name;

				echo"<option value=\"$bid\"";
				if($brandID==$bid){ echo " selected"; }
				echo">$brandName</option>\n";
			}
		}
	}


	function listRoleModulesForUpdate($roleID) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT role_id,modules FROM apl_access_roles where role_id = '$roleID'",$dbLink);
		$num_rows = $runQ->rowCount();

		$role = $runQ->fetch();
		$rid = $role->role_id;
		$modules = explode(",",$role->modules);

		//get all modules
		$runQ1 = $this->RunQuery("SELECT module_id, module_name FROM apl_app_module ORDER BY position",$dbLink);
		$num_rows1 = $runQ1->rowCount();

		if($num_rows1>0) {
			while($module = $runQ1->fetch()) {
				$mid = $module->module_id;
				$moduleName = $module->module_name;
				if(in_array($mid,$modules)){
					echo"<option value=\"$mid\" selected>$moduleName</option>\n";
				}else{
					echo"<option value=\"$mid\">$moduleName</option>\n";
				}
			}
		}
	}

	function addAccessRole($post, $process) {
		$dbLink = $this->connect_db();

		$time = time();

		if(isset($process)) {

			$name    	= trim($post['access_name']);
			$modules	= $post['modules'];
			$privileges	= $post['privilege'];

			//prepare selected modules for insertion into db
			$module = implode(',',$modules);

			//prepare selected privileges for insertion into db
			$holdPermission = array();
			foreach($privileges as $privilege) {
				if(isset($privilege)) {
					$holdPermission[] = $privilege;
				}
			}
			$permissions = implode(',',$holdPermission);


			$query = "insert into apl_access_roles values(default,'$name','$module','$permissions','".$_SESSION['userid']."','$time')";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Access Role Created</div>';
			}
		}
	}

	function updateAccessRole($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$role_id    =trim( $post['role_id']);
			$name    	= trim($post['access_name']);
			$modules	= $post['modules'];
			$privileges	= $post['privilege'];

			//prepare selected modules for insertion into db
			$module = implode(',',$modules);

			//prepare select privileges for insertion into db
			$holdPermission = array();
			foreach($privileges as $privilege) {
				if(isset($privilege)) {
					$holdPermission[] = $privilege;
				}
			}
			$permissions = implode(',',$holdPermission);


			$query = "update apl_access_roles set role_name = '$name',
			modules = '$module',
			privileges = '$permissions' WHERE role_id = '$role_id'";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {

				return '<div class="alert alert-success"><i class="fa fa-check"></i> Access Role Updated</div>';
			}
		}
	}

	function getAccessRoles() {
		$dbLink = $this->connect_db();

		$query = "SELECT * FROM apl_access_roles ORDER BY role_name";
		$runQ = $this->RunQuery($query,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Access Role Name</th>
					<th class=\"tbli_headder\">Created By</th>
					<th class=\"tbli_headder\">Created on</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($roles = $runQ->fetch()) {
				$sn += 1;
				$id 		= $roles->role_id;
				$name 		= $roles->role_name;
				$userid		= $roles->userid;
				$created	= date("D d M, Y: H:ia",$roles->time_created);

				$userData = $this->getUserInfo($userid);
				$createdBy = $userData->firstname;

				echo"<tr>
                        <td>$sn</td>
                        <td>$name</td>
                        <td>$createdBy </td>
                        <td>$created </td>
                        <td>
							<a href=\"edit-access-role.php?rid=$id\"><span class=\"add-on small-size\">Edit</span></a> |
							<a href=\"".$_SERVER['PHP_SELF']."?rid=$id&del=$sn\" onclick=\"return confirm('Are you sure you want to delete this?');\" ><span class=\"add-on small-size\">Delete</span></a>
						</td>
                     </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Access Role Created</div>';
	   }
	}

	function getAccessRoleInfo($roleID) {
		$dbLink = $this->connect_db();
		$query = "select * from apl_access_roles where role_id = '$roleID'";
		$runQ = $this->RunQuery($query,$dbLink);
		$role = $runQ->fetch();
		return $role;
	}

	function addUser($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$name    	= trim($post['fname']);
			$phone		= trim($post['phone']);
			$email		= trim($post['email']);
			$address	= trim($post['address']);
			$username	= trim($post['username']);
			$password	= trim($post['password']);
			$Level		= trim($post['level']);

			$time = time();


			$query = "insert into apl_users values('','$name','$email','$phone','$address','$username','".md5($password)."','','no','','0','$Level','','Live')";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i>User Added</div>';
			}
		}
	}

	function updateUser($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$user_id    = trim($post['staff_id']);
			$fname    	= trim($post['first-name']);
			$lname      = trim($post['last-name']);
			$gender		= trim($post['user-gender']);
			$phone		= trim($post['user-phone']);
			$dept		= trim($post['user-dept']);
			$station	= trim($post['user-station']);
			$email		= trim($post['user-email']);
			$password	= trim($post['user-pass']);
			$role		= trim($post['role']);

			$time = time();

			$query = "update apl_employees set station_id = '$station',
			firstname = '$fname',
			lastname = '$lname',
			gender = '$gender',
			phone = '$phone',
			department_id = '$dept',
			cooperate_email  = '$email'";
			if($password!="") { $query .= ",password = '".md5($password)."'";}
			$query .= ", access_role = '$role' WHERE id = '$user_id'";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> User Updated</div>';
			}
		}
	}

	function getallUsers() {
		$dbLink = $this->connect_db();

		$query = "SELECT * FROM apl_users ORDER BY id Desc";
		$runQ = $this->RunQuery($query,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Name</th>
					<th class=\"tbli_headder\">Phone </th>
					<th class=\"tbli_headder\">Email </th>
					<th class=\"tbli_headder\">Level</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($eng = $runQ->fetch()) {
				$sn += 1;
				$id 		= $eng->id;
				$name 		= $eng->name;
				$phone 		= $eng->phone;
				$email 		= $eng->email;
				$level 		= $eng->user_level;

				echo"<tr>
                        <td>$sn</td>
                        <td>$name</td>
                        <td>$phone </td>
                        <td>$email </td>
                        <td>$level</td>
                        <td>
							<a href=\"".$_SERVER['PHP_SELF']."?eid=$id&ac=ed#userform\"><span class=\"add-on small-size\">Edit</span></a> |
							<a href=\"".$_SERVER['PHP_SELF']."?eid=$id&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\" ><span class=\"add-on small-size\">Delete</span></a>
						</td>
                     </tr>";

			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No User Created</div>';
	   }
	}

	function getCaseLogs() {
		$dbLink = $this->connect_db();

		$query = "SELECT * FROM apl_case_log where log_status !='Empty' ORDER BY log_id Desc";
		$runQ = $this->RunQuery($query,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"20\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\"># Ref</th>
					<th class=\"tbli_headder\">Case Category</th>
					<th class=\"tbli_headder\">Caller Name (PNR)</th>
					<th class=\"tbli_headder\">Caller Phone </th>
					<th class=\"tbli_headder\">Department</th>
					<th class=\"tbli_headder\">Status</th>
					<th class=\"tbli_headder\">Opened by/Closed by</th>
					<th class=\"tbli_headder\">Date Opend/Closed</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($callog = $runQ->fetch()) {
				$sn += 1;
				$id 		= $callog->log_id;
				$category	= $callog->log_category;
				$callerName	= $callog->caller_name;
				$phone 		= $callog->caller_phone;
				$casePNR		= $callog->case_pnr;
				$logDept	= $callog->log_dept;
				$logStatus	= $callog->log_status;
				$openAgent	= $callog->open_agent_id;
				$closeAgent	= $callog->close_agent_id;
				$opened		= date("d-m-Y",$callog->time_opened);
				$closed		= date("d-m-Y",$callog->time_closed);

				//getusers
				$getOpenAgentData = $this->getEmployeeInfo($openAgent);
				$openAgentName = $getOpenAgentData->firstname;
				$getCloseAgentData = $this->getEmployeeInfo($closeAgent);
				$closeAgentName = $getCloseAgentData->firstname;

				$departmentData = $this->getDepartmentInfo($logDept);
				$departName = $departmentData->dept_name;

				echo"<tr>
                        <td><a href=\"open-case-log.php?lid=$id\">#$id</a></td>
                        <td>$category</td>
                        <td>$callerName";
												if($casePNR!=""){ echo " ($casePNR)";}
												echo"</td>
                        <td>$phone </td>
                        <td>$departName</td>
                        <td><span class=\"label ";
						switch($logStatus) {
								case "Open":
								echo"label-danger";
								break;
								case "Closed":
								echo"label-success";
								break;
							}
						echo"\">$logStatus</span></td>
                        <td>$openAgentName / ";
						if($closeAgent==0) {echo"still open";}else{echo $closeAgentName;}
						echo"</td>
                        <td>$opened / ";
						if($callog->time_closed==0) {echo"still open";}else{echo $closed;}
						echo"</td>
                        <td>
							<a href=\"open-case-log.php?lid=$id\"><span class=\"add-on small-size\" title=\"open log\"><i class=\"fa fa-ticket\"></i> open</span></a>
						</td>
                     </tr>";

			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Case Logged yet</div>';
	   }
	}

	function getOpenCaseLogs() {
		$dbLink = $this->connect_db();

		$query = "SELECT * FROM apl_case_log where log_status ='Open' ORDER BY time_opened Desc";
		$runQ = $this->RunQuery($query,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"20\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\"># Ref</th>
					<th class=\"tbli_headder\">Case Category</th>
					<th class=\"tbli_headder\">Caller Name (PNR)</th>
					<th class=\"tbli_headder\">Caller Phone </th>
					<th class=\"tbli_headder\">Department</th>
					<th class=\"tbli_headder\">Status</th>
					<th class=\"tbli_headder\">Opened by</th>
					<th class=\"tbli_headder\">Date Opend</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($callog = $runQ->fetch()) {
				$sn += 1;
				$id 		= $callog->log_id;
				$category	= $callog->log_category;
				$callerName	= $callog->caller_name;
				$phone 		= $callog->caller_phone;
				$casePNR = $callog->case_pnr;
				$logDept	= $callog->log_dept;
				$logStatus	= $callog->log_status;
				$openAgent	= $callog->open_agent_id;
				$opened		= date("d-m-Y",$callog->time_opened);

				//getusers
				$getOpenAgentData = $this->getEmployeeInfo($openAgent);
				$openAgentName = $getOpenAgentData->firstname;

				$departmentData = $this->getDepartmentInfo($logDept);
				$departName = $departmentData->dept_name;

				echo"<tr>
                        <td><a href=\"open-case-log.php?lid=$id\">#$id</a></td>
                        <td>$category</td>
                        <td>$callerName";
												if($casePNR!=""){ echo " ($casePNR)";}
												echo"</td>
                        <td>$phone </td>
                        <td>$departName</td>
                        <td><span class=\"label label-danger\">$logStatus</span></td>
                        <td>$openAgentName</td>
                        <td>$opened</td>
                        <td>
							<a href=\"open-case-log.php?lid=$id\"><span class=\"add-on small-size\" title=\"open log\"><i class=\"fa fa-ticket\"></i> open</span></a>
						</td>
                     </tr>";

			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-info">No Open Case</div>';
	    }
	}

	function getViewCaseLogs() {
		$dbLink = $this->connect_db();

		$query = "SELECT * FROM apl_case_log where log_status !='Empty' ORDER BY time_opened Desc";
		$runQ = $this->RunQuery($query,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"20\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\"># Ref</th>
					<th class=\"tbli_headder\">Case Category</th>
					<th class=\"tbli_headder\">Caller Name (PNR)</th>
					<th class=\"tbli_headder\">Caller Phone </th>
					<th class=\"tbli_headder\">Department</th>
					<th class=\"tbli_headder\">Status</th>
					<th class=\"tbli_headder\">Opened by</th>
					<th class=\"tbli_headder\">Date Opend</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($callog = $runQ->fetch()) {
				$sn += 1;
				$id 		= $callog->log_id;
				$category	= $callog->log_category;
				$callerName	= $callog->caller_name;
				$phone 		= $callog->caller_phone;
				$casePNR = $callog->case_pnr;
				$logDept	= $callog->log_dept;
				$logStatus	= $callog->log_status;
				$openAgent	= $callog->open_agent_id;
				$opened		= date("d-m-Y",$callog->time_opened);

				//getusers
				$getOpenAgentData = $this->getEmployeeInfo($openAgent);
				$openAgentName = $getOpenAgentData->firstname;

				$departmentData = $this->getDepartmentInfo($logDept);
				$departName = $departmentData->dept_name;

				echo"<tr>
                        <td><a href=\"open-case-log.php?lid=$id\">#$id</a></td>
                        <td>$category</td>
                        <td>$callerName";
												if($casePNR!=""){ echo " ($casePNR)";}
												echo"</td>
                        <td>$phone </td>
                        <td>$departName</td>
                        <td><span class=\"label ";
						switch($logStatus) {
								case "Open":
								echo"label-danger";
								break;
								case "Closed":
								echo"label-success";
								break;
							}
						echo"\">$logStatus</span></td>
                        <td>$openAgentName</td>
                        <td>$opened</td>
                        <td>
							<a href=\"open-case-log.php?lid=$id\"><span class=\"add-on small-size\" title=\"open log\"><i class=\"fa fa-ticket\"></i> open</span></a>
						</td>
                     </tr>";

			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-info">No Open Case</div>';
	    }
	}

	function getDeptCaseLogs() {
		$dbLink = $this->connect_db();

		$query = "SELECT case_id,department FROM apl_case_assignment where department ='".$_SESSION['dept_id']."' group BY case_id";
		$runQ = $this->RunQuery($query,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"20\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\"># Ref</th>
					<th class=\"tbli_headder\">Case Category</th>
					<th class=\"tbli_headder\">Caller Name</th>
					<th class=\"tbli_headder\">Caller Phone </th>
					<th class=\"tbli_headder\">Department</th>
					<th class=\"tbli_headder\">Status</th>
					<th class=\"tbli_headder\">Opened by/Closed by</th>
					<th class=\"tbli_headder\">Date Opend/Closed</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($callog = $runQ->fetch()) {
				$sn += 1;
				$id 		= $callog->case_id;
				$caseData = $this->getCaseInfo($id);

				$category	= $caseData->log_category;
				$callerName	= $caseData->caller_name;
				$phone 		= $caseData->caller_phone;
				$logStatus	= $caseData->log_status;
				$logDept	= $caseData->log_dept;
				$openAgent	= $caseData->open_agent_id;
				$closeAgent	= $caseData->close_agent_id;
				$opened		= date("d-m-Y",$caseData->time_opened);
				$closed		= date("d-m-Y",$caseData->time_closed);

				//getusers
				$getOpenAgentData = $this->getEmployeeInfo($openAgent);
				$openAgentName = $getOpenAgentData->firstname;
				$getCloseAgentData = $this->getEmployeeInfo($closeAgent);
				$closeAgentName = $getCloseAgentData->firstname;

				$departmentData = $this->getDepartmentInfo($logDept);
				$departName = $departmentData->dept_name;

				echo"<tr>
                        <td><a href=\"open-case-log.php?lid=$id\">#$id</a></td>
                        <td>$category</td>
                        <td>$callerName </td>
                        <td>$phone </td>
                        <td>$departName</td>
                        <td><span class=\"label ";
						switch($logStatus) {
								case "Open":
								echo"label-danger";
								break;
								case "Closed":
								echo"label-success";
								break;
							}
						echo"\">$logStatus</span></td>
                        <td>$openAgentName / ";
						if($closeAgent==0) {echo"still open";}else{echo $closeAgentName;}
						echo"</td>
                        <td>$opened / ";
						if($callog->time_closed==0) {echo"still open";}else{echo $closed;}
						echo"</td>
                        <td>
							<a href=\"open-case-log.php?lid=$id\"><span class=\"add-on small-size\" title=\"open log\"><i class=\"fa fa-ticket\"></i> open</span></a>
						</td>
                     </tr>";

			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Case Logged yet</div>';
	   }
	}

	function generateExcel_Case_Log($query) {
		$dbLink = $this->connect_db();

		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "call_log_".$creator.$time.'.xlsx';

			//execute query
			$runQ = $this->RunQuery($query,$dbLink);


			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Call Log Report by ".$creator)
						->setSubject("Call Log Report")
						->setDescription("Call Log Report")
						->setKeywords("Call Log Report")
						->setCategory("Call Log Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1','# Ref')
					->setCellValue('B1','Case Category')
					->setCellValue('C1','Caller Name')
					->setCellValue('D1','Caller Phone')
					->setCellValue('E1',' Case Description')
					->setCellValue('F1','Case Status')
					->setCellValue('G1','Opened by / Closed by')
					->setCellValue('H1','Date Opend/Closed');
					for($col = ord('a'); $col<= ord('h'); $col++){
						$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
					}
					$sn = 2;
			while($callog = $runQ->fetch()) {
				$id 		= $callog->log_id;
				$category	= $callog->log_category;
				$callerName	= $callog->caller_name;
				$phone 		= $callog->caller_phone;
				$caseDesc	= $this->limit_words($callog->case_description,5);
				$logStatus	= $callog->log_status;
				$openAgent	= $callog->open_agent_id;
				$closeAgent	= $callog->close_agent_id;
				$opened		= date("d-m-Y",$callog->time_opened);
				$closed		= date("d-m-Y",$callog->time_closed);

				//getusers
				$getOpenAgentData = $this->getEmployeeInfo($openAgent);
				$openAgentName = $getOpenAgentData->firstname;
				$getCloseAgentData = $this->getEmployeeInfo($closeAgent);
				$closeAgentName = $getCloseAgentData->firstname;

				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $id)
						->setCellValue('B'.$sn, $category)
						->setCellValue('C'.$sn, $callerName)
						->setCellValue('D'.$sn, $phone)
						->setCellValue('E'.$sn, $caseDesc)
						->setCellValue('F'.$sn, $logStatus)
						->setCellValue('G'.$sn, $openAgentName." / ".$closeAgentName)
						->setCellValue('H'.$sn, $opened." / ".$closed);

				$sn++;
			}
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
			// If you want to output e.g. a PDF file, simply do:
			//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
			PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
			$objWriter->save("exports/".$FileName);

				return $FileName;
	}

	function getUserInfo($userID) {
		$dbLink = $this->connect_db();
		$query = "select * from apl_employees where id = '$userID'";
		$runQ = $this->RunQuery($query,$dbLink);
		$user = $runQ->fetch();
		return $user;
	}

	function countTicket() {
		$dbLink = $this->connect_db();
		$sql = "SELECT ticket_id FROM apl_tickets where dropped = '0'";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();
		return $num_rows;
	}

	function countOpenTickets() {
		$dbLink = $this->connect_db();
		$sql = "select ticket_id from apl_tickets where status = 'Closed' and dropped = '0'";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();
		return $num_rows;
	}

	function countClosedTickets() {
		$dbLink = $this->connect_db();
		$sql = "select ticket_id from apl_tickets where status = 'Open' and dropped = '0'";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();
		return $num_rows;
	}

	function canBeAssigned($privileg,$empid=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT id,firstname,access_role FROM apl_employees",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($emp = $runQ->fetch()) {
				$emp_id = $emp->id;
				$fname = $emp->firstname;
				$roleid = $emp->access_role;
				//get role access details
				$accessData = $this->getAccessRoleInfo($roleid);
				$privileges = explode(",",$accessData->privileges);

				//check if has "can be assigned ticket" privilege
				if(in_array($privileg,$privileges)){
					echo"<option value=\"$emp_id\" ";
					if($empid==$emp_id){ echo"selected";}
					echo">$fname</option>\n";
				}
			}
		}
	}

	function listRoles($roleID=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT role_id,role_name FROM apl_access_roles",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($role = $runQ->fetch()) {
				$role_id = $role->role_id;
				$role_name = $role->role_name;

				echo"<option value=\"$role_id\" ";
				if($roleID==$role_id){ echo"selected";}
				echo">$role_name</option>\n";
			}
		}
	}

	function listStation($stationID=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT station_id,station_name FROM apl_station",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($station = $runQ->fetch()) {
				$station_id = $station->station_id;
				$station_name = $station->station_name;

				echo"<option value=\"$station_id\" ";
				if($stationID==$station_id){ echo"selected"; }
				echo">$station_name</option>\n";
			}
		}
	}

	function listLocation($locationID=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT location_id,location_name FROM apl_asset_location order by location_name asc",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($location = $runQ->fetch()) {
				$location_id = $location->location_id;
				$location_name = $location->location_name;

				echo"<option value=\"$location_id\" ";
				if($locationID==$location_id){ echo" selected"; }
				echo">$location_name</option>\n";
			}
		}
	}

	function listCallLogAgent($action,$agentID=null) {
		$dbLink = $this->connect_db();
		$query = "SELECT ";
		if($action=="open"){ $query .= "open_agent_id"; }elseif($action=="close"){ $query .= "close_agent_id"; }
		$query .=" FROM apl_case_log group by ";
		if($action=="open"){ $query .= "open_agent_id"; }elseif($action=="close"){ $query .= "close_agent_id"; }
		//$query .=", having log_status != 'Empty'";
		$runQ = $this->RunQuery($query,$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			while($logAgent = $runQ->fetch()) {
				if($action=="open"){
					$agent_id = $logAgent->open_agent_id;

					//get agent name
					$empData = $this->getEmployeeInfo($agent_id);
					$agentName = $empData->firstname;

					echo"<option value=\"$agent_id\" ";
					if($agentID==$agent_id){ echo"selected"; }
					echo">$agentName</option>\n";

				}elseif($action=="close"){
					$agent_id = $logAgent->close_agent_id;
					if($agent_id!=0) {
					//get agent name
					$empData = $this->getEmployeeInfo($agent_id);
					$agentName = $empData->firstname;

					echo"<option value=\"$agent_id\" ";
					if($agentID==$agent_id){ echo"selected"; }
					echo">$agentName</option>\n";
					}
				}
			}
		}
	}

	function getEmployeeInfo($id) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_employees where id = '$id'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getRoleInfo($id) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_access_roles where role_id = '$id'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getItemInfo($id) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_it_store_item where item_id = '$id'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getTicketInfo($id) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_tickets where ticket_id = '$id'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getStationInfo($id) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_station where station_id = '$id'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function getLocationInfo($id) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("select * from apl_asset_location where location_id = '$id'",$dbLink);
		$fetchData = $runQ->fetch();
		return $fetchData;
	}

	function genTicketRef() {
		$dbLink = $this->connect_db();
		$query = "SELECT ticket_ref FROM apl_tickets order by time_created desc LIMIT 1";
		$runQ = $this->RunQuery($query,$dbLink);
		$counRow = $runQ->rowCount();
		if($counRow>0) {
			$ref = $runQ->fetch();
			$tRef = $ref->ticket_ref;
			$newRef = $tRef + 1;
			return $newRef;
		}else{
			return 1;
		}
	}

	function addTicket($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			if(in_array("assign_ticket",$_SESSION['privileges'])) {
				$severity  	= $post['severity'];
				$subject	= trim($post['subject']);
				$message	= trim($post['message']);
				$owner		= trim($post['owner']);
				$station	= trim($post['station']);
				$assigned	= trim($post['assigned']);

				//generate ticket reference
				$ticketRef = $this->genTicketRef();

				$query = "insert into apl_tickets values(default,'$ticketRef','$owner','$station','$severity','$subject','$message','$assigned','$time','$time','In Progress','".date("Y-m-d",$time)."','0','0','".$_SESSION['userid']."','0')";
				$runQ = $this->RunQuery($query,$dbLink);
				$ticket_id = $dbLink->lastInsertId();

				//insert into ticket assignment history
				$query2 = "insert into apl_ticket_assignment values(default,'$ticket_id','$assigned','".$_SESSION['userid']."','$time')";
				$runQ2 = $this->RunQuery($query2,$dbLink);

				if($runQ && $runQ2) {

					//get ticket owner details
					$ownerData = $this->getEmployeeInfo($_SESSION['userid']);
					$ownerName = $ownerData->firstname;

					//get ticket details
					$ticketData = $this->getTicketInfo($ticket_id);
					$ref = $ticketData->ticket_ref;

					//send email to assigned
					$empData = $this->getEmployeeInfo($assigned);
					$firstname = $empData->firstname;
					$emailAddress = $empData->cooperate_email;

					$send  = mail($to, $subject, $message, $headers);
					$msg = "Dear $firstname<br /><br />A new Ticket (#$ref) has been assigned to you<br /><br />Subject: $subject <br />Description: $message<br />Assigned to: $firstname<br />Date Assigned: ".date("Y-m-d h:ia")."<br /><br />Regards<br />";

					$emailMessage = $this->emailTemplate($msg);

					$headers = "From: ".$_SESSION['email']." \r\n ";
					$headers .=	"Reply-To: ".Non_Reply." \r\n ";
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-type: text/html\r\n";

					mail($emailAddress, "New Ticket #$ref Assigned to you", $emailMessage, $headers);
					mail("itsupportdesk@flyairpeace.com","New Ticket #$ref Opened by $ownerName",$emailMessage, $headers);

					return '<div class="alert alert-success"><i class="fa fa-check"></i> Ticket Saved Successfully</div>';
				}
			}else{
				$severity = $post['severity'];
				$subject	= trim($post['subject']);
				$message	= trim($post['message']);

				//generate ticket reference
				$ticketRef = $this->genTicketRef();

				$query = "insert into apl_tickets values(default,'$ticketRef','".$_SESSION['userid']."','".$_SESSION['station_id']."','$severity','$subject','$message','0','0','$time','Open','".date("Y-m-d")."','0','0',".$_SESSION['userid'].",'0')";
				$runQ = $this->RunQuery($query,$dbLink);
				$ticket_id = $dbLink->lastInsertId();

				if($runQ) {
					//get ticket owner details
					$empData = $this->getEmployeeInfo($_SESSION['userid']);
					$firstname = $empData->firstname;
					$station_id = $empData->station_id;
					$stationData = $this->getStationInfo($station_id);
					$stationName = $stationData->station_name;

					//get ticket details
					$ticketData = $this->getTicketInfo($ticket_id);
					$ref = $ticketData->ticket_ref;

					$msg = "Dear IT Support,<br /><br />
					A new Ticket (#$ref) has been Opened<br /><br />
					Subject: $subject <br />Description: $message<br />
					Opened By: $firstname<br />
					Date Created: ".date("Y-m-d h:ia")."<br />
					Station: $stationName<br /><br />

					Regards<br />";

					$emailMessage = $this->emailTemplate($msg);

					$headers = "From: ".$_SESSION['email']." \r\n ";
					$headers .=	"Reply-To: ".Non_Reply." \r\n ";
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-type: text/html\r\n";

					mail("itsupportdesk@flyairpeace.com","New Ticket [#$ref] Opened from $stationName",$emailMessage,$headers);
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Ticket Sent to IT Support Desk Successfully</div>';
				}
			}
		}
	}

	function assignTicket($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$ticket_id	= trim($post['ticket_id']);
			$assigned	= trim($post['assigned']);

			//update ticket details
			$query = "update apl_tickets set assigned = '$assigned', status = 'In Progress', date_assigned = '$time' where ticket_id = '$ticket_id'";
			$runQ = $this->RunQuery($query,$dbLink);

			//update ticket assignement history
			$query2 = "insert into apl_ticket_assignment values(default,'$ticket_id','$assigned','".$_SESSION['userid']."','$time')";
			$runQ2 = $this->RunQuery($query2,$dbLink);

			if($runQ && $runQ2) {
				//get ticket details
				$ticketData = $this->getTicketInfo($ticket_id);
				$subject = $ticketData->ticket_subject;
				$message = $ticketData->ticket_desc;
				//send email to assigned
				$empData = $this->getEmployeeInfo($assigned);
				$firstname = $empData->firstname;
				$emailAddress = $empData->cooperate_email;

				$msg = "Dear $firstname<br /><br />
				A new Ticket (#$ticketRef) has been assigned to you<br /><br />
				Subject: $subject<br />Description: $message<br />
				Date Assigned: ".date("Y-m-d H:ia",$time)."<br /><br />
				Regards<br />
				IT Support Desk";

				$emailMessage = $this->emailTemplate($msg);

				$headers = "From: ".$_SESSION['email']." \r\n ";
				$headers .=	"Reply-To: ".Non_Reply." \r\n ";
				$headers .= "MIME-Version: 1.0\r\n";
				$headers .= "Content-type: text/html\r\n";

				$sendmail = mail($emailAddress,"New Ticket #$ticketRef Assigned to you",$emailMessage,$headers);

				if($sendmail) {
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Ticket Sent Successfully</div>';
				}
			}
		}
	}

	function getOpenTickets() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_tickets where status = 'Open' and dropped = '0' ORDER BY time_created";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			 $sn = 0;
			 echo"<div class=\"portlet-content\">


              <div class=\"table-responsive\">

                <table id=\"user-signups\" class=\"table table-striped table-bordered table-checkable\">
                  <thead>
                    <tr>
                      <th>Ref</th>
                      <th>Subject</th>
                      <th>Severity</th>
                      <th>Owned By</th>
                      <th>Status</th>
                      <th>Opened</th>
                    </tr>
                  </thead>

                  <tbody>";
			 while($ticket = $runQ->fetch()) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$tRef 			= $ticket->ticket_ref;
				$subject 		= $ticket->ticket_subject;
				$opened 		= date("d M, Y: h:ia",$ticket->time_created);
				$closed	 		= $ticket->close_date;
				$status 		= $ticket->status;
				$severity 		= $ticket->severity;
				$created_by 	= $ticket->created_by;
				$assigned 		= $ticket->assigned;

				$ownedBy = $this->getEmployeeInfo($created_by);
				$ownerName = $createdBy->firstname;

				$empData = $this->getEmployeeInfo($assigned);
				$empName = $empData->firstname;

				echo"<tr>
                        <td>ATT$tRef-";
						switch($severity) {
							case "Low Level":
							echo"0";
							break;
							case "Normal Level":
							echo"1";
							break;
							case "High Level":
							echo"2";
							break;
						}
						echo"</td>
                        <td><a href=\"ticket-details.php?tid=$id\" title=\"$subject\" style=\"text-decoration:none;\">";
							echo $this->limit_words($ticket->ticket_subject,5);
						echo"...</a></td>
                        <td><span class=\"label ";
									switch($severity) {
											case "Low Level":
											echo"label-info";
											break;
											case "Normal Level":
											echo"label-warning";
											break;
											case "High Level":
											echo"label-danger";
											break;
										}
									echo"\">$severity</span></td>

						<td>$ownerName</td>
                        <td><div class=\"label label-danger\"> $status Ticket</div></td>
                        <td>$opened</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table></div></div>";
		}else{
			echo'<div class="alert alert-danger" style="padding:5px; margin:5px;">';
			if($this->countTicket()>0){ echo "All Tickets Closed"; }else{ echo "No Ticket Opened Yet"; }
			echo'</div>';
	   }
	}

	function getallTickets() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_tickets where dropped = '0' ORDER BY time_created desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			 $sn = 0;
			 $total_amt = 0;
			 echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\"
              >
                  <thead>
                    <tr>
                      <th>Ref</th>
					  <th>Owner</th>
                      <th>Subject</th>
                      <th>Severity</th>
                      <th>Status</th>
                      <th>Assigned</th>
                      <th>Date Opened / Resolved</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 while($ticket = $runQ->fetch()) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$tRef 			= $ticket->ticket_ref;
				$owner 			= $ticket->created_by;
				$subject 		= $ticket->ticket_subject;
				$opened 		= date("d M, Y: h:ia",$ticket->time_created);
				$closed	 		= $ticket->close_date;
				$status 		= $ticket->status;
				$severity 		= $ticket->severity;
				$assigned 		= $ticket->assigned;

				$empData = $this->getEmployeeInfo($assigned);
				$empName = $empData->firstname;

				$ownerData = $this->getEmployeeInfo($owner);
				$ownerName = $ownerData->firstname;

				echo"<tr>
                        <td>ATT$tRef-";
						switch($severity) {
							case "Low Level":
							echo"0";
							break;
							case "Normal Level":
							echo"1";
							break;
							case "High Level":
							echo"2";
							break;
						}
						echo"</td>
						<td>$ownerName</td>
                        <td><a href=\"ticket-details.php?tid=$id\" title=\"$subject\" style=\"text-decoration:none;\">";
							echo $this->limit_words($ticket->ticket_subject,5);
						echo"...</a></td>
                        <td><span class=\"label ";
									switch($severity) {
											case "Low Level":
											echo"label-info";
											break;
											case "Normal Level":
											echo"label-warning";
											break;
											case "High Level":
											echo"label-danger";
											break;
										}
									echo"\">$severity</span></td>
                        <td><div class=\"label ";
						if($status=="Closed") { echo"label-success"; }elseif($status=="Open"){ echo"label-danger"; }elseif($status=="In Progress"){ echo"label-warning"; }
						echo"\"> $status Ticket</div></td>
						<td>$empName</td>
                        <td>$opened / ";
						if($closed=="0"){ echo "na"; }else{ echo date("d M, Y: h:ia",$ticket->close_date); }
						echo"</td>
                        <td>
							<a href=\"ticket-details.php?tid=$id\" title=\"View Details\"><span class=\"add-on small-size\"> <i class=\"fa fa-folder-o\"></i></span></a>
						</td>
					  </tr>";
			 }
			 echo"</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';
	   }
	}

	function getStationTickets($station_id) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_tickets where station_id = '$station_id' and dropped = '0' ORDER BY time_created";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			 $sn = 0;
			 $total_amt = 0;
			 echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\"
              >
                  <thead>
                    <tr>
                      <th>Ref</th>
                      <th>Subject</th>
                      <th>Severity</th>
                      <th>Status</th>
                      <th>Assigned</th>
                      <th>Date Opened / Resolved</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 while($ticket = $runQ->fetch()) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$tRef 			= $ticket->ticket_ref;
				$subject 		= $ticket->ticket_subject;
				$opened 		= date("d M, Y: h:ia",$ticket->time_created);
				$closed	 		= $ticket->close_date;
				$status 		= $ticket->status;
				$severity 		= $ticket->severity;
				$assigned 		= $ticket->assigned;

				$empData = $this->getEmployeeInfo($assigned);
				$empName = $empData->firstname;

				echo"<tr>
                        <td>ATT$tRef-";
						switch($severity) {
							case "Low Level":
							echo"0";
							break;
							case "Normal Level":
							echo"1";
							break;
							case "High Level":
							echo"2";
							break;
						}
						echo"</td>
                        <td><a href=\"ticket-details.php?tid=$id\" title=\"$subject\" style=\"text-decoration:none;\">";
							echo $this->limit_words($ticket->ticket_subject,5);
						echo"...</a></td>
                        <td><span class=\"label ";
									switch($severity) {
											case "Low Level":
											echo"label-info";
											break;
											case "Normal Level":
											echo"label-warning";
											break;
											case "High Level":
											echo"label-danger";
											break;
										}
									echo"\">$severity</span></td>
                        <td><div class=\"label ";
						if($status=="Closed") { echo"label-success"; }else{ echo"label-danger"; }
						echo"\"> $status Ticket</div></td>
						<td>$empName</td>
                        <td>$opened / ";
						if($closed=="0"){ echo "na"; }else{ echo date("d M, Y: h:ia",$ticket->close_date); }
						echo"</td>
                        <td>
							<a href=\"ticket-details.php?tid=$id\" title=\"Comment on Ticket\"><span class=\"add-on small-size\"> <i class=\"fa fa-comment\"></i></span></a>
						</td>
					  </tr>";
			 }
			 echo"</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';
	   }
	}

	function getUserTickets($user_id) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_tickets where created_by = '$user_id' and dropped = '0' ORDER BY time_created";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			 $sn = 0;
			 $total_amt = 0;
			 echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\"
              >
                  <thead>
                    <tr>
                      <th>Ref</th>
                      <th>Subject</th>
                      <th>Severity</th>
                      <th>Status</th>
                      <th>Assigned</th>
                      <th>Date Opened / Resolved</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 while($ticket = $runQ->fetch()) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$tRef 			= $ticket->ticket_ref;
				$subject 		= $ticket->ticket_subject;
				$opened 		= date("d M, Y: h:ia",$ticket->time_created);
				$closed	 		= $ticket->close_date;
				$status 		= $ticket->status;
				$severity 		= $ticket->severity;
				$assigned 		= $ticket->assigned;

				$empData = $this->getEmployeeInfo($assigned);
				$empName = $empData->firstname;

				echo"<tr>
                        <td>ATT$tRef-";
						switch($severity) {
							case "Low Level":
							echo"0";
							break;
							case "Normal Level":
							echo"1";
							break;
							case "High Level":
							echo"2";
							break;
						}
						echo"</td>
                        <td><a href=\"ticket-details.php?tid=$id\" title=\"$subject\" style=\"text-decoration:none;\">";
							echo $this->limit_words($ticket->ticket_subject,5);
						echo"...</a></td>
                        <td><span class=\"label ";
									switch($severity) {
											case "Low Level":
											echo"label-info";
											break;
											case "Normal Level":
											echo"label-warning";
											break;
											case "High Level":
											echo"label-danger";
											break;
										}
									echo"\">$severity</span></td>
                        <td><div class=\"label ";
						if($status=="Closed") { echo"label-success"; }else{ echo"label-danger"; }
						echo"\"> $status Ticket</div></td>
						<td>$empName</td>
                        <td>$opened / ";
						if($closed=="0"){ echo "na"; }else{ echo date("d M, Y: h:ia",$ticket->close_date); }
						echo"</td>
                        <td>
							<a href=\"ticket-details.php?tid=$id\" title=\"Comment on Ticket\"><span class=\"add-on small-size\"> <i class=\"fa fa-comment\"></i></span></a>
						</td>
					  </tr>";
			 }
			 echo"</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';
	   }
	}

	function getTicketAssignmentHistory($ticket_id) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_ticket_assignment where ticket_id = '$ticket_id' ORDER BY date_assigned desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows > 0){

			 echo"<br />
			 <h4>Ticket Assignment History</h4>
            <hr />
            <div class=\"list-group\" style=\"font-size:10px\">
			<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>Assigned To</th>
                      <th>Assigned By</th>
                      <th>Date Assigned</th>
                    </tr>
                  </thead>
                  <tbody>";

			 while($assignment = $runQ->fetch()) {
				$assigned_to	= $assignment->assigned_to;
				$assigned_by	= $assignment->assigned_by;
				$dateAssigned	= date("d M, Y: h:ia",$assignment->date_assigned);

				//assigned by
				$empAssignbyData = $this->getEmployeeInfo($assigned_by);
				$empAssignbyName = $empAssignbyData->firstname;
				//assigned to
				$empAssignedData = $this->getEmployeeInfo($assigned_to);
				$empAssignedName = $empAssignedData->firstname;

				echo"<tr>
                        <td>$empAssignedName</td>
                        <td>$empAssignbyName</td>
                        <td>$dateAssigned</td>
					  </tr>";
			 }
			 echo"</tbody></table></div>";
		}
	}

	function addComment($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$ticket_id 	= $post['ticket_id'];
			$comment	= trim($post['comment']);

			$query = "insert into apl_ticket_comment values(default,'$ticket_id','$comment','".$_SESSION['userid']."','$time')";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {

				//get ticket details
				$ticketData = $this->getTicketInfo($ticket_id);
				$ticketRef = $ticketData->ticket_ref;
				$subject = $ticketData->ticket_subject;
				$message = $ticketData->ticket_desc;
				$dateCreated = date("d-m-Y h:ia",$ticketData->time_created);

				//get Owner details
				$ownerData = $this->getEmployeeInfo($ticketData->created_by);
				$ownerName = $ownerData->firstname;
				$ownerEmail = $ownerData->cooperate_email;

				//get Assigned details
				$empData = $this->getEmployeeInfo($ticketData->assigned);
				$firstname = $empData->firstname;
				$emailAddress = $empData->cooperate_email;

				$msg = "Hello,<br /><br />
						Comment from ".$_SESSION['username']." on ticket #$ticketRef<br /><br />
						*******************************************************************<br />
						comment: $comment<br />
						*******************************************************************<br /><br />
						Date: ".date("Y-m-d h:ia",$time)."<br /><br />

						Ticket Details<br />
						**************<br /><br />
						Ref: #$ticketRef<br />
						Subject: $subject<br />
						Description: $message<br />
						Created By: $ownerName<br />
						Date Created: $dateCreated<br />
						Assigned To: $firstname<br /><br />";

						$emailMessage = $this->emailTemplate($msg);

						$headers = "From: ".$_SESSION['email']." \r\n ";
						$headers .=	"Reply-To: ".Non_Reply." \r\n ";
						$headers .= "MIME-Version: 1.0\r\n";
						$headers .= "Content-type: text/html\r\n";

				$sendMail = mail($ownerEmail, "New Comment on Ticket #$ticketRef by ".$_SESSION['username'].".", $emailMessage, $headers);
				mail("itsupportdesk@flyairpeace.com","New Comment on Ticket #$ticketRef by ".$_SESSION['username'],$emailMessage, $headers);

				return '<div class="alert alert-success"><i class="fa fa-check"></i> Comment Saved Successfully</div>';
			}
		}
	}

	function getTicketComments($ticketID) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_ticket_comment where ticket_id = '$ticketID' ORDER BY time_created";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			 $sn = 0;
			 echo" <div class=\"table-responsive\">
          <table class=\"table table-striped\">
            <tbody>";
			 while($comment = $runQ->fetch()) {
				$sn += 1;
				$id 			= $comment->comment_id;
				$commentText	= $comment->comment;
				$date	 		= date("d M, Y: h:ia",$comment->time_created);
				$empData 		= $this->getEmployeeInfo($comment->commented_by);
				$empName 		= $empData->firstname;

				echo"<tr>
					<td style=\"width: 125px;\">$date</td>
					<td>
					  <p><strong>$empName</strong></p>

					  <p>$commentText</p>
					</td>
				  </tr>";
			 }
			// print the navigation link
			echo "</tbody>
			</table>
			</div>";
		}else{
			echo'<div class="alert alert-info">No Comment Yet</div>';
	   }
	}

	function changeTicketStatus($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {

			if($post['status_val']=="0"){
				$query = "update apl_tickets set status = 'Closed', close_date = '".time()."', closed_by = '".$_SESSION['userid']."' where ticket_id='".$post['tid']."'";
				$runQ = $this->RunQuery($query,$dbLink);
				if($runQ) {
					//get ticket details
					$ticketData = $this->getTicketInfo($post['tid']);
					$subject = $ticketData->ticket_subject;
					$message = $ticketData->ticket_desc;
					$dateCreated = date("d-m-Y h:ia",$ticketData->ticket_desc);

					$msg = "Hello,<br />
						Ticket with Ref, #$ticketRef hass been closed successfully<br />
						Date: ".date("Y-m-d h:ia",time())."<br />

						Ticket Details<br />
						**************<br />
						Ref: #$ticketRef<br />
						Subject: $subject<br />
						Description: <strong>$message</strong><br />
						Created By: $ownerName<br />
						Date Created: $dateCreated<br />
						Assigned To: $firstname<br />";

					$emailMessage = $this->emailTemplate($msg);

					$headers = "From: ".$_SESSION['email']." \r\n ";
					$headers .=	"Reply-To: ".Non_Reply." \r\n ";
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-type: text/html\r\n";


					mail($ownerEmail,"Ticket #$ticketRef Closed by ".$_SESSION['username'],$emailMessage, $headers);
					//mail("itsupportdesk@flyairpeace.com","New Comment on Ticket #$ticketRef by ".$_SESSION['username'],$msg);

					return '<div class="alert alert-success"><i class="fa fa-check"></i> Ticket Closed Successfully</div>';
				}
			}elseif($post['status_val']=="1"){
				$query = "update apl_tickets set status = 'Open', close_date = '0', closed_by = '0' where ticket_id='".$post['tid']."'";
				$runQ = $this->RunQuery($query,$dbLink);
				if($runQ) {
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Ticket Opened Successfully</div>';
				}
			}
		}
	}

	function addDevice($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$device		= filter_var(trim($post['device-name']), FILTER_SANITIZE_STRING);


			$query = "insert into apl_device_asset values(default,'$device','".$_SESSION['userid']."','$time')";
			$runQ = $this->RunQuery($query,$dbLink);
			if(runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Brand Added Successfully</div>';
			}
		}
	}

	function getDevice() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_device_asset ORDER BY device_name";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>sn</th>
                      <th>Device Name</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($device = $runQ->fetch()) {
				$sn += 1;
				$device_id 	= $device->device_id;
				$deviceName	= $device->device_name;

				echo"<tr>
						<td>$sn</td>
						<td>$deviceName</td>
                        <td>
							<a href=\"#?bid=$device_id\" title=\"Edit device\"><span class=\"add-on small-size\"> <i class=\"fa fa-edit\"></i></span></a>
							<a href=\"#?bid=$device_id\" title=\"Delete device\"><span class=\"add-on small-size\"> <i class=\"fa fa-trash-o\"></i></span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Device Yet</div>';
	   }
	}

	function addBrand($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$brand		= filter_var(trim($post['brand-name']), FILTER_SANITIZE_STRING);


			$query = "insert into apl_asset_brand values(default,'$brand','".$_SESSION['userid']."','$time')";
			$runQ = $this->RunQuery($query,$dbLink);
			if(runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Brand Added Successfully</div>';
			}
		}
	}

	function getBrand() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_asset_brand ORDER BY brand_name";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>sn</th>
                      <th>Brand Name</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($brand = $runQ->fetch()) {
				$sn += 1;
				$brand_id 	= $brand->brand_id;
				$brandName	= $brand->brand_name;

				echo"<tr>
						<td>$sn</td>
						<td>$brandName</td>
                        <td>
							<a href=\"#?bid=$brand_id\" title=\"Edit Brand\"><span class=\"add-on small-size\"> <i class=\"fa fa-edit\"></i></span></a>
							<a href=\"#?bid=$brand_id\" title=\"Delete Brand\"><span class=\"add-on small-size\"> <i class=\"fa fa-trash-o\"></i></span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Brand Yet</div>';
	   }
	}

	function addStation($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$station		= filter_var(trim($post['station-name']), FILTER_SANITIZE_STRING);


			$query = "insert into apl_station values(default,'$station','".$_SESSION['userid']."','$time')";
			$runQ = $this->RunQuery($query,$dbLink);
			if(runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Station Added Successfully</div>';
			}
		}
	}

	function getStations() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_station ORDER BY station_name";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>sn</th>
                      <th>Station Name</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($station = $runQ->fetch()) {
				$sn += 1;
				$station_id 	= $station->station_id;
				$stationName	= $station->station_name;

				echo"<tr>
						<td>$sn</td>
						<td>$stationName</td>
                        <td>
							<a href=\"#?sid=$station_id\" title=\"Edit Station\"><span class=\"add-on small-size\"> <i class=\"fa fa-edit\"></i></span></a>
							<a href=\"#?sid=$station_id\" title=\"Delete Station\"><span class=\"add-on small-size\"> <i class=\"fa fa-trash-o\"></i></span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Station Yet</div>';
	   }
	}

	function addLocation($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$location		= filter_var(trim($post['location-name']), FILTER_SANITIZE_STRING);


			$query = "insert into apl_asset_location values(default,'$location','".$_SESSION['userid']."','$time')";
			$runQ = $this->RunQuery($query,$dbLink);
			if(runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Location Added Successfully</div>';
			}
		}
	}

	function getLocations() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_asset_location ORDER BY location_name";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>sn</th>
                      <th>Location Name</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($location = $runQ->fetch()) {
				$sn += 1;
				$location_id 	= $location->location_id;
				$locationName	= $location->location_name;

				echo"<tr>
						<td>$sn</td>
						<td>$locationName</td>
                        <td>
							<a href=\"#?sid=$location_id\" title=\"Edit Station\"><span class=\"add-on small-size\"> <i class=\"fa fa-edit\"></i></span></a>
							<a href=\"#?sid=$location_id\" title=\"Delete Station\"><span class=\"add-on small-size\"> <i class=\"fa fa-trash-o\"></i></span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No location Yet</div>';
	   }
	}

	function addItem($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$itemName		= filter_var(trim($post['item-name']), FILTER_SANITIZE_STRING);
			$reorderLevel		= filter_var(trim($post['reorder-level']), FILTER_SANITIZE_STRING);
			$measure		= filter_var(trim($post['unit-measure']), FILTER_SANITIZE_STRING);


			$query = "insert into apl_it_store_item values(default,'$itemName','0','$reorderLevel','$measure','".$_SESSION['userid']."','$time','0')";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> '.$itemName.' Added Successfully</div>';
			}
		}
	}
	
	function updateItem($post, $process) {
		$dbLink = $this->connect_db();

		if(isset($process)) {

			$item_id    = trim($post['item_id']);
			$itemName   = filter_var(trim($post['item-name']), FILTER_SANITIZE_STRING);
			$reorderLevel   = filter_var(trim($post['reorder-level']), FILTER_SANITIZE_STRING);
			$measure   = filter_var(trim($post['unit-measure']), FILTER_SANITIZE_STRING);

			$time = time();

			$query = "update apl_it_store_item set item_name = '$itemName', reorder_level='$reorderLevel', unit_measure='$measure' WHERE item_id = '$item_id'";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				return '<div class="alert alert-warning"><i class="fa fa-check"></i> Item Updated</div>';
			}
		}
	}
	
	function deleteStoreItem($post, $delete) {
		$dbLink = $this->connect_db();
		if(isset($delete)) {
			$id = $post['item_id'];
			$runQ = $this->RunQuery("update apl_it_store_item set dropped = '1' WHERE item_id = '$id'",$dbLink);
			if($runQ) {
				return  '<div class="alert alert-danger">
							<i class="fa fa-check"></i>
							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
							Item trashed successfully
						</div>';
			}
		}
	}	

	function listRequestItem($itemID=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT item_id,item_name FROM apl_it_store_item where dropped='0'",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			 while($item = $runQ->fetch()) {
				$sn += 1;
				$item_id 	= $item->item_id;
				$item_name	= $item->item_name;

				echo"<option value='$item_id' ";
				if($itemID==$item_id){ echo"selected"; }
				echo">$item_name</option>\n";
			}
		}
	}

	function listRequestItemJS($itemID=null) {
		$dbLink = $this->connect_db();
		$runQ = $this->RunQuery("SELECT item_id,item_name FROM apl_it_store_item where dropped='0'",$dbLink);
		$num_rows = $runQ->rowCount();

		if($num_rows>0) {
			 while($item = $runQ->fetch()) {
				$sn += 1;
				$item_id 	= $item->item_id;
				$item_name	= $item->item_name;

				echo"\"<option value='$item_id' ";
				if($itemID==$item_id){ echo"selected"; }
				echo">$item_name</option>\"+\n";
			}
		}
	}

	function getItems() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_it_store_item where dropped = '0' ORDER BY item_name";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>SN</th>
                      <th>Item Name</th>
                      <th>Stock Quantity</th>
                      <th>Re-order Level</th>
                      <th>Unit Measure</th>
                      <th width=\"20%\">Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($item = $runQ->fetch()) {
				$sn += 1;
				$item_id 	= $item->item_id;
				$item_name	= $item->item_name;
				$stock_level 	= $item->stock_level ;
				$reorder	= $item->reorder_level;
				$measure	= $item->unit_measure;

				echo"<tr class=\"alert-success\">
						<td>$sn</td>
						<td>$item_name </td>
						<!-- <td id=\"stock_$sn\">$stock_level <a href=\"#\" id=\"\" onclick=\"EditQuantity('stock_$sn');\"><i class=\"fa fa-edit\"></i></span></a></a></td>-->
						<td id=\"stock_$sn\">$stock_level</td>
						<td>$reorder</td>
						<td>$measure</td>
                        <td>
							<a href=\"update-store-item.php?tid=$item_id\" class=\"btn btn-xs btn-default\" data-toggle=\"modal\" data-target=\"#updateModal\" title=\"Edit Item\"><span class=\"add-on small-size\">
							<i class=\"fa fa-edit\"></i> Edit</span></a>
							<a href=\"add-item-stock.php?tid=$item_id\" class=\"btn btn-xs btn-warning\" title=\"Add Item Stock\"><span class=\"add-on small-size\"> <i class=\"fa fa-trash-o\"></i> Stock</span></a>
							<a href=\"delete-store-item.php?tid=$item_id\" class=\"btn btn-xs btn-danger\" data-toggle=\"modal\" data-target=\"#updateModal\"  title=\"Trash Item\"><span class=\"add-on small-size\"><i class=\"fa fa-trash-o\"></i> Trash</span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Item Yet</div>';
	   }
	}

	function addItemStock($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$itemID			= filter_var(trim($post['item_id']), FILTER_SANITIZE_STRING);
			$receivedQty	= filter_var(trim($post['quantity']), FILTER_SANITIZE_STRING);
			$receivedFrom	= filter_var(trim($post['received-from']), FILTER_SANITIZE_STRING);
			$dateReceived	= $_POST['date_received'];
			$remark			= filter_var(trim($post['remark']), FILTER_SANITIZE_STRING);

            echo $dateReceived;
            
			$query = "insert into apl_it_stock_received values(default,'$itemID','$receivedQty','$dateReceived','$receivedFrom','".$_SESSION['userid']."','$remark','$time')";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				$updateQty = $this->updateItemQuantity($itemID,$receivedQty,"add");
				if($updateQty==1){
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Item Stock Added Successfully</div>';
				}
			}
		}
	}
	
	function updateItemQuantity($itemID,$quantity,$action){
		$dbLink = $this->connect_db();
		
		$query = "update apl_it_store_item set stock_level = stock_level ";
		if($action=="add") {
			$query .= "+";
		}elseif($action=="remove"){
			$query .= "-";
		}
		
		$query .=" '$quantity' WHERE item_id = '$itemID'";
		$runQ = $this->RunQuery($query,$dbLink);
		if($runQ) {
			return 1;
		}
	}
	
	function checkItemQuantity($itemID) {
		$dbLink = $this->connect_db();
		
		$query = "select item_id, stock_level from apl_it_store_item where item_id = '$itemID'";
		$runQ = $this->RunQuery($query,$dbLink);
		$stock = $runQ->fetch();
		return $stock->stock_level;
	}

	function getStoreItemStock() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_it_store_item where stock_level != '0' and dropped = '0' ORDER BY time_created desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0) {
		   
		   while($item = $runQ->fetch()) {
				
				$item_name 	= $item->item_name ;
				$stock_level	= $item->stock_level;
				$reorder_level 	= $item->reorder_level;
				$unit_measure 	= $item->unit_measure;
				
				echo"<div class=\"col-sm-6 col-md-3\">
				  <div class=\"row-stat\">
					<p class=\"row-stat-label\">$item_name Stock</p>
					<h3 class=\"row-stat-value\" style=\"font-size:18px\">$stock_level $unit_measure</h3>";
					if($stock_level>$reorder_level){
						echo"<span class=\"label label-success row-stat-badge\">Stock Ok</span>";
					}else{
						echo"<span class=\"label label-danger row-stat-badge\">Re-order Stock</span>";
					}					
				  echo"</div> <!-- /.row-stat -->
				</div> <!-- /.col -->";
			
		   }
			
		}
	}	

	function getItemStockHistory($itemID) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_it_stock_received where item_id = '$itemID' ORDER BY time_created desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0) {
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>SN</th>
                      <th>Received Quantity</th>
                      <th>Date Received</th>
                      <th>Received From</th>
                      <th>Received By</th>
                      <th>Remark</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($stock = $runQ->fetch()) {
				$sn += 1;
				$qty_received 	= $stock->qty_received ;
				$date_received	= $stock->date_received;
				$received_from 	= $stock->received_from ;
				$received_by	= $stock->received_by;
				$remarks 		= $stock->remarks ;
				
				$itemData = $this->getItemInfo($itemID);
				$itemMeasure = $itemData->unit_measure;
				
				$staffData = $this->getEmployeeInfo($received_by);
				$staffName = $staffData->firstname;

				echo"<tr class=\"alert-success\">
						<td>$sn</td>
						<td>$qty_received $itemMeasure</td>
						<td>$date_received</td>
						<td>$received_from</td>
						<td>$staffName</td>
                        <td>$remarks</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No stock received Yet</div>';
	   }
	}	

	function makeRequest($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();
			
			$itemCount	= count($post['item_id']);
			$item = $post['item_id'];
			$requestQty = $post['item_qty'];
			$scope = $this->mysql_prepare_value($post['request_scope']);
			$remark = $this->mysql_prepare_value($post['item_remark']);
		    $defaultTime = strtotime("3 October 2000");
		    $nullUser = 0;
			
			$addRequestQuery = "insert into  apl_requisition values(default,'".$_SESSION['userid']."','$scope',";
			
			if($scope!="Station") { $addRequestQuery .= "'NULL',"; }else { $addRequestQuery .= "'".$_SESSION['station_id']."',"; }
			$addRequestQuery .= "'Pending','$remark','$time','$defaultTime','$nullUser','$defaultTime','$nullUser','','N/A','$defaultTime','$nullUser')";
			$this->RunQuery($addRequestQuery,$dbLink);
			$requestID = $dbLink->lastInsertId();
			$i = 0;
			
			while($i<$itemCount) {	
				//if(!empty($item[$i]) && !empty($requestQty[$i])) {
					$query = "insert into apl_requisition_items values(default,'".$item[$i]."','$requestID','".$requestQty[$i]."','0')";
					$runQ = $this->RunQuery($query,$dbLink);
				//}
				$i++;
			}

			$stationData = $this->getStationInfo($_SESSION['station_id']);	
			$empData = $this->getEmployeeInfo($_SESSION['userid']);
			$x = 0;
			$sn = 0;
		
		    
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = off;                      // Enable verbose debug output SMTP::DEBUG_SERVER
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.office365.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'itsupportdesk@flyairpeace.com';                     // SMTP username
    $mail->Password   = 'Y3z!W3@r30v3r@llB3st';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('itsupportdesk@flyairpeace.com', 'ICT Team');
    $mail->addAddress('emeka.anumnu@flyairpeace.com', 'World Class IT');     // Add a recipient
    //$mail->addAddress('emmanuel.nwankwo@flyairpeace.com');               // Name is optional
    $mail->addReplyTo('itsupportdesk@flyairpeace.com', 'World Class IT Department');
    $mail->addCC('chukwuemekaanumnu@gmail.com');
    //$mail->addBCC('');

    // Attachments
  //  $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'New Requisition::..HQ Station';
    $mail->Body = $this->emailTempOne();
    $mail->Body   .= 'Dear IT Support<br /><br />';
	$mail->Body .= "Please, kindly supply us with the counter consumables as                stated below<br /><br />";
	$mail->Body .= "*************************<br />";
	$mail->Body .= $item_issue.'<br />';
	$mail->Body .= "*************************<br />";
	$mail->Body .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
					<thead>
						<tr>
						<th>SN</th>
						<th>Item Name</th>
						<th>Quantity Requested</th>
						</tr>
					</thead>
					<tbody>";
					
			while($x<$itemCount) {
				$sn += 1;	
				if(!empty($item[$x]) && !empty($requestQty[$x])) {

					$itemData = $this->getItemInfo($item[$x]);

					$mail->Body .="<tr>
							<td>$sn</td>
							<td>$itemData->item_name</td>
							<td>$requestQty[$x] $itemData->unit_measure</td>
						</tr>";
				}
				$x++;
			}
			
	$mail->Body .= "</tbody></table><br /><br />";
	$mail->Body .= "$remark<br /><br />";
	$mail->Body .= " <a href=\"http://support.flyairpeace.com/requisition.php\" class=\"btn btn-primary\">Go to Requisitions</a><br /><br />";
	$mail->Body .=  $empData->firstname . " " . $empData->lastname . "<br/>";
	$mail->Body .=  "Regards";

	$mail->Body .= $this->emailTempTwo();
    
   // $mail->AltBody = 'This is a test message. Thank you';

    $mail->send();
    //echo 'Message has been sent';
} catch (Exception $e) {
    //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
		
		    
		    
		    	
		
		
		
		// COntinue

			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Request Sent Successfully<br /></div>';
			}
		}
	}	

	function updateRequest($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();
			
			$itemCount	= count($post['id']);
			$requestID = $post['request_id'];
			$requestBy = $post['requested_by'];
			$status = $this->mysql_prepare_value($post['status']);
			$id = $post['id'];
			$approvedQty = $post['item_appv'];
			$itemID = $post['item_id'];
			$completed_comment = $this->mysql_prepare_value($post['item_comment']);

			if($status=="Processing") {
				$a = 0;
				while($a<$itemCount) {
					$checkItemQuantity = $this->checkItemQuantity($itemID[$a]);
					if($checkItemQuantity<$approvedQty[$a]) {

						//get item details
						$itemData = $this->getItemInfo($itemID[$a]);

						return '<div class="alert alert-danger">
									<i class="fa fa-check"></i>
									<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
									Operation Failed; ' . $itemData->item_name . ' stock quantity is less than approved quantity
								</div>';
					}
					$a++;
				}
			}

			//update requisition
			$query = "update apl_requisition set request_status = '$status',";
			if($status=="Processing") { 
				$query .= " date_accepted ='$time', accepted_by ='".$_SESSION['userid']."' "; 
			}elseif($status=="Completed") { 
				$query .= " dated_completed ='$time', completed_by='".$_SESSION['userid']."',completed_comment = '$completed_comment',acknowledgment = 'Awaiting' "; 
			}else { 
				$query .= "acknowledgment = 'N/A' "; 
			}
			$query .= "where requisition_id = '$requestID'";
			$runQ = $this->RunQuery($query,$dbLink);

			$i = 0;
			while($i<$itemCount) {	
				//update requisition items
				if($status=="Pending" || $status=="Processing") {
					$addQuery = "update apl_requisition_items set ";
					if($status=="Pending") {
						$addQuery .= "approved_qty = '0' ";
					}else{
						$addQuery .= "approved_qty = '".$approvedQty[$i]."' ";
					}
					$addQuery .= "where id = '".$id[$i]."'";
					$runQuery = $this->RunQuery($addQuery,$dbLink);
				}
				//balance item stock if the requistion status is completed
				if($status=="Completed") {
					$updateQty = $this->updateItemQuantity($itemID[$i],$approvedQty[$i],"remove");
				}
				$i++;
			}


				//get requester Station ID
				/*$requestData = $this->getRequestInfo($requestID);
				$stationData = $this->getStationInfo($requestData->station_id);

				//get requested Email
				$empData = $this->getEmployeeInfo($requestData->request_by);
				$empEmail = $empData->cooperate_email;
				$staff = $empData->firstname;*/
			

			if($status=="Processing") { 

				//get requester Station ID
				$requestData = $this->getRequestInfo($requestID);
				$stationData = $this->getStationInfo($requestData->station_id);
				$empID = $requestData->requested_by;

				//get requested Email
				$empData = $this->getEmployeeInfo($requestData->requested_by);
				$empEmail = $empData->cooperate_email;
				$staff = $empData->firstname;

				//get responder details
				$empData2 = $this->getEmployeeInfo($_SESSION['userid']);

				$x = 0;
				$sn = 0;
		
		    
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = off;                      // Enable verbose debug output SMTP::DEBUG_SERVER
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.office365.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'itsupportdesk@flyairpeace.com';                     // SMTP username
    $mail->Password   = 'Y3z!W3@r30v3r@llB3st';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('itsupportdesk@flyairpeace.com', 'ICT Team');
    $mail->addAddress($empEmail, $stationData->station_name.'  Station');     // Add a recipient
    //$mail->addAddress('emmanuel.nwankwo@flyairpeace.com');               // Name is optional
    $mail->addReplyTo('itsupportdesk@flyairpeace.com', 'World Class IT Department');
    $mail->addCC('itsupportdesk@flyairpeace.com');
    //$mail->addBCC('');

    // Attachments
  //  $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = "RE: Counter Consumables For:: ..." .$stationData->station_name." Station";
    $mail->Body = $this->emailTempOne();
    $mail->Body   .= 'Dear '. $staff . '<br /><br />';
	$mail->Body .= "Please, kindly note that your request has been seen and currently receiving attention.<br /><br />";
	$mail->Body .= "See below for quantity approved for your request.<br /><br />";
	$mail->Body .= "*************************<br />";
	$mail->Body .= $item_issue.'<br />';
	$mail->Body .= "*************************<br />";
	$mail->Body .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
						<thead>
							<tr>
							<th>SN</th>
							<th>Item Name</th>
							<th>Quantity Requested</th>
							<th>Quantity Approved</th>
							</tr>
						</thead>
						<tbody>";
				while($x<$itemCount) {
					$sn += 1;	
						$itemData = $this->getItemInfo($itemID[$x]);
						$requestData = $this->getRequestItemInfo($id[$x]);

						$mail->Body .="<tr>
								<td>$sn</td>
								<td>$itemData->item_name</td>
								<td>$requestData->requested_qty $itemData->unit_measure</td>
								<td>$approvedQty[$x] $itemData->unit_measure</td>
							</tr>";
					$x++;
				}
				$mail->Body .= "</tbody></table><br /><br />";

	$mail->Body .= "$remark<br /><br />";
	$mail->Body .= " <a href=\"http://support.flyairpeace.com/requisition.php\" class=\"btn btn-primary\">Go to Requisitions</a><br /><br />";
//	$mail->Body .= $empData2->firstname . " " . $empData2->lastname . "<br />";
	$mail->Body .= 'From: ' . $_SESSION['username'] . "<br />" . $_SESSION['email'] . "<br />";

	$mail->Body .=  "Best Regards";

	$mail->Body .= $this->emailTempTwo();
    
   // $mail->AltBody = 'This is a test message. Thank you';

    $mail->send();
    //echo 'Message has been sent';
} catch (Exception $e) {
    //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

				
			/*
				
		
				$msg = "Dear $staff<br /><br />";
				$msg .= "Please, kindly note that your request has been seen and currently receiving attention.<br /><br />";
				$msg .= "See below for quantity approved for your request.<br /><br />";
				$msg .= "*************************<br />";
				$msg .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
						<thead>
							<tr>
							<th>SN</th>
							<th>Item Name</th>
							<th>Quantity Requested</th>
							<th>Quantity Approved</th>
							</tr>
						</thead>
						<tbody>";
				while($x<$itemCount) {
					$sn += 1;	
						$itemData = $this->getItemInfo($itemID[$x]);
						$requestData = $this->getRequestItemInfo($id[$x]);

						$msg .="<tr>
								<td>$sn</td>
								<td>$itemData->item_name</td>
								<td>$requestData->requested_qty $itemData->unit_measure</td>
								<td>$approvedQty[$x] $itemData->unit_measure</td>
							</tr>";
					$x++;
				}
				$msg .= "</tbody></table><br /><br />";
				$msg .= " <a href=\"http://support.flyairpeace.com/requisition.php\" class=\"btn btn-primary\">Go to Requisitions</a><br /><br />";
				$msg .= $empData2->firstname . " " . $empData2->lastname . "<br />";
				$msg .= "Regards";

				$emailMessage = $this->emailTemplate($msg);

				$headers[] = 'MIME-Version: 1.0';
				$headers[] = 'Content-type: text/html; charset=iso-8859-1';
				$headers[] = 'From: ' . $_SESSION['username'] . ' ' . $_SESSION['email'];
				$headers[] = 'CC: itsupportdesk@flyairpeace.com';

				$sendMail = mail($empEmail, "RE: Counter Consumables::..".$stationData->station_name." Station", $emailMessage, implode("\r\n",$headers));
				
				*/
			}










			if($status=="Completed") { 

				//get requester Station ID
				$requestData = $this->getRequestInfo($requestID);
				$stationData = $this->getStationInfo($requestData->station_id);
				$empID = $requestData->requested_by;

				//get requested Email
				$empData = $this->getEmployeeInfo($requestData->requested_by);
				$empEmail = $empData->cooperate_email;
				$staff = $empData->firstname;

				//get responder details
				$empData2 = $this->getEmployeeInfo($_SESSION['userid']);
				
				//Setup and send email for completed process
				

				$x = 0;
				$sn = 0;
		
		    
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = off;                      // Enable verbose debug output SMTP::DEBUG_SERVER
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.office365.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'itsupportdesk@flyairpeace.com';                     // SMTP username
    $mail->Password   = 'Y3z!W3@r30v3r@llB3st';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('itsupportdesk@flyairpeace.com', 'ICT Team');
    $mail->addAddress($empEmail, $stationData->station_name.'  Station');     // Add a recipient
    //$mail->addAddress('emmanuel.nwankwo@flyairpeace.com');               // Name is optional
    $mail->addReplyTo('itsupportdesk@flyairpeace.com', 'World Class IT Department');
    $mail->addCC('itsupportdesk@flyairpeace.com');
    //$mail->addBCC('');

    // Attachments
  //  $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = "RE: Counter Consumables Approved For:: ..." .$stationData->station_name." Station";
    $mail->Body = $this->emailTempOne();
    $mail->Body   .= 'Dear '. $staff . '<br /><br />';
	$mail->Body .= "Please, kindly note that your request has been Completed as approved below.<br /><br />";
	$mail->Body .= "See below for quantity approved for your request.<br /><br />";
	$mail->Body .= "*************************<br />";
	$mail->Body .= $item_issue.'<br />';
	$mail->Body .= "*************************<br />";
	$mail->Body .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
						<thead>
							<tr>
							<th>SN</th>
							<th>Item Name</th>
							<th>Quantity Requested</th>
							<th>Quantity Approved</th>
							</tr>
						</thead>
						<tbody>";
				while($x<$itemCount) {
					$sn += 1;	
						$itemData = $this->getItemInfo($itemID[$x]);
						$requestData = $this->getRequestItemInfo($id[$x]);

						$mail->Body .="<tr>
								<td>$sn</td>
								<td>$itemData->item_name</td>
								<td>$requestData->requested_qty $itemData->unit_measure</td>
								<td>$approvedQty[$x] $itemData->unit_measure</td>
							</tr>";
					$x++;
				}
				$mail->Body .= "</tbody></table><br /><br />";
				$mail->Body .= "$completed_comment <br /><br />";

	$mail->Body .= " <a href=\"http://support.flyairpeace.com/requisition.php\" class=\"btn btn-primary\">Go to Requisitions</a><br /><br />";
//	$mail->Body .= $empData2->firstname . " " . $empData2->lastname . "<br />";
	$mail->Body .= 'From: ' . $_SESSION['username'] . "<br />" . $_SESSION['email'] . "<br />";

	$mail->Body .=  "Best Regards";

	$mail->Body .= $this->emailTempTwo();
    
   // $mail->AltBody = 'This is a test message. Thank you';

    $mail->send();
    //echo 'Message has been sent';
} catch (Exception $e) {
    //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

				
				
				
				
				
/*
				$x = 0;
				$msg = "Dear $staff<br /><br />";
				$msg .= "Please, kindly note that your request has been Completed as approved below.<br /><br />";
				$msg .= "See below for quantity approved for your request.<br /><br />";
				$msg .= "***************************************************<br />";
				$msg .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
						<thead>
							<tr>
							<th>SN</th>
							<th>Item Name</th>
							<th>Quantity Requested</th>
							<th>Quantity Approved</th>
							</tr>
						</thead>
						<tbody>";
				while($x<$itemCount) {
					$sn += 1;	
						$itemData = $this->getItemInfo($itemID[$x]);
						$requestData = $this->getRequestItemInfo($id[$x]);

						$msg .="<tr>
								<td>$sn</td>
								<td>$itemData->item_name</td>
								<td>$requestData->requested_qty $itemData->unit_measure</td>
								<td>$approvedQty[$x] $itemData->unit_measure</td>
							</tr>";
					$x++;
				}
				$msg .= "</tbody></table><br /><br />";
				$msg .= "$completed_comment <br /><br />";
				$msg .= "Kindly follow the link below to acknowledge receipt once you do.<br /><br />";
				$msg .= "<a href=\"http://support.flyairpeace.com/requisition.php\" class=\"btn btn-primary\">Go to Requisitions</a><br /><br />";
				$msg .= $empData2->firstname . " " . $empData2->lastname . "<br />";
				$msg .= "Regards";

				$emailMessage = $this->emailTemplate($msg);

				$headers[] = 'MIME-Version: 1.0';
				$headers[] = 'Content-type: text/html; charset=iso-8859-1';
				$headers[] = 'From: ' . $_SESSION['username'] . ' ' . $_SESSION['email'];
				$headers[] = 'CC: itsupportdesk@flyairpeace.com';
				

				$sendMail = mail($empEmail, "RE: Counter Consumables::..".$stationData->station_name." Station", $emailMessage, implode("\r\n",$headers));
*/				
				///**********************************************************///
				
				//check if any of the Items has reached reorder level
				
				
				
				

// Instantiation and passing `true` enables exceptions
$mail2 = new PHPMailer(true);

try {
    //Server settings
    $mail2->SMTPDebug = off;                      // Enable verbose debug output SMTP::DEBUG_SERVER
    $mail2->isSMTP();                                            // Send using SMTP
    $mail2->Host       = 'smtp.office365.com';                    // Set the SMTP server to send through
    $mail2->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail2->Username   = 'itsupportdesk@flyairpeace.com';                     // SMTP username
    $mail2->Password   = 'Y3z!W3@r30v3r@llB3st';                               // SMTP password
    $mail2->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail2->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail2->setFrom('itsupportdesk@flyairpeace.com', 'ICT Team');
    $mail2->addAddress('itsupportdesk@flyairpeace.com', '  Best Department of the Year');     // Add a recipient
    //$mail->addAddress('emmanuel.nwankwo@flyairpeace.com');               // Name is optional
    $mail2->addReplyTo('itsupportdesk@flyairpeace.com', 'World Class IT Department');
   // $mail->addCC('itsupportdesk@flyairpeace.com');
    //$mail->addBCC('');

    // Attachments
  //  $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail2->isHTML(true);                                  // Set email format to HTML
    $mail2->Subject = "RE: Counter Consumables Re-Order Level";
    $mail2->Body = $this->emailTempOne();
    
    $b = 0;


    $mail2->Body     .= "Dear IT Team<br /><br />";
	$mail2->Body     .= "Please, kindly note that there are some items that have reached re-order Level<br /><br />";
	$mail2->Body .= "See details below<br /><br />";
	$mail2->Body .= "*****************************************<br />";
	$mail2->Body .= $item_issue.'<br />';
	$mail2->Body .= "*************************<br />";
	$mail2->Body .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
						<thead>
							<tr>
							<th>SN</th>
							<th>Item Name</th>
							<th>Quantity in stock</th>
							<th>Re-order level quantity </th>
							</tr>
						</thead>
						<tbody>";
						$sn = 0;
				while($b<$itemCount) {
					$sn += 1;	
						$itemData = $this->getItemInfo($itemID[$b]);						
						$itemName = $itemData->item_name;
						$stockLevel = $itemData->stock_level;
						$reOrderLevel = $itemData->reorder_level;
						
						if($stockLevel<=$reOrderLevel) {

							$mail2->Body .="<tr>
								<td>$sn</td>
								<td>$itemName</td>
								<td>$stockLevel</td>
								<td>$reOrderLevel</td>
							</tr>";
						}
					$b++;
				}
				$mail2->Body .= "</tbody></table><br /><br />";
				$mail2->Body .= "Kindly follow the link below to view IT Store.<br /><br />";
				$mail2->Body .= "<a href=\"http://support.flyairpeace.com/it-store.php\" class=\"btn btn-primary\">Go to Item Store</a><br /><br />";
				$mail2->Body .= "IT Portal<br />";
				$mail2->Body .= "Regards";

	$mail2->Body .= $this->emailTempTwo();
    
   // $mail->AltBody = 'This is a test message. Thank you';

    $mail2->send();
    //echo 'Message has been sent';
} catch (Exception $e) {
    //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

				
				
				
				
				
				
				
				/*
				$b = 0;
				$msg2 = "Dear IT Team<br /><br />";
				$msg2 .= "Please, kindly note that there are some items that have reached re-order Level<br /><br />";
				$msg2 .= "See details below<br /><br />";
				$msg2 .= "***************************************************<br />";
				$msg2 .="<table class=\"table table-striped table-bordered table-hover\" border=\"1\">
						<thead>
							<tr>
							<th>SN</th>
							<th>Item Name</th>
							<th>Quantity in stock</th>
							<th>Re-order level quantity </th>
							</tr>
						</thead>
						<tbody>";
						$sn = 0;
				while($b<$itemCount) {
					$sn += 1;	
						$itemData = $this->getItemInfo($itemID[$b]);						
						$itemName = $itemData->item_name;
						$stockLevel = $itemData->stock_level;
						$reOrderLevel = $itemData->reorder_level;
						
						if($stockLevel<=$reOrderLevel) {

							$msg2 .="<tr>
								<td>$sn</td>
								<td>$itemName</td>
								<td>$stockLevel</td>
								<td>$reOrderLevel</td>
							</tr>";
						}
					$b++;
				}
				$msg2 .= "</tbody></table><br /><br />";
				$msg2 .= "Kindly follow the link below to view IT Store.<br /><br />";
				$msg2 .= "<a href=\"http://support.flyairpeace.com/it-store.php\" class=\"btn btn-primary\">Go to Item Store</a><br /><br />";
				$msg2 .= "IT Portal<br />";
				$msg2 .= "Regards";

				$emailMessage2 = $this->emailTemplate($msg2);

				$header[] = 'MIME-Version: 1.0';
				$header[] = 'Content-type: text/html; charset=iso-8859-1';
				$header[] = 'From: Itsupportdesk@flyairpeace.com';
				

				$sendMail2 = mail("itsupportdesk@flyairpeace.com", "Re-order ALERT", $emailMessage2, implode("\r\n",$header));
				
				*/
			}

			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Request updated successfully <br /></div>';
			}
		}
	}

	function stationUnAcknowledgedRequests($stationID) {
		$dbLink = $this->connect_db();
		//$sql = "SELECT * FROM apl_requisition where station_id = '$stationID' and acknowledgment = 'Awaiting' and acknowledgment != 'Acknowledged'";
		$sql = "SELECT * FROM apl_requisition where station_id = '$stationID' and (acknowledgment = 'N/A' OR acknowledgment = 'Awaiting') ";

		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0) {
			return 0;
	   }else{
		   return 1;
	   }
	}	

	function acknowledgeRequest($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();
			
			$requestID = $post['request_id'];

			//update requisition
			$query = "update apl_requisition set acknowledgment = 'Acknowledged', 
			date_acknowledged = '$time',
			acknowledged_by = '".$_SESSION['userid']."'
			where requisition_id = '$requestID'";
			$runQ = $this->RunQuery($query,$dbLink);
				
			if($runQ) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Request updated successfully<br /></div>';
			}
		}
	}
	

	function getStationRequest($stationID) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_requisition";
		if(in_array("request_user",$_SESSION['privileges'])) {
			$sql .= " where station_id = '$stationID'";
		}
		$sql .= " ORDER BY date_requested desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0) {
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>SN</th>
                      <th>Request Ref</th>
                      <th>Request Scope</th>
                      <th>Station</th>
                      <th>Request By</th>
                      <th>Request Status</th>
                      <th>Acknoledgment</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($request = $runQ->fetch()) {
				$sn += 1;
				$request_id 	= $request->requisition_id ;
				$request_scope	= $request->request_scope;
				$stationID	 	= $request->station_id ;
				$requested_by	= $request->requested_by;
				$request_status	= $request->request_status;
				$request_status	= $request->request_status;
				$acknowledgment	= $request->acknowledgment;
				
				$stationData = $this->getStationInfo($stationID);
				$stationName = $stationData->station_name;
				
				$staffData = $this->getEmployeeInfo($requested_by);
				$staffName = $staffData->firstname;

				echo"<tr>
						<td>$sn</td>
						<td>$request_id</td>
						<td>$request_scope</td>
						<td>$stationName</td>
						<td>$staffName</td>
						<td><label class=\"label ";
							if($request_status=="Pending") {
								echo "label-primary";
							}elseif($request_status=="Processing") {
								echo "label-warning";
							}elseif($request_status=="Completed") {
								echo "label-success";
							}
							echo"\">$request_status</label>
						</td>
                        <td><label class=\"label ";
						if($acknowledgment=="N/A"){
							echo"label-primary";
						}elseif($acknowledgment=="Awaiting"){
							echo"label-warning";
						}elseif($acknowledgment=="Acknowledged"){
							echo"label-success";
						}
						echo"\">$acknowledgment </label></td>
						<td>
							<div class=\"btn-group\">
								<button type=\"button\" class=\"btn btn-xs btn-primary dropdown-toggle\" data-toggle=\"dropdown\">
								Action <span class=\"caret\"></span>
								</button>
								<ul class=\"dropdown-menu\" role=\"menu\">
									<li><a href=\"requested-item.php?rid=$request_id\" data-toggle=\"modal\" data-target=\"#item_Modal\" title=\"Edit Item\">View Item</a></li>";
									if(in_array("request_admin",$_SESSION['privileges'])) {
										echo"<li><a href=\"javascript:;\">Print manifest</a></li>";
									}
									if(in_array("request_user",$_SESSION['privileges']) && $acknowledgment=="Awaiting") {
										echo"<li><a href=\"acknowledge.php?rid=$request_id\" data-toggle=\"modal\" data-target=\"#ackModal\" >Acknowledge Receipt</a></li>";
									}
								echo"</ul>
							</div>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No request Yet</div>';
	   }
	}	

	function getRequestInfo($requestID) {
		$dbLink = $this->connect_db();
		$sql = "SELECT * FROM apl_requisition where requisition_id = '$requestID'";
		$runQ = $this->RunQuery($sql,$dbLink);
		return $runQ->fetch();
	}

	function getRequestItemList($requestID) {
		$dbLink = $this->connect_db();
		$sql = "SELECT * FROM apl_requisition_items where requisition_id = '$requestID'";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0) {
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>SN</th>
                      <th>Item Name</th>
                      <th>Quantity Requested</th>
                      <th>Quantity Approved</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($item = $runQ->fetch()) {
				$sn += 1;
				$id = $item->id ;
				$itemID = $item->item_id ;
				$requisitionID = $item->requisition_id ;
				$requestedQty = $item->requested_qty;
				$approvedQty = $item->approved_qty;
				
				$itemData = $this->getItemInfo($itemID);
				$itemName = $itemData->item_name;
				$itemMeasure = $itemData->unit_measure;

				$requisitionData = $this->getRequestInfo($requisitionID);
				

				echo"<tr>
						<td>$sn</td>
						<td>$itemName</td>
						<td>$requestedQty $itemMeasure</td>
						<td>";
						if(in_array("request_admin",$_SESSION['privileges'])) {
							if($requisitionData->request_status!="Completed"){
							echo"<input type=\"number\" id=\"item_appv\" name=\"item_appv[]\" min=\"0\" value=\"$approvedQty\" class=\"form-control\">
							<input type=\"hidden\" name=\"id[]\" value=\"$id\">
							<input type=\"hidden\" name=\"item_id[]\" value=\"$itemID\">";
							}else{
								echo "$approvedQty $itemMeasure";
							}
						 }else{
							echo "$approvedQty $itemMeasure";
						 }
						echo"</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Items Yet</div>';
	   }
	}

	function getRequestItemInfo($id) {
		$dbLink = $this->connect_db();
		$sql = "SELECT * FROM apl_requisition_items where id = '$id'";
		$runQ = $this->RunQuery($sql,$dbLink);
		$data = $runQ->fetch();
		return $data;
	}

	function getAllRequest() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_requisition ORDER BY date_requested desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0) {
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>SN</th>
                      <th>Request Ref</th>
                      <th>Request Scope</th>
                      <th>Station</th>
                      <th>Request By</th>
                      <th>Request Status</th>
                      <th>Acknoledgment</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($request = $runQ->fetch()) {
				$sn += 1;
				$request_id 	= $request->requisition_id ;
				$request_scope	= $request->request_scope;
				$stationID	 	= $request->station_id ;
				$requested_by	= $request->requested_by;
				$request_status	= $request->request_status;
				$request_status	= $request->request_status;
				$acknowledgment	= $request->acknowledgment;
				
				$stationData = $this->getStationInfo($stationID);
				$stationName = $stationData->station_name;
				
				$staffData = $this->getEmployeeInfo($requested_by);
				$staffName = $staffData->firstname;

				echo"<tr>
						<td>$sn</td>
						<td>$request_id</td>
						<td>$request_scope</td>
						<td>$stationName</td>
						<td>$staffName</td>
                        <td>$request_status</td>
                        <td>$acknowledgment </td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No request Yet</div>';
	   }
	}	

	function getCaseLogComment($logID) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_case_log_comment where log_id = '$logID' ORDER BY time_created desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){

			 $sn = 0;
			 while($comment = $runQ->fetch()) {
				$sn += 1;
				$commentText 	= $comment->comment_text;
				$agentID		= $comment->agent_id;
				$timecreated	= date("d-m-Y h:ia", $comment->time_created);

				$agentData = $this->getEmployeeInfo($agentID);
				$agentName = $agentData->firstname;
				$gender		= $agentData->gender;

				echo"<li>
					  <img src=\"./img/avatars/";
					  if($gender=="Male"){ echo"male_avatar.png"; }elseif($gender=="Female"){ echo"female_avatar.png"; }
					  echo"\" alt=\"Avatar\" class=\"panel-list-avatar\">
					  <div class=\"panel-list-content\">
						  <a href=\"javascript:;\" class=\"panel-list-title\">$commentText.</a>
						  <span class=\"panel-list-meta\">comment by <a href=\"javascript:;\">$agentName</a> | time <a href=\"javascript:;\">$timecreated</a></span>
					  </div>
					</li>";
			 }
		}else{
			echo'<div class="alert alert-info">No comment Yet</div>';
	   }
	}

	function getCaseForwardHistory($logID) {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_case_assignment where case_id = '$logID' ORDER BY date_assigned desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){

			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>Department</th>
                      <th>Assigned By</th>
                      <th>Date Assigned</th>
                    </tr>
                  </thead>
                  <tbody>";

			 $sn = 0;
			 while($assignment = $runQ->fetch()) {
				$sn += 1;
				$assignedBy 	= $assignment->assigned_by;
				$dept_id		= $assignment->department;
				$dateAssigned	= date("l jS \of F Y h:i:s A", $assignment->date_assigned);

				$agentData = $this->getEmployeeInfo($assignedBy);
				$assignBy = $agentData->firstname;

				$deptData = $this->getDepartmentInfo($dept_id);
				$deptName = $deptData->dept_name;

				echo"<tr>
                      <th>$deptName</th>
                      <th>$assignBy</th>
                      <th>$dateAssigned</th>
                    </tr>";
			 }
			 echo"</tbody></table>";
		}else{
			echo'<div class="alert alert-info">History Empty</div>';
	   }
	}

	function addEmployee($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$fname		= filter_var(trim(ucfirst(strtolower($post['first-name']))), FILTER_SANITIZE_STRING);
			$lname		= filter_var(trim(ucfirst(strtolower($post['last-name']))), FILTER_SANITIZE_STRING);
			$gender		= filter_var(trim($post['gender']), FILTER_SANITIZE_STRING);
			$email		= filter_var(trim($post['user-email']), FILTER_SANITIZE_STRING);
			$station	= $post['user-station'];
			$dept		= $post['user-dept'];
			$phone		= filter_var(trim($post['user-phone']), FILTER_SANITIZE_STRING);
			$passw		= md5(filter_var(trim($post['user-pass']), FILTER_SANITIZE_STRING));
			$role		= $post['role'];
			$sendMeCopy		= $post['send_me_copy'];

			$checkEmpEmail = $this->checkEmpEmail($email,"add");

			if($checkEmpEmail==1){
				return '<div class="alert alert-danger"><i class="fa fa-times"></i> Operation failed! Email Already exist for another user</div>';
			}

			$query = "insert into apl_employees values(default,'$station','$fname','$lname','$gender','$phone','$dept','$email','$passw','Active','".$_SESSION['userid']."','$role','0','$time','0','0','No','0')";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {

				if($post['send_details']=="Yes") {
					//send email to new user
					$msg = "Hello $fname,<br />
							<br />
							<p>A new account has been created for you on support.flyairpeace.com<br />
							<br />
							Details<br />
							**************<br />
							username: $email<br />
							password: ".$post['user-pass']."<br />
							URL: <a href=\"http://support.flyairpeace.com/account-login.php?em=$email\">Air Peace Support Portal</a>
							<br />
							<br />

							regards<br />
							IT Team Airpeace.</p>";

					$emailMessage = $this->emailTemplate($msg);

					$headers = "From: ".$_SESSION['email']." \r\n ";
					$headers .=	"Reply-To: ".Non_Reply." \r\n ";
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-type: text/html\r\n";

					$sendMail = mail($email, "Airpeace Support; your login details", $emailMessage, $headers);
					if($sendMeCopy=="send_me_copy") {
						$sendMail = mail($_SESSION['email'], "Airpeace Support; your login details", $emailMessage, $headers);
					}
				}

				return '<div class="alert alert-success"><i class="fa fa-check"></i> User Created Successfully</div>';
			}
		}
	}

	function updateEmployee($post,$process) {
		$dbLink = $this->connect_db();
		if(isset($process)) {
			$time = time();

			$staffID	= $post['staff_id'];
			$fname		= filter_var(trim(ucfirst(strtolower($post['first-name']))), FILTER_SANITIZE_STRING);
			$lname		= filter_var(trim(ucfirst(strtolower($post['last-name']))), FILTER_SANITIZE_STRING);
			$gender		= filter_var(trim($post['gender']), FILTER_SANITIZE_STRING);
			$email		= filter_var(trim($post['user-email']), FILTER_SANITIZE_STRING);
			$station	= $post['user-station'];
			$dept		= $post['user-dept'];
			$change_password		= $post['change_password'];
			$phone		= filter_var(trim($post['user-phone']), FILTER_SANITIZE_STRING);
			$passw		= md5(filter_var(trim($post['user-pass']), FILTER_SANITIZE_STRING));
			$role		= $post['role'];

			$checkEmpEmail = $this->checkEmpEmail($email,"update",$staffID);

			if($checkEmpEmail==0){
				return '<div class="alert alert-danger"><i class="fa fa-times"></i> Operation failed! Email Already exist for another user</div>';
			}

			$query = "update apl_employees set
			station_id = '$station',
			firstname = '$fname',
			lastname = '$lname',
			gender = '$gender',
			phone = '$phone',
			department_id  = '$dept',
			cooperate_email = '$email',";
			if($passw!=""){ $query .= "password = '$passw',"; }
			$query .= "access_role = '$role',
			changed_password = '$change_password'
			where id = '$staffID'";
			$runQ = $this->RunQuery($query,$dbLink);
			if($runQ) {
				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> User Created Successfully</div>';
			
			}
		}
	}

	function getUsers() {
		$dbLink = $this->connect_db();

		$sql = "SELECT * FROM apl_employees where dropped = '0' ORDER BY time_created desc";
		$runQ = $this->RunQuery($sql,$dbLink);
		$num_rows = $runQ->rowCount();

	   if($num_rows > 0){
			echo"<table
                class=\"table table-striped table-bordered table-hover\"
                data-provide=\"datatable\"
                data-display-rows=\"10\"
                data-paginate=\"true\"
                data-info=\"true\"
                data-search=\"true\"
                data-length-change=\"true\">
                  <thead>
                    <tr>
                      <th>sn</th>
                      <th>firstname</th>
                      <th>Station</th>
                      <th>Email Address</th>
                      <th>Phone</th>
                      <th>Department</th>
                      <th>Role</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>";
			 $sn = 0;
			 while($emp = $runQ->fetch()) {
				$sn += 1;
				$emp_id 		= $emp->id;
				$station_id 	= $emp->station_id;
				$department_id 	= $emp->department_id;
				$fname			= $emp->firstname;
				$email			= $emp->cooperate_email;
				$phone			= $emp->phone;
				$roleid			= $emp->access_role;
				$createdon		= date("d-m-Y",$emp->time_created);
				$lastloggin		= $emp->last_loggedin;

				$departmentData = $this->getDepartmentInfo($department_id);
				$deptName = $departmentData->dept_name;

				$stationData = $this->getStationInfo($station_id);
				$stationName = $stationData->station_name;

				$roleData = $this->getRoleInfo($roleid);
				$roleName = $roleData->role_name;

				echo"<tr>
						<td>$sn</td>
						<td>$fname</td>
						<td>$stationName</td>
						<td>$email</td>
						<td>$phone</td>
						<td>$deptName</td>
						<td>$roleName</td>
                        <td>
							<a href=\"edit-user.php?sid=$emp_id\" data-toggle=\"modal\" data-target=\"#editUserModal\" title=\"Edit user\"><span class=\"add-on small-size\"> <i class=\"fa fa-edit\"></i></span></a>
							<a href=\"delete-user.php?sid=$emp_id\" data-toggle=\"modal\" data-target=\"#editUserModal\" title=\"Delete user\"><span class=\"add-on small-size\"> <i class=\"fa fa-trash-o\"></i></span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No User Created Yet</div>';
	   }
	}

	function TopNavigation() {
		$dbLink = $this->connect_db();

		foreach($_SESSION['userAccessModules'] as $moduleID) {
			//get all modules
			$runQ = $this->RunQuery("SELECT * FROM apl_app_module where module_id = '$moduleID' and parent_id = '0' and status='Active' ORDER BY position asc",$dbLink);
			while($moduleData = $runQ->fetch()) {
				$moduleID 	= $moduleData->module_id;
				$moduleName = $moduleData->module_name;
				$moduleLink = $moduleData->module_link;

				echo"<li class=\"";
				if($moduleLink=="#") { echo "dropdown"; }
				echo"\">\n
				<a href=\"$moduleLink\" ";
				if($moduleLink=="#") { echo"class=\"dropdown-toggle\" data-toggle=\"dropdown\" data-hover=\"dropdown\""; }
				echo">
					$moduleName";
				if($moduleLink=="#") { echo"<span class=\"caret\"></span>"; }
				echo"</a>\n";
				if($moduleLink=="#") {
					$this->subNavigation($moduleID);
				}
				echo"</li>\n";
			}
		}		
		
	}

	function emailTemplate($message) {

		return "<link rel=\"stylesheet\" href=\"http://support.flyairpeace.com/css/bootstrap.min.css\">
		<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"font-family:verdana\">
				  <tr>
					<td align=\"center\" valign=\"top\" bgcolor=\"#f7f7f7\" style=\"background-color:#f7f7f7;\"><br>
					<br>
					<table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
					  <tr>
						<td align=\"center\" valign=\"top\"><table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinktop.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						  <tr>
							<td align=\"left\" valign=\"top\" bgcolor=\"#a01b16\" style=\"background-color:#ffffff; padding:10px;\"><img src=\"http://support.flyairpeace.com/img/logo.png\"></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinkbot.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						</table></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/blank.png\" width=\"18\" height=\"18\" style=\"display:block;\"></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/whitebox_top.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\" bgcolor=\"#a01b16\" style=\"background-color:#ffffff; padding-left:14px; padding-right:14px;\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
							  <tr>
								<td align=\"left\" valign=\"top\" style=\"padding-right:10px;\">
								  $message
								  </td>
							  </tr>
							</table></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/whitebox_bot.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						</table></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/blank.png\" width=\"18\" height=\"18\" style=\"display:block;\"></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinktop.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						  <tr>
							<td align=\"left\" valign=\"top\" bgcolor=\"#a01b16\" style=\"background-color:#a01b16; padding-left:10px; padding-right:10px;\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
							  <tr>
								<td align=\"left\" valign=\"top\" style=\"font-family:Arial, Helvetica, sans-serif; font-size:11px; color:#ffffff; padding-left:10px;\">
								  <b>Hours:</b> Mon-Fri 8:30-5:00 <br>
								  <b>Inter Com:</b> 227 or 108 <br>
								  <b>IT Support: </b>itsupportdesk@flyairpeace.com<br>
								  <br>
								  <b>Phone Numbers: </b> 09087237537,08176689740 09087218315,09087261669<br></td>
							  </tr>
							</table></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinkbot.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						</table></td>
					  </tr>
					</table>
					<br>
					<br></td>
				  </tr>
				</table>
				<script src=\"http://support.flyairpeace.com/js/libs/jquery-1.10.1.min.js\"></script>
			   <script src=\"http://support.flyairpeace.com/js/libs/jquery-ui-1.9.2.custom.min.js\"></script>
			   <script src=\"http://support.flyairpeace.com/js/libs/bootstrap.min.js\"></script>";
	}



//Begin EMail temp








function emailTempOne() {

		return "<link rel=\"stylesheet\" href=\"http://support.flyairpeace.com/css/bootstrap.min.css\">
		<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"font-family:verdana\">
				  <tr>
					<td align=\"center\" valign=\"top\" bgcolor=\"#f7f7f7\" style=\"background-color:#f7f7f7;\"><br>
					<br>
					<table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
					  <tr>
						<td align=\"center\" valign=\"top\"><table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinktop.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						  <tr>
							<td align=\"left\" valign=\"top\" bgcolor=\"#a01b16\" style=\"background-color:#ffffff; padding:10px;\"><img src=\"http://support.flyairpeace.com/img/logo.png\"></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinkbot.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						</table></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/blank.png\" width=\"18\" height=\"18\" style=\"display:block;\"></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/whitebox_top.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\" bgcolor=\"#a01b16\" style=\"background-color:#ffffff; padding-left:14px; padding-right:14px;\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
							  <tr>
								<td align=\"left\" valign=\"top\" style=\"padding-right:10px;\">";
								
								}
								
								
				function emailTempTwo() {
						return 
								  "</td>
							  </tr>
							</table></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/whitebox_bot.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						</table></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/blank.png\" width=\"18\" height=\"18\" style=\"display:block;\"></td>
					  </tr>
					  <tr>
						<td align=\"center\" valign=\"top\"><table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinktop.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						  <tr>
							<td align=\"left\" valign=\"top\" bgcolor=\"#a01b16\" style=\"background-color:#a01b16; padding-left:10px; padding-right:10px;\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
							  <tr>
								<td align=\"left\" valign=\"top\" style=\"font-family:Arial, Helvetica, sans-serif; font-size:11px; color:#ffffff; padding-left:10px;\">
								  <b>Hours:</b> Mon-Fri 8:30-5:00 <br>
								  <b>Inter Com:</b> 227 or 108 <br>
								  <b>IT Support: </b>itsupportdesk@flyairpeace.com<br>
								  <br>
								  <b>Phone Numbers: </b> 09087237537,08176689740 09087218315,09087261669<br></td>
							  </tr>
							</table></td>
						  </tr>
						  <tr>
							<td align=\"center\" valign=\"top\"><img src=\"http://support.flyairpeace.com/img/pinkbot.png\" width=\"600\" height=\"11\" style=\"display:block;\"></td>
						  </tr>
						</table></td>
					  </tr>
					</table>
					<br>
					<br></td>
				  </tr>
				</table>
				<script src=\"http://support.flyairpeace.com/js/libs/jquery-1.10.1.min.js\"></script>
			   <script src=\"http://support.flyairpeace.com/js/libs/jquery-ui-1.9.2.custom.min.js\"></script>
			   <script src=\"http://support.flyairpeace.com/js/libs/bootstrap.min.js\"></script>";
	}




// End of EMail temp



	function subNavigation($parentID) {
		$dbLink = $this->connect_db();
		echo"<ul class=\"dropdown-menu\">";
		foreach($_SESSION['userAccessModules'] as $moduleID) {
			//get all modules
			$runQ = $this->RunQuery("SELECT * FROM apl_app_module where module_id = '$moduleID' and parent_id = '$parentID' and status='Active' ORDER BY position asc",$dbLink);
			while($moduleData = $runQ->fetch()) {
				$moduleName = $moduleData->module_name;
				$moduleLink = $moduleData->module_link;

				echo"<li class=\"\">\n
				  <a href=\"$moduleLink\">
				   $moduleName
				  </a>\n
				</li>\n";
			}

		}
		echo"</ul>\n";
	}
	
	function navigation($active_nav) {
		echo"  
 <div class=\"navbar navbar-default navbar-fixed-top navbar-inverse\">
      <div class=\"container\">
        <div class=\"navbar-header\">
        <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\"#example\">
          <span class=\"icon-bar\"></span>
          <span class=\"icon-bar\"></span>  
          <span class=\"icon-bar\"></span>
        </button>
          <a href=\"\" class=\"navbar-brand\">Asset Listing</a>
        </div>
        <div class=\"collapse navbar-collapse\" id=\"example\">
          <ul class=\"nav navbar-nav\">
            <li ";
		  if($active_nav=="homepage") { echo"class=\"active\""; }
		  echo"><a href=\"homepage.php\"><span  class=\"glyphicon glyphicon-home\"></span> Home</a></li>
            <li ";
		  if($active_nav=="display") { echo"class=\"active\""; }
		  echo"><a href=\"display.php\"><span class=\"glyphicon glyphicon-list-alt\"></span> View List</a></li>
            <li ";
		  if($active_nav=="update_page") { echo"class=\"active\""; }
		  echo"><a href=\"update_page.php\"><span class=\"glyphicon glyphicon-pencil\"></span> Update List</a></li>
            <li ";
		  if($active_nav=="advance_search") { echo"class=\"active\""; }
		  echo"><a href=\"advance_search.php\"><span class=\"glyphicon glyphicon-search\"></span> Advance Search</a></li>
            <li>
            <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">
            <span class=\"glyphicon glyphicon-user\"></span> Super Admin
            <span class=\"caret\"></span>
            </a>
            <ul class=\"dropdown-menu\">
              <li ";
		  
		  if($active_nav=="add_item") { echo"class=\"active\""; }
		  echo"><a href=\"add_item.php\"><span class=\"glyphicon glyphicon-shopping-cart\"></span> Add item</a></li>              
            </ul>
            </li>
          </ul>
           <form action=\"search.php\" method=\"POST\" class=\"navbar-form navbar-left\" role=\"search\">
            <div class=\"form-group \">
              <input type=\"text\" name=\"search\" class=\"form-control\" placeholder=\"Search Here\">
            </div>
            <button name=\"submit\" type=\"submit\" class=\"btn btn-primary \"><span class=\"glyphicon glyphicon-search\"></span></button>
  
          </form>
		  <ul class=\"nav navbar-nav  navbar-left \" >
		   <li>
		   <form action=\"homepage.php\" method=\"POST\" class=\"navbar-form\">
            <a href=\"\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">
            <span class=\"glyphicon glyphicon-user\">
			 </span>";
			  
			echo"<span class=\"caret\"></span>
            </a>
			</form>
		  </ul>";

        if(isset($_POST['logout']))	 
		{
			session_destroy();
			header('location:index.php');
		}
	 
	 echo"
        </div>
      </div>
    </div>";
	}


	function loadImage($imagePath) {

	  $photo = "";

	  $path = $imagePath;
	  $fp = @fopen($path, 'r'); // open a file handle of the temporary file

	  $photo  = @fread($fp, filesize($path)); // read the temp file

	  $photo = mysql_real_escape_string($photo);

	  @fclose($fp); // close the file handle


	  return $photo;
	}



}

?>
