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

if(isset($_GET['log_out'])) {
	$Login_Process = new Login_Process;
	$Login_Process->log_out($_SESSION['username'], $_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);
			echo "Connected successfully";
		}
		catch(PDOException $e){
			echo "Connection failed: " . $e->getMessage();
		}
	}

	function query($sql) {

		$this->connect_db();
		$sql = mysql_query($sql);
		$num_rows = mysql_num_rows($sql);
		$result = mysql_fetch_assoc($sql);
			
		return array("num_rows"=>$num_rows,"result"=>$result,"sql"=>$sql);
	
	}
	
	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 $value;
	}
	
	function limit_words($string, $word_limit) {
		$words = explode(" ",$string);
		return implode(" ",array_splice($words,0,$word_limit));
	}

	function welcome_note() {
			
		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', 'false', 'cookie'); 
		}
		if(isset($_SESSION['username'])) { 
			return "<a href=\"".Script_URL.Script_Path."\">Welcome ".$_SESSION['first_name']."</a>";
		} else {
			return "<a href=\"".Script_URL.Script_Path."index.php\">Welcome Guest, Please Login</a>";
		}	
	}
	
	function generate_po_ref() {
		$query = "SELECT po_ref FROM purchase_order order by time_created desc LIMIT 1";
		$result = mysql_query($query)or die(mysql_error());
		$counRow = mysql_num_rows($result);
		if($counRow>0) {
			$order = mysql_fetch_object($result)or die(mysql_error());
			$orderRef = $order->po_ref;
			$newRef = $orderRef + 1;
			return $newRef;
		}else{
			return 1;
		}
	}
	
	function genTicketRef() {
		$query = "SELECT ticket_ref FROM tickets order by time_created desc LIMIT 1";
		$result = mysql_query($query)or die(mysql_error());
		$counRow = mysql_num_rows($result);
		if($counRow>0) {
			$ref = mysql_fetch_object($result)or die(mysql_error());
			$tRef = $ref->ticket_ref;
			$newRef = $tRef + 1;
			return $newRef;
		}else{
			return 1;
		}
	}
	
	function genTransferRef() {
		$query = "SELECT trans_ref FROM transfer_request order by time_created desc LIMIT 1";
		$result = mysql_query($query)or die(mysql_error());
		$counRow = mysql_num_rows($result);
		if($counRow>0) {
			$ref = mysql_fetch_object($result)or die(mysql_error());
			$tRef = $ref->trans_ref;
			$newRef = $tRef + 1;
			return $newRef;
		}else{
			return 1;
		}
	}
	
	function generate_asset_serial() {
		$query = "SELECT asset_serial FROM assets order by time_created desc LIMIT 1";
		$result = mysql_query($query)or die(mysql_error());
		$counRow = mysql_num_rows($result);
		if($counRow>0) {
			$serial = mysql_fetch_object($result)or die(mysql_error());
			$assetSerial = $serial->asset_serial;
			$newSerial = $assetSerial + 1;
			return $newSerial;
		}else{
			return 1;
		}
	}
	
	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: http://".$_SERVER['HTTP_HOST'].$page); 
		} else {
		    return true;
		}
	}

	function check_status($page) {

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

		if(!isset($_SESSION['username'])){
			header("Location: http://".$_SERVER['HTTP_HOST'].Script_Path."login.php");
		}
	}

	function log_in($username, $password, $page, $submit) {
		
		if(isset($submit)) {

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

			$query = $this->query("SELECT * FROM app_users WHERE username = '$username' AND password='$password'");

			if($query['num_rows'] == 1) {
				
				if ($query['result']['status'] == "suspended") {
					return '<div class="alert alert-danger alert-dismissible" role="alert">
							  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
							 Account Suspended, <br /> Contact Supervisor.
							 </div>';
				}
				
				if ($query['result']['status'] == "pending") {
					return '<div class="alert alert-danger alert-dismissible" role="alert">
							  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
							 Account Pending, <br /> Contact Supervisor</div>';
				}

				$this->set_session($username, $password);	
								
			} else {
					return '<div class="alert alert-danger alert-dismissible" role="alert">
							  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
							  Username or Password is Invalid.
							</div>';
			}	

				$this->query("UPDATE app_users SET last_loggedin = '".time()."' WHERE username = '$username'");
			if(!$page) { $page = Script_Path."index.php"; }
				
			if ($page == 'false') {
					return true;
			} else {
					header("Location: http://".$_SERVER['HTTP_HOST'].$page); 
			}
		
		}
	}
	
	function set_session($username, $password) {
			
			$query = $this->query("SELECT * FROM app_users WHERE username='$username' AND password='$password'");
	
			ini_set("session.gc_maxlifetime", Session_Lifetime); 
			session_start();

			$_SESSION['userid']    	  	= $query['result']['id'];
			$_SESSION['fname'] 			= $query['result']['name'];
			$_SESSION['username']		= $query['result']['username'];
			$_SESSION['password']      	= $query['result']['password'];
			$_SESSION['level'] 			= $query['result']['user_level'];
			$_SESSION['profileimg']		= $query['result']['has_img'];
			$time_created			   	= $query['result']['time_created'];
			$_SESSION['time_created']   = date("M. Y",$time_created);
			

	}	
	
	function set_cookie($username, $password, $set) {

			if($set == "+")
				{ $cookie_expire = time()+60*60*24*30; }
			else 
				{ $cookie_expire = time()-60*60*24*30; }		
	
			setcookie($this->cookie_user, $username, $cookie_expire, '/');
			setcookie($this->cookie_pass, $password, $cookie_expire, '/');
	
	} 

	function log_out($username, $password, $header) {
		if($_SESSION['level']=="Engineer") {
			session_start();
			session_unset();
			session_destroy();
			$this->set_cookie($username, $password, '-');

			if(!isset($header)) {
				header('Location: ../login2.php');
			} else {
				return true;
			}
		}else {
			session_start();
			session_unset();
			session_destroy();
			$this->set_cookie($username, $password, '-');

			if(!isset($header)) {
				header('Location: ../');
			} else {
				return true;
			}
		}
	
	}

	function edit_details($post, $process) {

		if(isset($process)) {
			
		$first_name		= $post['first_name'];
		$last_name		= $post['last_name'];
		$email_address	= $post['email_address'];
		$info			= $post['info'];
		$username		= $post['username'];
		$password		= $_SESSION['password'];
		
		if((!$first_name) || (!$last_name) || (!$email_address) || (!$info)) {
			return "Please enter all details.";
		}

		$this->query("UPDATE ".TBLUSER." SET first_name = '$first_name', last_name = '$last_name', 
		email_address = '$email_address', info = '$info' WHERE username = '$username'");		

				$this->set_session($username, $password);		
				if(isset($_COOKIE[$this->cookie_pass])) 
				{ $this->set_cookie($username, $pass, '+'); }

				return "Details sucessfully changed.";
		}
	}

	function edit_password($post, $process) {

		if(isset($process)) {

		$pass1		= $post['pass1'];
		$pass2		= $post['pass2'];
		$password	= $post['pass'];
		$username	= $post['username'];
		
		if ((!$password) || (!$pass1) || (!$pass2)) {
			return "Missing required details.";
		} 
		if (md5($password) !== $_SESSION['password']) {
			return "Current password is incorrect.";
		}
		if ($pass1 !== $pass2) {
			return "New passwords do not match.";
		}

		$new = md5($pass1);
		$this->query("UPDATE ".TBLUSER." SET password = '$new' WHERE username = '$username'");

				$this->set_session($username, $new);		
				if(isset($_COOKIE[$this->cookie_pass])) 
				{ $this->set_cookie($username, $pass, '+'); }

			return "Password update successfull.";
		}
	}

	function Forgot_Password($get, $post) {
	
		$username = $post['username'];
		if(!$username) { 
		$username = $get['username']; } 
		
		$code = $post['code'];
		if(!$code) { 
		$code = $get['code']; } 

		if (isset($code)) {
				$query = $this->query("SELECT * FROM ".TBLUSER." WHERE username='$username' AND forgot='$code'");
			
			if($query['num_rows'] == 1) {		
					return "<!-- !-->";
			}else {
				if(isset($code) && isset($username)) {
					return "Link Invalid, Please Request a new link.";
				} else {
					return false;
				}
			}
		}
	}

	function Request_Password($post, $process) {
		
		$username = $post['username'];
		$email = $post['email'];
			
		if(isset($process)) {

			$query = $this->query("SELECT * FROM ".TBLUSER." WHERE username='$username' AND email_address = '$email'");

			if((!$username) || (!$email)) {
				return "Please enter all details.";
			}

			if($query['num_rows'] == 0){
				return "Matching details were not found.";
			}

		    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
		    srand((double)microtime()*1000000);
		    $i = 0;
		    $pass = '' ;

   			while ($i <= 7) {
   			    $num = rand() % 33;
        		$tmp = substr($chars, $num, 1);
        		$pass = $pass . $tmp;
        		$i++;
    		}
			$code = md5($pass);
			$this->query("UPDATE ".TBLUSER." SET forgot = '$code' WHERE username='$username' AND email_address='$email'");

			Mail_Reset_Password($username, $code, $email);
				return "We have sent an email to your address, this will allow you to reset your password.";
			
		}
	}

	function Reset_Password($post, $process) {

		if(isset($process)) {
		
		$pass1 = $post['pass1'];
		$pass2 = $post['pass2'];
		$username = $post['username'];
		
		if ($pass1 !== $pass2) {
			return "New passwords do not match";
		}
		
			$password = md5($pass1);

		$query = $this->query("UPDATE ".TBLUSER." SET password = '$password', forgot = 'NULL' WHERE username = '$username'");
		
		Mail_Reset_Password_Confirmation($username, $email);
			return "Password Reset Sucsessfull, You may now login.";

		}
	} 
	
	function change_password($post, $process) {
		$this->connect_db();
		if(isset($process)) {

			$oldPass			= $this->mysql_prepare_value($post['old_pass']);
			$newPass			= $this->mysql_prepare_value($post['new_pass']);
			$newPass2			= $this->mysql_prepare_value($post['new_pass2']);
			$username			= $post['username'];
			
			if((!$oldPass) || (!$newPass) || (!$newPass2)) {
				return "<div class=\"alert alert-danger\">Some Fields Are Missing</div>";
			}
			$query = mysql_query("select username,password from swin_applicant_login where username='$username' and password = '".md5($oldPass)."'");
			if(mysql_num_rows($query)!=1) {
				return "<div class=\"alert alert-danger\"><strong>Error:</strong> The Old password you entered is Wrong</div>";
			}			
			if($newPass != $newPass2) {
				return "<div class=\"alert alert-danger\">New Password does not Match</div>";
			}
					
			$queryII = "update swin_applicant_login set password = '".md5($newPass)."' where username = '$username'";
			$result = mysql_query($queryII)or die(mysql_error());
			$this->saveQueryString($queryII);
			if($result) {
				return "<div class=\"alert alert-success\">Password Changed Successfully</div>";
			}
			
		}
	}
	
	function sendMail($post, $process) {
		$this->connect_db();
		if(isset($process)){
			$name			= $this->mysql_prepare_value($post['name']);
			$email			= $this->mysql_prepare_value($post['email']);
			$phone			= $this->mysql_prepare_value($post['phone']);
			$city			= $this->mysql_prepare_value($post['city']);
			$courseID		= $this->mysql_prepare_value($post['course']);
			
			if((!$name) || (!$email) || (!$phone) || (!$city)) {
				return "<div class=\"alert alert-danger\">Some Fields Are Missing</div>";
			}
				
			$query = "select course_name from swin_course WHERE course_id = '$courseID'";
			$result = mysql_query($query)or die(mysql_error());
			$course = mysql_fetch_object($result)or die(mysql_error());
			$courseName = $course->course_name;
			
			$dat = "";

			 //send mail
			 
			 $to = 'ikenna@swinteconline.net';

			$headers = "From: " . strip_tags($email) . "\r\n";
			$headers .= "MIME-Version: 1.0\r\n";
			$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
			
			$message = '<html>
			<body bgcolor="#f7f7f7">';
			$message .= '<table width="700px" border="0" align="center" cellpadding="20" style="border:solid 1px #CCC;"><tr><td valign="top" style="color:#000; font-size:25px"><img src="http://www.swinteconline.net/images/app_logo.png" width="131" height="45"></td></tr>';
			$message .= '<tr><td valign="top"><span style="color:#000; font-size:25px">Requiry from '.$name.'</span></td></tr>';
			$message .= '<tr><td valign="top">Enquiry on '.$courseName.'</td></tr>';
			$message .= "<tr><td valign=\"top\">Phone Number: ".$phone."</td></tr>";
			$message .= "<tr><td>City: ".$city."</td></tr>";  
			$message .= "</table>";
			$message .= "</body></html>";
			 
			$sendmail = mail($to, "New Enquiry", $message, $headers);
			if($sendmail) {
				return '<div class="msg">Your Message Has Been Sent Successfully</div>';
			}else {
				return "Error Sending Message, Try Again";
			}
		}
	}
	
	function countSites() {
		$this->connect_db();
		$query = "select id from site";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countPO() {
		$this->connect_db();
		$query = "select po_id from purchase_order";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countVendors() {
		$this->connect_db();
		$query = "select id from vendors";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countSupervisors() {
		$this->connect_db();
		$query = "select id from supervisors";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countEngineers() {
		$this->connect_db();
		$query = "select id from engineers";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countLiveSite() {
		$this->connect_db();
		$query = "select id from site where status = 'Live'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countITPs() {
		$this->connect_db();
		$query = "select * from itp";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countTickets() {
		$this->connect_db();
		$query = "select ticket_id from tickets";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countOpenTickets() {
		$this->connect_db();
		$query = "select ticket_id from tickets where status = '0'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countClosedTickets() {
		$this->connect_db();
		$query = "select ticket_id from tickets where status = '1'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countIssuedInvoice() {
		$this->connect_db();
		$today = date("Y-m-d", time());
		$query = "select * from invoice_customer where payment_status = 'Not Paid' and invoiced_next = 'Not Done'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countInvoicePaid() {
		$this->connect_db();
		$query = "select id from invoice_customer where payment_status = 'Paid'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countInvoiceDue() {
		$this->connect_db();
		$query = "select id from invoice_customer where due_date <= now() and  payment_status = 'Not Paid'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countDueToIssueInvoice() {
		$this->connect_db();
		$today = date("Y-m-d", time());
		$query = "select * from invoice_customer where next_invoice_date <= '$today' and invoiced_next = 'Not Done'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countInvoiceNotPaid() {
		$this->connect_db();
		$query = "select id from invoice_customer where status = 'Not Paid'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		
		return $countRows;
	}
	
	function countITPTenants() {
		$this->connect_db();
		$query = "select id from site_tenants where state = 'ITP'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		if($countRows >1) {
			return $countRows;
		}else{
			return $countRows;
		}
	}
	
	function countSiteProvisionTenants() {
		$this->connect_db();
		$query = "select id from site_tenants where state = 'Site Provision'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		if($countRows >1) {
			return $countRows;
		}else{
			return $countRows;
		}
	}
	
	function countLiveTenants() {
		$this->connect_db();
		$query = "select id from site_tenants where state = 'Live'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		if($countRows >1) {
			return $countRows;
		}else{
			return $countRows;
		}
	}
	
	function countDecommissionedTenants() {
		$this->connect_db();
		$query = "select id from site_tenants where state = 'Decommissioned'";
		$result = mysql_query($query)or die(mysql_error());
		$countRows = mysql_num_rows($result);
		if($countRows >1) {
			return $countRows;
		}else{
			return $countRows;
		}
	}
	
	function checkSiteID($siteID) {
		$this->connect_db();
		$sql = "SELECT site_id FROM site where site_id = '$siteID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0) {
			return 1;
		}else {
			return 0;
		}
	}
	
	function checkBCTID($bctID) {
		$this->connect_db();
		$sql = "SELECT bct_id FROM site where bct_id = '$bctID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0) {
			return 1;
		}else {
			return 0;
		}
	}
	
	function getTodayExpenses() {
		$this->connect_db();
		$today = date("Y-m-d",time());
		$query = "select sum(ex_amount) as expensetoday from  expenses where  ex_date = '$today'";
		$result = mysql_query($query)or die(mysql_error());
		$expData = mysql_fetch_object($result);
		$expense = $expData->expensetoday;
		return $expense;
	}
	
	function getWeekExpenses() {
		$this->connect_db();
		
		$today = date("Y-m-d",time());
		$sunday = date_create()->modify('last Sunday');
		$weekStart = date_format($sunday,"Y-m-d");
		
		$query = "select sum(ex_amount) as expensetoday from  expenses where ex_date between '$weekStart' and '$today'";
		$result = mysql_query($query)or die(mysql_error());
		$expData = mysql_fetch_object($result);
		$expense = $expData->expensetoday;
		return $expense;
	}
	
	function getMonthExpenses() {
		$this->connect_db();
		
		$today = date("Y-m-d",time());
		$month = date_create()->modify('first day of this month');
		$monthStart = date_format($month,"Y-m-d");
		
		$query = "select sum(ex_amount) as expensetoday from  expenses where ex_date between '$monthStart' and '$today'";
		$result = mysql_query($query)or die(mysql_error());
		$expData = mysql_fetch_object($result);
		$expense = $expData->expensetoday;
		return $expense;
	}
	
	function addSite($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$site_id    		= $this->mysql_prepare_value($post['siteid']);
			$bct_id				= $this->mysql_prepare_value($post['bctid']);
			$address			= $this->mysql_prepare_value($post['address']);
			$region				= strtoupper($this->mysql_prepare_value($post['region']));
			$longitude			= $this->mysql_prepare_value($post['longitude']);
			$latitude			= $this->mysql_prepare_value($post['latitude']);
			$state				= $this->mysql_prepare_value($post['state']);
			$tower_height		= $this->mysql_prepare_value($post['tower_height']);
			$loc_type			= $this->mysql_prepare_value($post['location_type']);
			$site_no			= $this->mysql_prepare_value($post['site_no']);
			$supervisor			= $this->mysql_prepare_value($post['supervisor']);
			$security			= $this->mysql_prepare_value($post['security']);
			$supplier			= $this->mysql_prepare_value($post['supplier']);
			$landType			= $this->mysql_prepare_value($post['landType']);
			$tankMode			= $this->mysql_prepare_value($post['tankMode']);
			$power_threshold	= $this->mysql_prepare_value($post['power_threshold']);
			
			if($post['landType']=="leased"){ 
				$amount 	= $this->mysql_prepare_value($post['amount_leased']);
				$duration	= $this->mysql_prepare_value($post['duration']);
				$acqDate	= $this->mysql_prepare_value($post['lease_date']);
				$lease_alert = $this->mysql_prepare_value($post['lease_alert']);
			}else {
				$amount 	= $this->mysql_prepare_value($post['amount_bought']);
				$duration   = 0;
				$acqDate	= $this->mysql_prepare_value($post['date_bought']);
				$lease_alert = 0;
			}
			
		
			
			//check site_id exists before now
			$checkSiteID = $this->checkSiteID($site_id);
			if($checkSiteID==1) {
				return '<div class="alert alert-danger"><i class="fa fa-ban"></i>Site ID already exists, try another.</div>';
			}
			
			//check bct_id exists before now
			$checkBCTID = $this->checkBCTID($bct_id);
			if($checkBCTID==1) {
				return '<div class="alert alert-danger"><i class="fa fa-ban"></i>BCT ID already exists, try another.</div>';
			}
			
			
			$query = "insert into site values('','$site_id','$bct_id','$address','$region','$longitude','$latitude',
						'$state','$tower_height','$loc_type','$site_no','$supervisor','$security','$supplier','$landType','$amount','$duration','$acqDate','$lease_alert','$tankMode','$power_threshold','on','on','Not Live','0','0')";
					
			$result = mysql_query($query)or die(mysql_error()." 1");
			$sitekey = mysql_insert_id();
			
			//add site power sources
			if(isset($post['genPower'])) { 
				$gen = $post['genPower']; 
				$genService = $post['genservice']; 
				$GenServiceCounter = 0; //this counter get the corresponding gen service hour value of each gen
				$genNumber = 1; //this counter tracks the number of gen inserted to make up the source_name colunm in the db
				foreach ($gen as $genSource) {
					//get gen asset_id;
					//$genData = $this->getAssetInfo($genSource);
					//$assetID = $getData->asset_id;
					
					$insertGen = "insert into power_source values('','$sitekey','Gen','$genSource','Gen $genNumber','".$genService[$GenServiceCounter]."','0','".$_SESSION['userid']."','$time')";
					$resGen = mysql_query($insertGen)or die(mysql_error()." 4");
					$Genkey = mysql_insert_id();
					
					//setup gen current service data
					$SerqueryGen = "insert into service_curr_stats values('','$sitekey','$Genkey','0000-00-00','0','0','0000-00-00','0')";
					$Serviceresult = mysql_query($SerqueryGen)or die(mysql_error()." 6");
					
					$GenServiceCounter++;
					$genNumber++;
				}
			}
			
			
			
			if(isset($post['hybridPower'])) { 
				$hybrid = $post['hybridPower']; 
				$HyServiceCounter = 0; 
				foreach ($hybrid as $hybridsource) {
					$insertHy = "insert into power_source values('','$sitekey','Hybrid','0','$hybridsource','','0','".$_SESSION['userid']."','$time')";
					$resHy = mysql_query($insertHy)or die(mysql_error()." 8");
					$Hykey = mysql_insert_id();
					
					//setup hybrid current service data
					$SerqueryGen1 = "insert into service_curr_stats values('','$sitekey','$Hykey','0000-00-00','0','0','0000-00-00','0')";
					$Serviceresult1 = mysql_query($SerqueryGen1)or die(mysql_error()." 9");
					
					$HyServiceCounter++;
				}
			}
			
			if(isset($post['phcnPower'])) { 
				$phcn = $this->mysql_prepare_value($post['phcnPower']); 
				$insertPhcn = "insert into power_source values('','$sitekey','phnc','0','PHCN','','0','".$_SESSION['userid']."','$time')";
				$resPhcn = mysql_query($insertPhcn)or die(mysql_error()." 2");
				$Phcnkey = mysql_insert_id();
				
				//setup phnc current service data
				$SerqueryGen1 = "insert into service_curr_stats values('','$sitekey','$Phcnkey','0000-00-00','0','0','0000-00-00','0')";
				$Serviceresult1 = mysql_query($SerqueryGen1)or die(mysql_error()." 3");
			}		
			
			if($result) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Site Added Successfully</div>';
			}
		}
	}
	
	function updateSite($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$sid    		= $this->mysql_prepare_value($post['sid']);
			$site_id    		= $this->mysql_prepare_value($post['site_id']);
			$bct_id				= $this->mysql_prepare_value($post['bct_id']);
			$address			= $this->mysql_prepare_value($post['address']);
			$region				= $this->mysql_prepare_value($post['region']);
			$longitude			= $this->mysql_prepare_value($post['longitude']);
			$latitude			= $this->mysql_prepare_value($post['latitude']);
			$state				= $this->mysql_prepare_value($post['state']);
			$site_type			= $this->mysql_prepare_value($post['site_type']);
			$loc_type			= $this->mysql_prepare_value($post['location_type']);
			$site_no			= $this->mysql_prepare_value($post['site_no']);
			$supervisor			= $this->mysql_prepare_value($post['supervisor']);
			$security			= $this->mysql_prepare_value($post['security']);
			$supplier			= $this->mysql_prepare_value($post['supplier']);
			
			$gen_power1			= $this->mysql_prepare_value($post['power_rating1']);
			$capacity1			= $this->mysql_prepare_value($post['capacity1']);
			$hr_rate1			= $this->mysql_prepare_value($post['hr_rate1']);
			$hr_nepa1			= $this->mysql_prepare_value($post['hr_nepa1']);
			
			$gen_power2			= $this->mysql_prepare_value($post['power_rating2']);
			$capacity2			= $this->mysql_prepare_value($post['capacity2']);
			$hr_rate2			= $this->mysql_prepare_value($post['hr_rate2']);
			$hr_nepa2			= $this->mysql_prepare_value($post['hr_nepa2']);
			
			//check if site_id already exist fopr another site
			$checkSiteID = "select id,site_id from site where id != $sid and site_id='$site_id '";
			$checkSiteID_res = mysql_query($checkSiteID)or die(mysql_error());
			$countRowSiteID = mysql_num_rows($checkSiteID_res);
			if($countRowSiteID>0) {
				return '<div class="alert alert-danger"><i class="fa fa-ban"></i>Site ID already exists, try another.</div>';
			}
			
			//check if bct_id already exist fopr another site
			$checkBctID = "select id,bct_id from site where id != $sid and bct_id='$bct_id'";
			$checkBctID_res = mysql_query($checkBctID)or die(mysql_error());
			$countRowBCT = mysql_num_rows($checkBctID_res);
			if($countRowBCT>0) {
				return '<div class="alert alert-danger"><i class="fa fa-ban"></i>BCT ID already exists, try another.</div>';
			}
			
			$query_I = "update site set
						site_id = '$site_id',
						bct_id = '$bct_id',
						address = '$address',
						region = '$region',
						longitude = '$longitude',
						latitude = '$latitude',
						state = '$state',
						site_type = '$site_type',
						location_type = '$loc_type',
						site_no = '$site_no',
						supervisor = '$supervisor',
						security = '$security',
						supplier = '$supplier'
						where id = '$sid'";
					
			$result_I = mysql_query($query_I)or die(mysql_error());
			
			if($result_I) {				
				
				
				//update site generator 1
				$GenqueryI = "update site_gen set
				power_rating = '$gen_power1',
				capacity = '$capacity1',
				hr_rate = '$hr_rate1',
				hr_nepa = '$hr_nepa1'
				where site_id = '$sid' and gen_name = 'gen1'";
				$GenqueryI_result = mysql_query($GenqueryI)or die(mysql_error());
				
				//update site generator 2
				$GenqueryII = "update site_gen set
				power_rating = '$gen_power2',
				capacity = '$capacity2',
				hr_rate = '$hr_rate2',
				hr_nepa = '$hr_nepa2'
				where site_id = '$sid' and gen_name = 'gen2'";
				$GenqueryII_result = mysql_query($GenqueryII)or die(mysql_error());
				
				if($GenqueryI_result && $GenqueryII_result) {
					return '<div class="alert alert-success"><i class="fa fa-check"></i>Site Info Updated</div>';
				}else {
				
				}
			}
		}
	}
	
	function addCustomer($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			
			$customerName		= $this->mysql_prepare_value(trim($post['customername']));
			$short_name			= $this->mysql_prepare_value(strtoupper(trim($post['acro'])));
			$custType			= $this->mysql_prepare_value(trim($post['custType']));
			$terms				= $this->mysql_prepare_value(trim($post['terms']));
			$address			= $this->mysql_prepare_value(trim($post['address']));			
			$city				= $this->mysql_prepare_value(trim($post['city']));			
			$phone				= $this->mysql_prepare_value(trim($post['phone']));			
			$email				= $this->mysql_prepare_value(trim($post['email']));			

			$query_I = "insert into customer values('','$customerName','$short_name','$custType','$terms','$address','$city','$phone','$email','".$_SESSION['userid']."','$time')";
					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Customer Added</div>';
			}
		}
	}
	
	function addTenant($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$site_id    		= $this->mysql_prepare_value(trim($post['siteID']));
			$customerName		= $this->mysql_prepare_value(trim($post['cus_name']));
			$rf					= $this->mysql_prepare_value(trim($post['rf']));
			$mw					= $this->mysql_prepare_value(trim($post['mw']));			
			$height				= $this->mysql_prepare_value(trim($post['height']));			
			$cost				= $this->mysql_prepare_value(trim($post['cost']));			
			$criteria			= $this->mysql_prepare_value(trim($post['criteria']));			
			$state				= $this->mysql_prepare_value(trim($post['state']));			

			$query_I = "insert into site_tenants values('','$site_id','$customerName','$rf','$mw','$height','$cost','0','0','$time','$time','$state','0','Not Invoiced')";
					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Customer Added</div>';
			}
		}
	}
	
	function addCommercialTerm($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$comm_name    		= $this->mysql_prepare_value(trim($post['comm_name']));
			$period				= $this->mysql_prepare_value(trim($post['period']));
			$criteria			= $this->mysql_prepare_value(trim($post['criteria']));
			$netdays			= $this->mysql_prepare_value(trim($post['net_days']));			

			$query_I = "insert into commercial_terms values('','$comm_name','$period','$criteria','$netdays','".$_SESSION['userid']."','$time')";
					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Commercial Term Added</div>';
			}
		}
	}
	
	function addProject($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$project_name  		= $this->mysql_prepare_value(trim($post['project_name']));
			$project_decs		= $this->mysql_prepare_value(trim($post['project_decs']));			

			$query_I = "insert into bj_projects values('','$project_name','$project_decs','$time')";
					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Project Saved</div>';
			}
		}
	}
	
	function addTicket($post,$file,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$siteID    		= $this->mysql_prepare_value(trim($post['siteID']));
			$severity  		= $this->mysql_prepare_value(trim($post['severity']));
			$subject		= $this->mysql_prepare_value(trim($post['subject']));
			$message		= $this->mysql_prepare_value(trim($post['message']));
			
			$ticketImg		= $file['ticketimg'];
			$ticketImgdesc	= $post['img_title'];
			
			//generate ticket reference
			$ticketRef = $this->genTicketRef();

			$query = "insert into tickets values('','$ticketRef','$siteID','".$_SESSION['userid']."','$severity','$subject','$message','$time','0','".$_SESSION['userid']."','0','0')";
			$result = mysql_query($query)or die(mysql_error());
			$ticketId = mysql_insert_id();
			if($result) {
				//check if there is any ticket image and save to db
				$imgCount = count($ticketImg['name']);
				
				//loop to add image if any
				for($i=0;$i<$imgCount;$i++) {					
					if($ticketImg['name'][$i]!=NULL) {					
						$target_path = "ticket_img/";
						$target_path = $target_path . $time.basename($ticketImg['name'][$i]);
						$file_name = $time.basename( $ticketImg['name'][$i]);
						move_uploaded_file($ticketImg['tmp_name'][$i], $target_path);
						
						$query2 = "insert into ticket_img values('','$ticketId','".$ticketImgdesc[$i]."','$file_name')";	
						$result2 = mysql_query($query2)or die(mysql_error());
					}
				}
			
				//get ticket notification enabled user
				$ticketUsers = $this->getTicketNotificationUsers();
				if($ticketUsers!=0){
					//get the name of the user that opened the ticket
					$userData = $this->getUserInfo($_SESSION['userid']);
					$user_name = $userData->name;
					//insert notification.
					while($ticketuser = mysql_fetch_object($ticketUsers)){
						$enabledUsers = $ticketuser->id;
						mysql_query("insert into ticket_notification values('','$ticketId','$siteID','".$_SESSION['userid']."','$enabledUsers','New Ticket opened by $user_name','ticket topic','no','0','$time','0','0')");
					}
				}
							
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Ticket Sent Successfully '.$ticketUsers.'</div>';
			}
		}
	}
	
	function ticketImage($post,$file,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			$ticket_id    		= $post['ticket_id'];
			$ticket_id    		= $post['ticket_id'];
			
			$target_path = "ticket_img/";
			$target_path = $target_path . $time.basename($_FILES['timg']['name']);
			$Userfile = $time.basename( $_FILES['timg']['name']);
			move_uploaded_file($_FILES['timg']['tmp_name'], $target_path);
			
			$query .= "insert into ticket_img values('','$ticket_id','$target_path')";	
			$result = mysql_query($query)or die(mysql_error());
			if($result) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Image Upload Successfull</div>';
			}
		}
	}
	
	
	
	function getTicketImages($tid) {
		$this->connect_db();
		$sql = "select * from ticket_img where ticket_id = '$tid' order by id desc";
		$result = mysql_query($sql)or die(mysql_error());
		$countRow = mysql_num_rows($result);

		if($countRow>0) {
			echo"<div class=\"col-md-12\">
					<!-- panel -->
					<div class=\"panel panel-piluku\">
						<div class=\"panel-body\">";
			while($imgs = mysql_fetch_object($result)) {
			
				$sn +=1;
				$fileid  	= $imgs->id;
				$imgDesc  	= $imgs->img_desc;
				$imgName  	= $imgs->file_name;
				
				echo"<div class=\"col-md-4\"><img src=\"ticket_img/$imgName\" width=\"200\" class=\"img-responsive\" />$imgDesc</div>";

			}
			echo"</div>
					</div>
					<!-- /panel -->
				</div>
				<!-- /col-md-6 -->";
		}
	}
	
	function addTicketComment($post,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$tid    		= $this->mysql_prepare_value(trim($post['tid']));
			$userid			= $this->mysql_prepare_value(trim($post['userid']));
			$userlevel		= $this->mysql_prepare_value(trim($post['userlevel']));			
			$comment		= $this->mysql_prepare_value(trim($post['comment']));			

			$query_I = "insert into ticket_reply values('','$tid','$userid','$userlevel','$comment','$time')";	
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				
				//get ticket Data
				$ticketData = $this->getTicketInfo($tid);
				$ticketId = $ticketData->ticket_id;
				$owner = $ticketData->engr_id;
				$siteID = $ticketData->site_id;
				$receipents = explode(",",$ticketData->notification_recipients);
				
				//get the name of the user that opened the ticket
				$userData = $this->getUserInfo($_SESSION['userid']);
				$user_name = $userData->name;
				//insert notification.
				foreach($receipents as $userid){
					mysql_query("insert into ticket_notification values('','$ticketId','$siteID','".$_SESSION['userid']."','$userid','$user_name responded to a Ticket','ticket reply''no','0','$time')");
				}
				
				//check if this user is in the receipent list, add  if the user is not in it and update the receipent's column
				if(!in_array($_SESSION['userid'],$receipents)){
					array_push($receipents,$_SESSION['userid']);
					$newReceipents = implode(",",$receipents);
					mysql_query("update tickets set notification_recipients = '$newReceipents' where ticket_id = '$ticketId'")or die(mysql_error());
				}
							
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Comment Posted Successfully</div>';
			}
		}
	}
	
	function addEscComment($post,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$eid    		= $this->mysql_prepare_value(trim($post['eid']));
			$userid			= $this->mysql_prepare_value(trim($post['userid']));
			$userlevel		= $this->mysql_prepare_value(trim($post['userlevel']));			
			$comment		= $this->mysql_prepare_value(trim($post['comment']));			

			$query_I = "insert into downtime_comments values('','$eid','".$_SESSION['userid']."','$comment','$time')";	
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {							
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Comment Posted Successfully</div>';
			}
		}
	}
	
	function adduserFile($post,$file,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			$ftitle    		= $this->mysql_prepare_value(trim($post['fileTitle']));
			$ftype			= $this->mysql_prepare_value(trim($post['ftype']));
			
			$target_path = "files/";
			$target_path = $target_path . $time.basename($_FILES['user_file']['name']);
			$Userfile = $time.basename( $_FILES['user_file']['name']);
			move_uploaded_file($_FILES['user_file']['tmp_name'], $target_path);
			
			$query .= "insert into user_files values('','".$_SESSION['userid']."','$ftitle','$ftype','$target_path','$time')";	
			$result = mysql_query($query)or die(mysql_error());
			if($result) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> File Upload Successfull</div>';
			}
		}
	}
	
	function checkBatchSupply($siteID, $batchID) {
		$this->connect_db(); 
		$query = "select site_id,site_batch_id from supplies where site_id = '$siteID' and site_batch_id = '$batchID'";	
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow>0) {
			return 1;
		}else{
			return 0;
		}
	}
	
	function addSupply($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			$date_submitted = date("Y-m-d",time());
			
			//Alway normal variables at every submit
			$siteID    		= $this->mysql_prepare_value(trim($post['siteID']));			
			$siteBatchID	= $this->mysql_prepare_value(trim($post['siteBatchID']));			
			$supplyDate		= $this->mysql_prepare_value(trim($post['supplyDate']));
			$cpd			= $this->mysql_prepare_value(trim($post['cpd']));					
			$litercost		= $this->mysql_prepare_value(trim($post['litercost']));					
			$vendor			= $this->mysql_prepare_value(trim($post['vendor']));					
			$comment		= $this->mysql_prepare_value(trim($post['comment']));			
			$nextDate		= $this->mysql_prepare_value(trim($post['nextDate']));

			
			
			//Always array at every submit
			$supplied_qty	= $post['supplied_qty'];				
			$init_stock  	= $post['init_stock'];
			$tanks   		= $post['tank'];			
			$runnhrs		= $post['runnhrs'];				
			$sourceid  		= $post['sourceid'];
			
			//check if supply has been made to this site under this batch
			$checkBatchSupply = $this->checkBatchSupply($siteID, $siteBatchID);
			
			if($checkBatchSupply==0) {

				//get total cost of supply
				$totalCost = $litercost * array_sum($supplied_qty);
				
				//get some site Data
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$siteTanks = $siteData->tank_mode;
				$approveSupply = $siteData->approve_supply;

				$year = substr($supplyDate,0,4);
				$month = substr($supplyDate,5,2);
				$day = substr($supplyDate,8,9);
				
				switch($month) {
					case "01":
					$supplyMonth = "Jan";
					$orderMonth = '1';
					break;
					case "02":
					$supplyMonth = "Feb";
					$orderMonth = '2';
					break;
					case "03":
					$supplyMonth = "Mar";
					$orderMonth = '3';
					break;
					case "04":
					$supplyMonth = "Apr";
					$orderMonth = '4';
					break;
					case "05":
					$supplyMonth = "May";
					$orderMonth = '5';
					break;
					case "06":
					$supplyMonth = "Jun";
					$orderMonth = '6';
					break;
					case "07":
					$supplyMonth = "Jul";
					$orderMonth = '7';
					break;
					case "08":
					$supplyMonth = "Aug";
					$orderMonth = '8';
					break;
					case "09":
					$supplyMonth = "Sep";
					$orderMonth = '9';
					break;
					case "10":
					$supplyMonth = "Oct";
					$orderMonth = '10';
					break;
					case "11":
					$supplyMonth = "Nov";
					$orderMonth = '11';
					break;
					case "12":
					$supplyMonth = "Dec";
					$orderMonth = '12';
					break;
				}
				
				//update previous supply on this site, ie set it as supplied
				$updatePreviousSiteSupply = $this->updatePreviousSiteSupplyStatus($siteID);
				if($updatePreviousSiteSupply==1) {
				
					$query = "insert into supplies values('','$siteID','$siteBatchID','".$_SESSION['userid']."','$supplyDate','$year','$supplyMonth','$orderMonth','$cpd','$nextDate','$litercost','$totalCost','$vendor','$comment','','0','High','$date_submitted',";
					if($approveSupply=="on") { $query .="'Pending','0','0',"; }else { $query .="'Approved','0','$time',"; }
					$query .="'$time')";
					$result = mysql_query($query)or die(mysql_error());
					$supplyID = mysql_insert_id();
					
				
					$counter = 0; //tracks each row that has been added
					
					for($i=1;$i<=$siteTanks;$i++) {
						$newStock = $init_stock[$counter] + $supplied_qty[$counter];
						
						//insert supply details on tank on site.
						$query_I = "insert into supplies_details values('','$supplyID','$siteID','Tank $i','".$this->mysql_prepare_value(trim($init_stock[$counter]))."',
									'".$this->mysql_prepare_value(trim($supplied_qty[$counter]))."','$newStock','".$this->mysql_prepare_value(trim($init_stock[$counter]))."',
									'".$this->mysql_prepare_value(trim($supplied_qty[$counter]))."','$newStock','".$this->mysql_prepare_value(trim($init_stock[$counter]))."',
									'".$this->mysql_prepare_value(trim($supplied_qty[$counter]))."','$newStock','$year','$supplyMonth','$orderMonth','$day','$time')";
						$result_I = mysql_query($query_I)or die(mysql_error());
						
						$counter++;
					}
					
					//insert the new power sources running hours
					$PowerIDcounter = 0; //this counter is used to keep track of the power source ID;
					foreach($runnhrs as $runningHour) {
						//insert ruuning hours
						$sqlRunhours = "insert into site_running_hours values('','".$sourceid[$PowerIDcounter]."','$runningHour','supply','$supplyID','$time')";
						$resultRunhours = mysql_query($sqlRunhours)or die(mysql_error());
							
						$PowerIDcounter++;
					}
					if($resultRunhours) {
						//get supply Notification enabled users
						$supplyUsers = $this->getSupplyNotificationUsers();
						if($supplyUsers!=0){
							//get the name of the user that supllied the report
							$userData = $this->getUserInfo($_SESSION['userid']);
							$user_name = $userData->name;
							
							//insert notification.
							while($supplyUser = mysql_fetch_object($supplyUsers)){
								$enabledUser = $supplyUser->id;
								$notify_sql = "insert into supply_notification values('','$supplyID','$siteID','".$_SESSION['userid']."','$enabledUser','Supply on Site $site_id by $user_name','no','0','Done',";
								if($approveSupply=="on") {$notify_sql .= "'Pending',";}else{ $notify_sql .= "'Approved',";}								
								$notify_sql .= "'$time')";
								$notify_res = mysql_query($notify_sql)or die(mysql_error());
							}
						}
						//update dieselevel_notification work Order to done
						mysql_query("update dieselevel_notification set work_order = 'Done' where site_id='$siteID'")or die(mysql_error());
						mysql_query("update supply_batch_site set status = 'reported' where id='$siteBatchID'")or die(mysql_error());
						return '<div class="alert alert-success"><i class="fa fa-check"></i> Supply Added Successfully</div>';
					}			
				}else{
					return '<div class="alert alert-danger"><i class="fa fa-times"></i> Operation Failed: Could not update Pervious Supply</div>';
				}
			}else {
				return '<div class="alert alert-danger"><i class="fa fa-times"></i> Operation Failed: Supply for this Site in the Batch has been submitted before</div>';
			}
		}
	}
	
	function ConfirmSupplyReport($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			
			//Alway normal variables at every submit
			$supplyID    	= $this->mysql_prepare_value(trim($post['supply_id']));						
			$comment		= $this->mysql_prepare_value(trim($post['qa_comment']));	
			
			//Always array at every submit
			$tanks  = $post['tanks'];	
			
			
			foreach($tanks as $tank) {
				$init_stock_var = "init_stock_".$tank;
				$supplied_var = "supplied_qty_".$tank;
				
				$initial_stock = $post[$init_stock_var];
				$supplied_qty = $post[$supplied_var];
				$newStock = $initial_stock + $supplied_qty;
				
				//insert supply details on tank on site.
				$query_I = "update supplies_details set initial_stock='$initial_stock',supplied_qty='$supplied_qty',
				new_stock='$newStock',qa_initial_stock='$initial_stock',qa_supplied_qty='$supplied_qty',qa_new_stock='$newStock' 
				where id = '".$tank."'";
				$result_I = mysql_query($query_I)or die(mysql_error()." 2");				
			}
			
			if($result_I) {
				mysql_query("update supplies set qa_comment = '$comment', approve_status = 'Approved', approved_by = '".$_SESSION['userid']."', date_approved='$time' where id = '$supplyID'")or die(mysql_error());
				mysql_query("update supply_notification set approved_status = 'Approved' where supply_id = '$supplyID'")or die(mysql_error());
				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Report Approved</div>';
			}else{
				return '<div class="alert alert-danger"><i class="fa fa-check"></i> Report Approval Failed</div>';
			}
		}
	}
	
	function ConfirmService($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			
			//Alway normal variables at every submit
			$serviceID    	= $this->mysql_prepare_value(trim($post['service_id']));							
			$comment		= $this->mysql_prepare_value(trim($post['qa_comment']));	
			
				
				//insert supply details on tank on site.
				$query_I = "update servicing set qa_comment='$comment',approve_status='Approved',approved_by='".$_SESSION['userid']."',date_approved='$time' 
				where id = '$serviceID'";
				$result_I = mysql_query($query_I)or die(mysql_error());	
			if($result_I) {
				mysql_query("update service_notification set approved_status = 'Approved' where service_id = '$serviceID'")or die(mysql_error());
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Report Approved</div>';
			}else{
				return '<div class="alert alert-danger"><i class="fa fa-check"></i> Report Approval Failed</div>';
			}
		}
	}
	
	function updateSupply($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			$date_submitted = date("Y-m-d",time());
			
			//Alway normal variables at every submit
			$supply_id 		= $post['rid'];			
			$siteID    		= $post['siteID'];			
			$supplyDate		= $this->mysql_prepare_value(trim($post['supplyDate']));
			$cpd			= $this->mysql_prepare_value(trim($post['cpd']));					
			$comment		= $this->mysql_prepare_value(trim($post['comment']));			
			$nextDate		= $this->mysql_prepare_value(trim($post['nextDate']));	
			
			//Always array at every submit
			$supplied_qty	= $post['supplied_qty'];				
			$init_stock  	= $post['init_stock'];		
			$runnhrs		= $post['runnhrs'];				
			$sourceid  		= $post['sourceid'];			

			$year = substr($supplyDate,0,4);
			$month = substr($supplyDate,5,2);
			$day = substr($supplyDate,8,9);
			
			switch($month) {
				case "01":
				$supplyMonth = "Jan";
				$orderMonth = '1';
				break;
				case "02":
				$supplyMonth = "Feb";
				$orderMonth = '2';
				break;
				case "03":
				$supplyMonth = "Mar";
				$orderMonth = '3';
				break;
				case "04":
				$supplyMonth = "Apr";
				$orderMonth = '4';
				break;
				case "05":
				$supplyMonth = "May";
				$orderMonth = '5';
				break;
				case "06":
				$supplyMonth = "Jun";
				$orderMonth = '6';
				break;
				case "07":
				$supplyMonth = "Jul";
				$orderMonth = '7';
				break;
				case "08":
				$supplyMonth = "Aug";
				$orderMonth = '8';
				break;
				case "09":
				$supplyMonth = "Sep";
				$orderMonth = '9';
				break;
				case "10":
				$supplyMonth = "Oct";
				$orderMonth = '10';
				break;
				case "11":
				$supplyMonth = "Nov";
				$orderMonth = '11';
				break;
				case "12":
				$supplyMonth = "Dec";
				$orderMonth = '12';
				break;
			}
			
				
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$siteTanks = $siteData->tank_mode;
							
				$query = "update supplies set supply_date ='$supplyDate',cpd='$cpd',next_supply_date='$nextDate',comment='$comment'
						where id = '$supply_id'";
				$result = mysql_query($query)or die(mysql_error());
				
			
				$counter = 0; //tracks each row that has been added
				$totalStock = 0;
				for($i=1;$i<=$siteTanks;$i++) {
					$newStock = $init_stock[$counter] + $supplied_qty[$counter];
					
					//insert supply details on tank on site.
					$query_I = "update supplies_details set initial_stock = '".$this->mysql_prepare_value(trim($init_stock[$counter]))."',
								supplied_qty = '".$this->mysql_prepare_value(trim($supplied_qty[$counter]))."',
								new_stock = '$newStock',year='$year',month='$supplyMonth',month_order='$orderMonth',day='$day'
								where supply_id = '$supply_id' and tank = 'Tank $i'";
					$result_I = mysql_query($query_I)or die(mysql_error());
					
					$totalStock =$totalStock+$newStock;
					$counter++;
				}
				
				//update supply cost
				$supplyData = $this->getSupplyInfo($supply_id);
				$unitCost = $supplyData->unit_cost;
				$TotalCost = $unitCost*$totalStock;
				$updatesql = mysql_query("update supplies set cost = '$TotalCost' where id = '$supply_id'")or die(mysql_error());
				
				//insert the new power sources running hours
				$PowerIDcounter = 0; //this counter is used to keep track of the power source ID;
				foreach($runnhrs as $runningHour) {
						
						//update Power source total ran hours and running hour track columns
						$updateRunhours = "update site_running_hours set 
											running_hrs = '$runningHour'
											where power_id = '".$sourceid[$PowerIDcounter]."' 
											and reported_from = 'supply' 
											and report_id='$supply_id'";
						$resultRunhours = mysql_query($updateRunhours)or die(mysql_error());
						
					$PowerIDcounter++;
				}
				if($resultRunhours) {
					
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Supply Updated Successfully</div>';
				}
		}
	}	
	
	function addWeekReport($post, $process) {
		$this->connect_db(); 
		
		//get diesel reoder level threshold
		$dieselCongi = $this->getDieselConfigInfo();
		$reorderLevel = $dieselCongi->reorder_level;
		
		if(isset($process)) {
			
			$time = time();
			$date_submitted = date("Y-m-d",$time);

			$siteID    		= $this->mysql_prepare_value(trim($post['siteID']));			
			$reportDate		= $this->mysql_prepare_value(trim($post['reportDate']));				
			$comment		= $this->mysql_prepare_value(trim($post['comment']));	
			
			$stock_level    = $post['stock_level'];				
			$runnhrs		= $post['runnhrs'];				
			$sourceid		= $post['sourceid'];
			$tank			= $post['tank'];
			
			$totalSiteCurrStock = array_sum($stock_level);
			
			//get some site Data
			$siteData = $this->getSiteInfo($siteID);
			$site_id = $siteData->site_id;
		
			$query = "insert into weekly_report values('','$siteID','".$_SESSION['userid']."','$reportDate','$comment','$date_submitted ','$time')";
			$result = mysql_query($query)or die(mysql_error());
			$weekID = mysql_insert_id();
			if($result) {
				//insert the diesel level of tanks on site
				$Supplycounter = 0;
				foreach($stock_level  as $level) {
					$queryII = "insert into weekly_diesel_level values('','$weekID','$siteID','".$tank[$Supplycounter]."','$level','$time')";
					$resultII = mysql_query($queryII)or die(mysql_error());
					$Supplycounter++;
				}
				
				//insert the diesel level of tanks on site
				$runHourcounter = 0;
				foreach($runnhrs  as $runHours) {
					$queryIII = "insert into weekly_running_hours values('','$weekID','$siteID','".$sourceid[$runHourcounter]."','$runHours','$time')";
					$resultIII = mysql_query($queryIII)or die(mysql_error());
					
					$sql = "insert into site_running_hours values('','".$sourceid[$runHourcounter]."','$runHours','week_report','$weekID','$time')";
					$res = mysql_query($sql)or die(mysql_error());
					
					$runHourcounter++;
				}
				
				/*	Check the current site stock level percentage and update site supple diesel_level_status.
				*	NOTE: 100% - 61  = HIGH, 60% - 40 = NORMAL, 39% - 0 = LOW	
				*/
				$lastSupplyStock = $this->getSiteLastStockQty($siteID);
				$percentage = (100*$totalSiteCurrStock)/$lastSupplyStock;
				$remainingPercent = 100-$percentage;
				$remainingPercentRound = round($remainingPercent, 2);
				if($remainingPercentRound<=39) { $dls = "Low"; }elseif($remainingPercentRound>=40 && $remainingPercentRound<=60) { $dls = "Normal"; }else{ $dls = "High"; }
				mysql_query("update supplies set diesel_level_status = '$dls' where site_id = '$siteID' and status = '0'")or die(mysql_error());
				
				
				if($resultIII) {
					//get supply Notification enabled users
					$weeklyUsers = $this->getWeeklyReportNotificationUsers();
					if($weeklyUsers!=0){
						//get the name of the user that opened the ticket
						$userData = $this->getUserInfo($_SESSION['userid']);
						$user_name = $userData->name;
						
						//insert notification.
						while($weeklyUser = mysql_fetch_object($weeklyUsers)){
							$enabledUser = $weeklyUser->id;
							mysql_query("insert into notifications values('','New Weekly Report on Site $site_id submitted by $FullName','week_report','$weekID','$siteID','$enabledUser','no','0','$time')")or die(mysql_error());
						}
					}
					
					//check if the site diesel level has reached or gone below the reorder Level and if yes create a work order notification
					
					if($totalSiteCurrStock==$reorderLevel || $totalSiteCurrStock<$reorderLevel){
						//get supply Notification enabled users
						$reOrderUsers = $this->getDieselOrorderNotificationUsers();
						if($reOrderUsers!=0){
							//get the name of the user that opened the ticket
							$userData = $this->getUserInfo($_SESSION['userid']);
							$user_name = $userData->name;
							
							//insert notification.
							while($reOrderUser = mysql_fetch_object($reOrderUsers)){
								$enabledUser = $reOrderUser->id;
								mysql_query("insert into dieselevel_notification values('','$siteID','$enabledUser','Site $site_id is Due for Diesel Reoreder','Not Seen','0','Not Done','$time')")or die(mysql_error());
							}
						}
					}
					
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Report Submitted Successfully</div>';
				}
			}else {
				return '<div class="alert alert-danger"><i class="fa fa-times"></i> Operation Failed</div>';
			}
		}
	}	
	
	function addQAWeekReport($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();
			$date_submitted = date("Y-m-d",$time);

			$siteID    		= $this->mysql_prepare_value(trim($post['siteID']));			
			$reportDate		= $this->mysql_prepare_value(trim($post['reportDate']));				
			$comment		= $this->mysql_prepare_value(trim($post['comment']));	
			
			$stock_level    = $post['stock_level'];				
			$runnhrs		= $post['runnhrs'];				
			$sourceid		= $post['sourceid'];
			$tank			= $post['tank'];
			
			$totalSiteCurrStock = array_sum($stock_level);
		
			$query = "insert into qa_weekly_report values('','$siteID','".$_SESSION['userid']."','$reportDate','$comment','Not Viewed','$date_submitted ','$time')";
			$result = mysql_query($query)or die(mysql_error());
			$weekID = mysql_insert_id();
			if($result) {
				//insert the diesel level of tanks on site
				$Supplycounter = 0;
				foreach($stock_level  as $level) {
					$queryII = "insert into qa_weekly_diesel_level values('','$weekID','$siteID','".$tank[$Supplycounter]."','$level','$time')";
					$resultII = mysql_query($queryII)or die(mysql_error());
					$Supplycounter++;
				}
				
				//insert the diesel level of tanks on site
				$runHourcounter = 0;
				foreach($runnhrs  as $runHours) {
					$queryIII = "insert into qa_weekly_running_hours values('','$weekID','$siteID','".$sourceid[$runHourcounter]."','$runHours','$time')";
					$resultIII = mysql_query($queryIII)or die(mysql_error());
					
					$sql = "insert into qa_site_running_hours values('','".$sourceid[$runHourcounter]."','$runHours','week_report','$weekID','$time')";
					$res = mysql_query($sql)or die(mysql_error());
					
					$runHourcounter++;
				}
				
				$lastSupplyStock = $this->getSiteLastStockQty($siteID);
				
				//calculate percent of disel remaining
				$percentage = (100*$totalSiteCurrStock)/$lastSupplyStock;
				$remainingPercent = 100-$percentage;
				$remainingPercentRound = round($remainingPercent, 2);
				if($remainingPercentRound<=39) { $dls = "Low"; }elseif($remainingPercentRound>=40 && $remainingPercentRound<=60) { $dls = "Normal"; }else{ $dls = "High"; }
				mysql_query("update qa_supplies set diesel_level_status = '$dls' where site_id = '$siteID' and status = '0'")or die(mysql_error());
				
				if($resultIII) {	
					//get user who submitted the report 
					$siteData = $this->getSiteInfo($siteID);
					$site_id = $siteData->site_id;
					
					//get user who submitted the report 
					$userData = $this->getUserInfo($_SESSION['userid']);
					$FullName = $userData->name;
					//Created Notification (Work Order) for Week report submitted
					$notifQuery = mysql_query("insert into notifications values('','Quality Assurance: New Weekly Report on Site $site_id submitted by $FullName','week_report','$weekID','$siteID','no','Not Done','$date')")or die(mysql_error());
					if($notifQuery) {
						return '<div class="alert alert-success"><i class="fa fa-check"></i> Report Submitted Successfully</div>';
					}
				}
			}else {
				return '<div class="alert alert-danger"><i class="fa fa-times"></i> Operation Failed</div>';
			}
		}
	}
	
	function updatePreviousSiteServicingStatus($siteID) {
		$this->connect_db(); 
		
		//get last service id
		$query = mysql_query("select * from servicing where site_id = '$siteID' and status = '0'")or die(mysql_error());
		$serviceData = mysql_fetch_object($query);
		$serviceid = $serviceData->id;		
		
		$query = "update servicing set status  = '1', report_status = 'Closed' where site_id = '$siteID' and status = '0'";
		$Result = mysql_query($query)or die(mysql_error());
		
		if($updateQuery && $Result) {
			return 1;
		}else{
			return 0;
		}
	}
	
	function updatePreviousSiteServicingStatusQA($siteID) {
		$this->connect_db(); 
		
		//get last service id
		$query = mysql_query("select * from qa_servicing where site_id = '$siteID' and status = '0'")or die(mysql_error());
		$serviceData = mysql_fetch_object($query);
		$serviceid = $serviceData->id;
		
		$query = "update qa_servicing set status  = '1' where site_id = '$siteID' and status = '0'";
		$Result = mysql_query($query)or die(mysql_error());
		
		if($updateQuery && $Result) {
			return 1;
		}else{
			return 0;
		}
	}
	
	function updatePreviousSiteSupplyStatus($siteID) {
		$this->connect_db(); 
		
		//get last supply id
		$query = mysql_query("select * from supplies where site_id = '$siteID' and status = '0'")or die(mysql_error());
		$supplyData = mysql_fetch_object($query);
		$supplyid = $supplyData->id;
		
		$query1 = "update supplies set status  = '1' where site_id = '$siteID' and status = '0'";
		$Result = mysql_query($query1)or die(mysql_error());
		if($Result) {
			return 1;
		}else{
			return 0;
		}
	}
	
	function updatePreviousSiteSupplyStatusQA($siteID) {
		$this->connect_db(); 
		
		//get last supply id
		$query = mysql_query("select * from qa_supplies where site_id = '$siteID' and status = '0'")or die(mysql_error());
		$supplyData = mysql_fetch_object($query);
		$supplyid = $supplyData->id;
		
		$query1 = "update qa_supplies set status  = '1' where site_id = '$siteID' and status = '0'";
		$Result = mysql_query($query1)or die(mysql_error());
		if($Result) {
			return 1;
		}else{
			return 0;
		}
	}
	
	function addServicing($post, $process) {
		$this->connect_db(); 
		if(isset($process)) {

			$siteID    				= $this->mysql_prepare_value(trim($post['siteID']));			
			$servicecost			= $this->mysql_prepare_value(trim($post['servicecost']));			
			$serviceDate			= $this->mysql_prepare_value(trim($post['serviceDate']));
			$nextServiceDate		= $this->mysql_prepare_value(trim($post['nextServiceDate']));				
			$count					= $this->mysql_prepare_value(trim($post['count']));	
			$comment				= $this->mysql_prepare_value(trim($post['comment']));
			
			$runnhrs				= $post['runnhrs'];
			$nxtrunnhrs				= $post['nxtrunnhrs'];
			$sourceid				= $post['sourceid'];
			$itemid					= $post['sitemid'];
			$items					= $post['sitem'];
			$itemsQty				= $post['itemqty'];
			$item_cost				= $post['itemcost'];

			$time = time();
			$date_submitted = date("Y-m-d",time());
			
			$year = substr($serviceDate,0,4);
			$month = substr($serviceDate,5,2);
			$day = substr($serviceDate,8,9);
			
			switch($month) {
				case "01":
				$serviceMonth = "Jan";
				$orderMonth = '1';
				break;
				case "02":
				$serviceMonth = "Feb";
				$orderMonth = '2';
				break;
				case "03":
				$serviceMonth = "Mar";
				$orderMonth = '3';
				break;
				case "04":
				$serviceMonth = "Apr";
				$orderMonth = '4';
				break;
				case "05":
				$serviceMonth = "May";
				$orderMonth = '5';
				break;
				case "06":
				$serviceMonth = "Jun";
				$orderMonth = '6';
				break;
				case "07":
				$serviceMonth = "Jul";
				$orderMonth = '7';
				break;
				case "08":
				$serviceMonth = "Aug";
				$orderMonth = '8';
				break;
				case "09":
				$serviceMonth = "Sep";
				$orderMonth = '9';
				break;
				case "10":
				$serviceMonth = "Oct";
				$orderMonth = '10';
				break;
				case "11":
				$serviceMonth = "Nov";
				$orderMonth = '11';
				break;
				case "12":
				$serviceMonth = "Dec";
				$orderMonth = '12';
				break;
			}
			
			//update previous Service on this site, ie set it as Serviced
			$UpdatePreviousService = $this->updatePreviousSiteServicingStatus($siteID);
			if($UpdatePreviousService = 1) {

				$query_I = "insert into servicing values('','$siteID','".$_SESSION['userid']."','$serviceDate','$nextServiceDate','$servicecost','$count','$serviceMonth','$year','$orderMonth','$comment','','0','$date_submitted','Pending','0','0','Open','$time')";
				$result_I = mysql_query($query_I)or die(mysql_error()." e1");
				$serviceID = mysql_insert_id();
				
				if($result_I) {
					$counter = 0; //tracks each row that has been added
					foreach($runnhrs as $runningHour) {
						
						//insert supply details on tank on site.
						$query_I = "insert into servicing_details values('','$siteID','$serviceID','".$sourceid[$counter]."','$runningHour','".$nxtrunnhrs[$counter]."','$count','$serviceMonth','$year','$orderMonth','$time')";
						$result_I = mysql_query($query_I)or die(mysql_error()." e2");
						
						//update Power source total ran hours and running hour track columns
						$sqlRunhours = "insert into site_running_hours values('','".$sourceid[$counter]."','$runningHour','service','$serviceID','$time')";
						$resultRunhours = mysql_query($sqlRunhours)or die(mysql_error()." e3");
						
						$counter++;
					}
					
					$counter2 = 0; //tracks each row that has been added
					$totalServiceCost = 0;
					for($i=0;$i<count($itemid);$i++) {
						//get total service item cost
						$itemCost = $itemsQty[$i] * $item_cost[$i];
						//insert service items on site.
						$sql = "insert into service_item values('','$siteID','$serviceID','".$itemid[$i]."','".$itemsQty[$i]."','$itemCost','$time')";
						$res = mysql_query($sql)or die(mysql_error()." e4");
						
						$totalServiceCost += $itemCost;
					}
					
					//update service cost
					$sql_serviceCost = mysql_query("update servicing set cost = '$totalServiceCost' where id = '$serviceID'")or die(mysql_error());
							
					if($sql_serviceCost){
						//get supply Notification enabled users
						$serviceUsers = $this->getServiceNotificationUsers();
						if($serviceUsers!=0){
							//get the name of the user that opened the ticket
							$userData = $this->getUserInfo($_SESSION['userid']);
							$user_name = $userData->name;
							
							//insert notification.
							while($serviceUser = mysql_fetch_object($serviceUsers)){
								$enabledUser = $serviceUser->id;
								mysql_query("insert into service_notification values('','$serviceID','$siteID','".$_SESSION['userid']."','$enabledUser','Service on Site $site_id by $user_name','no','0','Pending','$time')");
							}
						}		
						return '<div class="alert alert-success"><i class="fa fa-check"></i> Service Added Successfully</div>';
					}
				}
			}
		}
	}
	
	function addQAServicing($post, $process) {
		$this->connect_db(); 
		if(isset($process)) {

			$siteID    				= $this->mysql_prepare_value(trim($post['siteID']));			
			$serviceDate			= $this->mysql_prepare_value(trim($post['serviceDate']));
			$nextServiceDate		= $this->mysql_prepare_value(trim($post['nextServiceDate']));				
			$count					= $this->mysql_prepare_value(trim($post['count']));	
			$comment				= $this->mysql_prepare_value(trim($post['comment']));
			
			$runnhrs				= $post['runnhrs'];
			$nxtrunnhrs				= $post['nxtrunnhrs'];
			$sourceid				= $post['sourceid'];

			$time = time();
			$date_submitted = date("Y-m-d",time());
			
			$year = substr($serviceDate,0,4);
			$month = substr($serviceDate,5,2);
			$day = substr($serviceDate,8,9);
			
			switch($month) {
				case "01":
				$serviceMonth = "Jan";
				$orderMonth = '1';
				break;
				case "02":
				$serviceMonth = "Feb";
				$orderMonth = '2';
				break;
				case "03":
				$serviceMonth = "Mar";
				$orderMonth = '3';
				break;
				case "04":
				$serviceMonth = "Apr";
				$orderMonth = '4';
				break;
				case "05":
				$serviceMonth = "May";
				$orderMonth = '5';
				break;
				case "06":
				$serviceMonth = "Jun";
				$orderMonth = '6';
				break;
				case "07":
				$serviceMonth = "Jul";
				$orderMonth = '7';
				break;
				case "08":
				$serviceMonth = "Aug";
				$orderMonth = '8';
				break;
				case "09":
				$serviceMonth = "Sep";
				$orderMonth = '9';
				break;
				case "10":
				$serviceMonth = "Oct";
				$orderMonth = '10';
				break;
				case "11":
				$serviceMonth = "Nov";
				$orderMonth = '11';
				break;
				case "12":
				$serviceMonth = "Dec";
				$orderMonth = '12';
				break;
			}
			
			//update previous Service on this site, ie set it as Serviced
			$UpdatePreviousService = $this->updatePreviousSiteServicingStatusQA($siteID);
			if($UpdatePreviousService = 1) {

				$query_I = "insert into qa_servicing values('','$siteID','".$_SESSION['userid']."','$serviceDate','$nextServiceDate','0','$count','$serviceMonth','$year','$orderMonth','$comment','Not Viewed','0','$date_submitted','$time')";
				$result_I = mysql_query($query_I)or die(mysql_error()." e1");
				$serviceID = mysql_insert_id();
				
				if($result_I) {
					$counter = 0; //tracks each row that has been added
					foreach($runnhrs as $runningHour) {
						
						//insert supply details on tank on site.
						$query_I = "insert into qa_servicing_details values('','$siteID','$serviceID','".$sourceid[$counter]."','$runningHour','".$nxtrunnhrs[$counter]."','$count','$serviceMonth','$year','$orderMonth','$time')";
						$result_I = mysql_query($query_I)or die(mysql_error()." e2");
						
						//update Power source total ran hours and running hour track columns
						$sqlRunhours = "insert into qa_site_running_hours values('','".$sourceid[$counter]."','$runningHour','service','$serviceID','$time')";
						$resultRunhours = mysql_query($sqlRunhours)or die(mysql_error()." e3");
						
						$counter++;
					}
							
					if($resultRunhours){
						//get supply Notification enabled users
						$serviceUsers = $this->getServiceNotificationUsers();
						if($serviceUsers!=0){
							//get the name of the user that opened the ticket
							$userData = $this->getUserInfo($_SESSION['userid']);
							$user_name = $userData->name;
							
							//insert notification.
							while($serviceUser = mysql_fetch_object($serviceUsers)){
								$enabledUser = $serviceUser->id;
								mysql_query("insert into service_notification values('','$serviceID','$siteID','".$_SESSION['userid']."','$enabledUser','[QA] Service on Site $site_id by $user_name','no','0','$time')");
							}
						}		
						return '<div class="alert alert-success"><i class="fa fa-check"></i> Service Added Successfully</div>';
					}
				}
			}
		}
	}
	
	function invoiceCustomer($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
		
			$time = time();

			$cust_id   		= $this->mysql_prepare_value(trim($post['custID']));
			$startDate		= $this->mysql_prepare_value(trim($post['startDate']));
			$dueDate		= $this->mysql_prepare_value(trim($post['dueDate']));			
			$amount			= $this->mysql_prepare_value(trim($post['amount']));	
			$nextDate		= $this->mysql_prepare_value(trim($post['nextDate']));	

			//arrange date befor inserrting

			$query_I = "insert into invoice_customer values('','$cust_id','$startDate','$dueDate','$amount','Not Paid',0,'$nextDate','Not Invoiced','".$_SESSION['userid']."','$time')";
			$result_I = mysql_query($query_I)or die(mysql_error());
			
			if($result_I) {
			
				$query = "update site_tenants set invoice = 'Invoiced' where id='$cust_id'";
				$result = mysql_query($query)or die(mysql_error());
				if($result) {
					return '<div class="alert alert-success"><i class="fa fa-check"></i>Customer Invoiced</div>';
				}
			}
		}
	}
	
	function updateSupplyCost($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$sid   		= $this->mysql_prepare_value(trim($post['supplyID']));
			$nid   		= $this->mysql_prepare_value(trim($post['notifID']));
			$ucost		= $this->mysql_prepare_value(trim($post['unitcost']));	
			$cost		= $this->mysql_prepare_value(trim($post['cost']));	
			
			$time = time();

			//supply info
			$supplyData = $this->getSupplyInfo($sid);
			$siteid = $supplyData->site_id;
			$supply_date 	= date("Y-m-d",strtotime($supplyData->supply_date));
			
			//site info
			$siteData = $this->getSiteInfo($siteid);
			$s_ID = $siteData->site_id;

			$query = "update supplies set unit_cost = '$ucost', cost = '$cost' where id='$sid'";
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {
				//update notification notif_status to Done
				$queryI = "update supply_notification set work_order = 'Done' where supply_id='$sid'";
				$resultI = mysql_query($queryI)or die(mysql_error());
				
				if($resultI) {
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Diesel Cost Updated Successfully</div>';
				}
			}
		}
	}
	
	/*function updateServiceCost($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$sid   		= $this->mysql_prepare_value(trim($post['serviceID']));
			$nid   		= $this->mysql_prepare_value(trim($post['notifID']));
			$cost		= $this->mysql_prepare_value(trim($post['cost']));	
			
			$time = time();

			//supply info
			$serviceData = $this->getServiceInfo($sid);
			$siteid = $serviceData->site_id;
			$service_date 	= date("Y-m-d",strtotime($serviceData->service_date));
			
			//site info
			$siteData = $this->getSiteInfo($siteid);
			$s_ID = $siteData->site_id;

			$query = "update servicing set cost = '$cost' where id='$sid'";
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Service Cost Updated Successfully</div>';
			}
		}
	}*/
	
		function checkSiteCustomers($siteID){
			$query = "select * from site_tenants where state = 'Live' and site_id = '$siteID'";
			$result = mysql_query($query)or die(mysql_error());
			$countRows = mysql_num_rows($result);
			if($countRows>0) {
				return 1;
			}else {
				return 0;
			}
		}
		
		function checkForFirstLiveTenant($site_id) {
			$this->connect_db();
			$query = mysql_query("select site_id,first_live from site_tenants where site_id = '$site_id' and first_live = 'yes'");
			$countRow = mysql_num_rows($query);
			return $countRow;
		}
		
		function getFirstLiveTenant($site_id) {
			$this->connect_db();
			$query = mysql_query("select id,site_id,first_live from site_tenants where site_id = '$site_id' and first_live = 'yes'");
			$data = mysql_fetch_object($query);
			return $data->id;
		}
	
		function updateCustomerState($POST, $change) {

		$this->connect_db();
		if(isset($change)) {
			
			$custID			= $this->mysql_prepare_value($POST['custID']);
			$siteID			= $this->mysql_prepare_value($POST['siteID']);
			$state	   		= $this->mysql_prepare_value($POST['state']);
			$day	   		= $this->mysql_prepare_value($POST['day']);
			$month	   		= $this->mysql_prepare_value($POST['month']);
			$year	   		= $this->mysql_prepare_value($POST['year']);
			$time = time();
			
			//get site info
			$siteData = $this->getSiteInfo($siteID);
			$siteState = $siteData->status;
			
			//check if this tenant is the first live tenant
			$FirstLiveTenant = $this->checkForFirstLiveTenant($siteID);
					
			$query = "update site_tenants set state = '$state', last_update = '$time' ";
			if($state=="Live") {
				$liveDate = strtotime("$day $month $year");
				$query .=",live_date = '$liveDate' ";
			}
			$query .= ",first_live=";
			if($FirstLiveTenant==0) {
				$query .="'yes' ";
			}else {
				$query .="'no' ";
			}
			$query .= "where id='$custID'";
			$result = mysql_query($query)or die(mysql_error());
			
			
				
			if($result) {
				//check if the state of this Site is Not Live
				if($siteState!="Live"){
					//check if the state of this customer is live
					if($state=="Live") {
						//update site status to "live"
						$liveDate = strtotime("$day $month $year");
						$q = "update site set status = 'Live', live_date = '$liveDate', first_anni_date = '$liveDate' where id = '$siteID'";
						$r = mysql_query($q)or die(mysql_error());
						if($r) {
							return '<div class="alert alert-success">Customer State Updated.</div>
							<div class="alert alert-info">Site is now Live.</div>';
						}
						return '<div class="alert alert-success">Customer State Updated</div>';
					}elseif($state=="Decommissioned"){
						//update site status to "Decommissioned"
						$decomDate = strtotime("$day $month $year");
						$q = "update site_tenants set state = 'Decommissioned', decommissioned_date = '$decomDate' where id = '$custID'";
						$r = mysql_query($q)or die(mysql_error());
						if($r) {
							return '<div class="alert alert-info">Tenant Decommissioned. </div>';
						}
					}else {
						//check if any customer is live. if not change site status to not live
						$siteCustomersState = $this->checkSiteCustomers($siteID);
						if($siteCustomersState==0){
							//update site status to "not live"
							$q = "update site set status = 'Not Live', live_date = '0', first_anni_date = '0' where id = '$siteID'";
							$r = mysql_query($q)or die(mysql_error());
							if($r) {
								return '<div class="alert alert-success">Customer State Updated.</div>
								<div class="alert alert-info">Site Status is set to Not Live.</div>';
							}
						}else {
							//get first live tenant
							$firstLive = $this->getFirstLiveTenant($site_id);
							if($firstLive==$custID) {
								//update site live date
								$liveDate = strtotime("$day $month $year");
								$q = "update site set live_date = '$liveDate' where id = '$siteID'";
								$r = mysql_query($q)or die(mysql_error());
								if($r) {
									return '<div class="alert alert-success">Customer State Updated.</div>
									<div class="alert alert-info">Site Status is set to Not Live.</div>';
								}
							}
						}
					}
				}elseif($siteState=="Live") {
					if($state=="Decommissioned"){
						//update site status to "Decommissioned"
						$decomDate = strtotime("$day $month $year");
						$q = "update site_tenants set state = 'Decommissioned', decommissioned_date = '$decomDate' where id = '$custID'";
						$r = mysql_query($q)or die(mysql_error());
						if($r) {
							//check if there is still any tenant live on site, else change site status to 'Not Live'
								$siteCustomersState = $this->checkSiteCustomers($siteID);
								if($siteCustomersState==0){
								//update site status to "not live"
								$q1 = "update site set status = 'Not Live' where id = '$siteID'";
								$r1 = mysql_query($q1)or die(mysql_error());
								if($r1) {
									return '<div class="alert alert-success">Tenant Decommissioned.
									<div class="alert alert-info">This Site is now Not Live.</div>
									</div>';
								}
							}else {
							return '<div class="alert alert-info">Tenant Decommissioned.</div>';
							}
						}
					}else {
						//get first live tenant
						$firstLive = $this->getFirstLiveTenant($siteID);
						if($firstLive==$custID) {
							//update site live date
							$liveDate = strtotime("$day $month $year");
							$q = "update site set live_date = '$liveDate' where id = '$siteID'";
							$r = mysql_query($q)or die(mysql_error());
							if($r) {
								return '<div class="alert alert-success">Customer State Updated.</div>';
							}
						}
					}
				}
				
				return "<div class=\"alert alert-success\">Customer State Updated</div>";
			}
		}
	}
	
	function getall_tickets() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM tickets ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Ref</th>
                    <th>Site ID</th>
                    <th>Subject</th>
                    <th>Severity</th>
                    <th>Date Created</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$tRef 			= $ticket->ticket_ref;
				$sid 			= $ticket->site_id;
				$Subject 		= $ticket->ticket_subject;				
				$time	 		= date("d M, Y: h:ma",$ticket->time_created);
				$status 		= $ticket->status;
				$severity 		= $ticket->severity;
				
				//get site_ID
				$siteData = $this->getSiteInfo($sid );
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>#$tRef</td>
                        <td>$site_id ";
						if($indicator=="new ticket") {echo"<span class=\"badge bg-danger\">New</span>"; }
						echo"</td>
                        <td>$Subject</td>
                        <td><span class=\"label ";
									switch($severity) {
											case "Low Level":
											echo"label-info";
											break;
											case "Normal Level":
											echo"label-primary";
											break;
											case "High Level":
											echo"label-danger";
											break;
										}
									echo"\">$severity</span></td>
                        <td>$time</td>
                        <td><div class=\"label ";
						if($status=="1") { echo"label-success"; }else{ echo"label-danger"; }
						echo"\">";
						if($status=="1") { echo"Closed Ticket"; }else{ echo"Open Ticket"; }
						echo"</div></td>
                        <td>
							<a href=\"open_ticket.php?tid=$id \"><span class=\"add-on small-size\"> View</span></a> |
                            <a href=\"#\"><span class=\"add-on small-size\">Edit</span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';   
	   }
	}
	
	function getSitetickets($siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM tickets where site_id = '$siteID' ORDER BY time_created asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Subject</th>
                    <th>Date Created</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$sid 		= $ticket->site_id;
				$Subject 		= $ticket->ticket_subject;				
				$time	 		= date("d M, Y: H:m:i",$ticket->capacity);
				$status 		= $ticket->status;
				$indicator 		= $ticket->ticket_indicator;
				
				//get site_ID
				$siteData = $this->getSiteInfo($sid );
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id ";
						if($indicator=="new ticket") {echo"<span class=\"label label-danger\">New</span>"; }
						echo"</td>
                        <td>$Subject</td>
                        <td>$time</td>
                        <td><div class=\"badge ";
						if($status=="1") {echo"bg-green"; }else{echo"bg-red";}
						echo"\">";
						if($status=="1") {echo"Closed"; }else{echo"Open";}
						echo"</div></td>
                        <td>
							<a href=\"open_ticket.php?tid=$id \"><span class=\"add-on small-size\"> View</span></a> |
                            <a href=\"#\"><span class=\"add-on small-size\">Edit</span></a>
						</td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';   
	   }
	}
	
	function getallEngrTickets($engrID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM tickets where engr_id = '$engrID' ORDER BY time_created asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Ref</th>
                    <th>Site ID</th>
                    <th>Subject</th>
                    <th>Severity</th>
                    <th>Date Created</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$tRef 			= $ticket->ticket_ref;
				$sid 			= $ticket->site_id;
				$Subject 		= $ticket->ticket_subject;				
				$time	 		= date("d M, Y: H:m:ia",$ticket->capacity);
				$status 		= $ticket->status;
				$severity 		= $ticket->severity;
				
				//get site_ID
				$siteData = $this->getSiteInfo($sid );
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>#$tRef </td>
                        <td>$site_id</td>
                        <td>$Subject</td>
                        <td><span class=\"label ";
							switch($severity) {
									case "Low Level":
									echo"label-info";
									break;
									case "Normal Level":
									echo"label-primary";
									break;
									case "High Level":
									echo"label-danger";
									break;
								}
							echo"\">severity</span></td>
                        <td>$time</td>
                        <td><div class=\"label ";
						if($status=="1") {echo"label-success"; }else{echo"label-danger";}
						echo"\">";
						if($status=="1") {echo"Closed Ticket"; }else{echo"Open Ticket";}
						echo"</div></td>
                        <td><a href=\"open_ticket.php?tid=$id \">View</a></td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';   
	   }
	}
	
	function getEngrTickets($engrID,$siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM tickets where engr_id = '$engrID' and site_id = '$siteID' ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" id=\table1\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Severity Level</th>
                    <th>Subject</th>
                    <th>Date Created</th>
                    <th>Status</th>
                    <th width=\"20%\" scope=\"col\" colspan=\"2\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$sid 		= $ticket->site_id;
				$severity 		= $ticket->severity;				
				$Subject 		= $ticket->ticket_subject;				
				$time	 		= date("d M, Y: H:m:i",$ticket->capacity);
				$status 		= $ticket->status;
				
				//get site_ID
				$siteData = $this->getSiteInfo($sid );
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$severity</td>
                        <td>$Subject</td>
                        <td>$time</td>
                        <td><div class=\"badge ";
						if($status=="1") {echo"bg-green"; }else{echo"bg-red";}
						echo"\">";
						if($status=="1") {echo"Closed"; }else{echo"Open";}
						echo"</div></td>
                        <td><a href=\"open_ticket.php?tid=$id \">
					  <span class=\"add-on small-size\"> View</span></a></td>
                        <td><a href=\"#\">
					  <span class=\"add-on small-size\">Edit</span></a></td>
					  </tr>";
			}

			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';   
	   }
	}
	
	function getall_ticket_reply($tid) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM ticket_reply where ticket_id='$tid' ORDER BY time_created asc ";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->reply_id;
				$ticket_id 		= $ticket->ticket_id;				
				$user_id 		= $ticket->user_id;				
				$user_level 	= $ticket->user_level;				
				$reply_text 	= $ticket->reply_text;				
				$time1	 		= date("d-M-Y",$ticket->time_created);
				$time2	 		= date("D h:ma",$ticket->time_created);
				
				//get ticket status
				$ticketData = $this->getTicketInfo($ticket_id);
				$ticketStatus = $ticketData->status;
				
				echo"<div class=\time-bar\"></div>
				<div class=\"row\">
							<!--                                   col md 2-->
							<div class=\"col-md-2 col-md-offset-1\">
								<div class=\"timeline-date\">
									$time1,
									<br>$time2
								</div>
							</div>
							<!--                                    /col md 2-->
							<!--                                   col md 1-->
							<div class=\"col-md-1\">
								<div class=\"timeline-icon ";
									if($user_level=="Engineer") { 
											echo"flatRed";
										}elseif($user_level=="Supervisor") {
											echo"flatBlue";
										}
									echo"\">
									<i class=\"ti-comments\"></i>
								</div>
							</div>
							<!--                                    /col md 1-->
							<!--                                   col md 6-->
							<div class=\"col-md-6\">
								<div class=\"timeline-hover\">
									<div class=\"timeline-heading  ";
									if($user_level=="Engineer") { 
											echo"flatRed";
										}elseif($user_level=="Supervisor") {
											echo"flatBlue";
										}
									echo"\">
										<div class=\"timeline-arrow ";
										if($user_level=="Engineer") { 
											echo"arrow-red";
										}elseif($user_level=="Supervisor") {
											echo"arrow-blue";
										}
										
										echo"\"></div>";
										if($user_level=="Engineer") { 
											$engrData = $this->getUserInfo($user_id);
											echo $engrData->name;
										}elseif($user_level=="Supervisor") {
											$SuperData = $this->getSupervisorInfo($user_id);
											echo $SuperData->name;
										}
									echo"</div>
									<div class=\"timeline-content\">
										 $reply_text<br />";
											if($ticketStatus==0) {
											   if($_SESSION['userid']== $user_id && $_SESSION['level']== $user_level) {
												echo"<a href=\"".$_SEVER['PHP_SELF']."?tid=$ticket_id&reply=$id&ac=edit\"><button class=\"btn btn-orange btn-xs\">Edit</button></a> ";
												}
											   if($_SESSION['level']=="Supervisor") {
												echo"<a href=\"".$_SEVER['PHP_SELF']."?tid=$ticket_id&reply=$id&ac=del\" onclick=\"return confirm('Are you sure you want to Delete this?');\"><button class=\"btn btn-danger btn-xs\">Delete</button></a>";
												}
											}
									echo"</div>
								</div>
							</div>
							<!--col md 6-->
						</div>";
			 }
			 
			 }else{
			echo'<div class="alert alert-danger">No Comments on this ticket yet</div>';
	   }
	}
		
	function getEscComment($eid) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM downtime_comments where downt_id='$eid' ORDER BY time_created asc ";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			 $sn = 0;
			 $rand = rand();
			echo'<table class="table table-hover table-striped display">';
			while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->id;
				$escid 		= $ticket->downt_id;				
				$user_id 		= $ticket->userid;					
				$comment 	= $ticket->comments;				
				$time	 		= date("d-M-Y, H:ma",$ticket->time_created);	

				//get down time info
				$DownTimeData = $this->getDownTimeInfo($eid);
				$esc_status = $DownTimeData->escalation_status;
				
				//get down time info
				$UserData = $this->getUserInfo($user_id);
				$userName = $UserData->username;
				
				echo"<tr>
						<td><strong>$userName</strong></td>
						<td>$comment<br />[$time]";
						if($esc_status=="Open") {
						   if($_SESSION['userid']== $user_id) {
							echo"<a href=\"".$_SEVER['PHP_SELF']."?eid=$escid&ed=$rand\"><i class\"fa fa-edit\"></i> Edit</a> | 
								<a href=\"".$_SEVER['PHP_SELF']."?eid=$escid&del=$rand\" onclick=\"return confirm('Are you sure you want to Delete this?');\"><i class\"fa fa-trash\"></i> Delete</a>";
							}
						}
						echo"</td>
					</tr>";
			}			
				echo'</table>';
		}else{
			echo'<div class="alert alert-danger">No Comments on this Escalation</div>';
	    }
	}
	
	function getall_decommTenants() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM  site_tenants where state ='Decommissioned' ORDER BY last_update desc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th><input id=\"selectall\" type=\"checkbox\"></th>
                    <th>sn</th>
                    <th>Tenant</th>
                    <th>Site ID</th>
                    <th>RF</th>
                    <th>MW</th>
                    <th>criteria</th>
                    <th>Decommissioned Date</th>
                    <th width=\"20%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$customer_name	= $site->customer_name;
				$rf 			= $site->rf;
				$mw		 		= $site->mw;
				$criteria 		= $site->criteria;
				$decomDate   	= date("d M, Y",$site->decommissioned_date);
				
				$supvisorData = $this->getSiteInfo($siteID);
				$site = $supvisorData->site_id;
				
				echo"<tr>
                        <td><input name=\"decomID[]\" id=\"decomID[]\" value=\"$id\" type=\"checkbox\"></td>
                        <td>$sn</td>
                        <td>$customer_name</td>
                        <td>$site </td>
                        <td>$rf</td>
                        <td>$mw</td>
                        <td>$criteria</td>
                        <td>$decomDate</td>
                        <td><a href=\"".$_SERVER['PHP_SELF']."?ac=decom&cid=$id#decommTenant\" onclick=\"return confirm('Are you sure you want to Active this Tenant?');\">
					  <span class=\"add-on small-size\"> Active</span></a></td>
                     </tr>";
			 }
			
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Tenant Decommissioned Yet</div>';   
	   }
	}
	
	function getall_site4maintenance($type) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site where status = 'Live' ORDER BY id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site No</th>
                    <th>State</th>
                    <th>Height</th>
                    <th>Land Type</th>
                    <th>Location</th>
                    <th>Supervisor</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor;
				$land_acq_type 	= $site->land_acq_type;
				$location_type  = $site->location_type ;
				$status 		= $site->status;
				
				$supvisorData = $this->getSupervisorInfo($supervisor);
				$supvisorName = $supvisorData->name;
				
				$a = $this->getSupplyDateDiff($id);
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$bct_id </td>
                        <td>$site_no</td>
                        <td>$state</td>
                        <td>$tower_height</td>
                        <td>$land_acq_type</td>
                        <td>$location_type </td>
                        <td>$supvisorName</td>
                        <td>$status</td>
                        <td>";
                            if($type=="supply") {
								echo"<a href=\"view_supply.php?siteID=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-folder-o\"></i> view</span></a>";
							}else{
								echo"<a href=\"view_service.php?siteID=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-folder-o\"></i> view</span></a>";
							}
						echo"</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Site Yet</div>';   
	   }
	}
	
	function ServiceCostByGeo($geoZone) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site where region = '$geoZone' and status = 'Live' ORDER BY site_id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site No</th>
                    <th>State</th>
                    <th>Height</th>
                    <th>Location</th>
                    <th>Total Service Cost</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor;
				$location_type  = $site->location_type ;
				$status 		= $site->status;
				
				$siteServiceCost = $this->SiteTotalServiceCost($id);
				$serviceAmount = $siteServiceCost->amount;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$bct_id </td>
                        <td>$site_no</td>
                        <td>$state</td>
                        <td>$tower_height</td>
                        <td>$location_type </td>
                        <td>N".number_format($serviceAmount,2)."</td>
                        <td><a href=\"site-service-cost.php?siteID=$id\"  data-toggle=\"modal\" data-target=\"#serviceCost\"><span class=\"add-on small-size\"><i class=\"fa fa-folder-o\"></i> view</span></a></td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Service in this zone Yet</div>';   
	   }
	}
	
	function ServiceCostBySite($siteID) {	
		$this->connect_db();
		
		$sql = "select id,site_id,cost,engr_id,service_date from servicing where site_id = '$siteID'";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Service Date</th>
                    <th>FSE</th>
                    <th>Total Amount</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$cost	 		= $site->cost;
				$engr_id	  	= $site->engr_id;
				$service_date	= $site->service_date ;
				//get engr that made the supply
				$UserData = $this->getUserInfo($engr_id);
				$engr = $UserData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$service_date</td>
                        <td>$engr</td>
                        <td>N".number_format($cost,2)."</td>
                       </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Service on Site</div>';   
	   }
	}
	
	function SiteTotalServiceCost($siteID) {
		$this->connect_db();
		
		$sql = "select sum(cost) as amount, site_id from servicing where site_id = '$siteID'";
		$result = mysql_query($sql)or die(mysql_error());
		$data = mysql_fetch_object($result);
		
		return $data;
	}
	
	function DieselCostByGeo($geoZone) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site where region = '$geoZone' and status = 'Live' ORDER BY site_id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site No</th>
                    <th>State</th>
                    <th>Height</th>
                    <th>Location</th>
                    <th>Total Diesel Cost</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor;
				$location_type  = $site->location_type ;
				$status 		= $site->status;
				
				$siteSupplyCost = $this->SiteTotalDieslCost($id);
				$supplyAmount = $siteSupplyCost->amount;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$bct_id </td>
                        <td>$site_no</td>
                        <td>$state</td>
                        <td>$tower_height</td>
                        <td>$location_type </td>
                        <td>N".number_format($supplyAmount,2)."</td>
                        <td><a href=\"site-supply-cost.php?siteID=$id\"  data-toggle=\"modal\" data-target=\"#supplyCost\"><span class=\"add-on small-size\"><i class=\"fa fa-folder-o\"></i> view</span></a></td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Supply in this zone Yet</div>';   
	   }
	}
	
	function DieselCostBySite($siteID) {	
		$this->connect_db();
		
		$sql = "select id,site_id,cost,engr_id,supply_date,cpd,unit_cost from supplies where site_id = '$siteID'";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Supply Date</th>
                    <th>FSE</th>
                    <th>CPD</th>
                    <th>Unit Cost</th>
                    <th>Total Supplied</th>
                    <th>Total Amount</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$cost	 		= $site->cost;
				$engr_id	  	= $site->engr_id;
				$supply_date	= $site->supply_date ;
				$cpd	 		= $site->cpd;
				$unit_cost 		= $site->unit_cost;
				//get engr that made the supply
				$UserData = $this->getUserInfo($engr_id);
				$engr = $UserData->name;
				//get the total diesel supplied on site
				$siteTotalSupply  = $this->SiteSupplied($id,$siteID);
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$supply_date</td>
                        <td>$engr</td>
                        <td>$cpd</td>
                        <td>N".number_format($unit_cost,2)."</td>
                        <td>$siteTotalSupply</td>
                        <td>N".number_format($cost,2)."</td>
                       </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Supply on Site</div>';   
	   }
	}
	
	function SiteTotalDieslCost($siteID) {
		$this->connect_db();
		
		$sql = "select sum(cost) as amount, site_id from  supplies where site_id = '$siteID'";
		$result = mysql_query($sql)or die(mysql_error());
		$data = mysql_fetch_object($result);
		
		return $data;
	}
	
	function countSiteTenants($siteID) {
		$this->connect_db();
		
		$query = mysql_query("select * from site_tenants where site_id = '$siteID'")or die(mysql_error());
		$countRows = mysql_num_rows($query);
		
		return $countRows;
	}
	
	function getSitePowerConsumption($siteID) {
		$this->connect_db();
		
		$query = mysql_query("select * from site_tenants where site_id = '$siteID'")or die(mysql_error());
		$countRows = mysql_num_rows($query);
		
		if($countRows>0) {	
			$powerSum = 0;
			while($sTenants = mysql_fetch_object($query)) {
				$customer_id = $sTenants->customer_id;		
				$customerData = $this->getCustomerInfo($customer_id);
				$ctype_id = $customerData->ctype_id;
				$ctypeData = $this->getCustomerTypeInfo($ctype_id);
				$kilowatts = $ctypeData->kilowatts;
				
				$powerSum += $kilowatts;
			}			
			return $powerSum;
		}else{
			return "Nil";
		}
	}
	
	function getSiteRevenue($siteID) {
		$this->connect_db();		
		$query = mysql_query("select sum(amount) as revenue from site_tenants where site_id = '$siteID'")or die(mysql_error());
		$site = mysql_fetch_object($query)or die(mysql_error());
		$revenue = $site->revenue;
		
		return $revenue;
	}
	
	function getSiteMainatenanceCost($siteID,$month,$year) {
		$this->connect_db();		
		$query = mysql_query("select sum(cost) as mtce from servicing where site_id = '$siteID' and month = '$month' and year='$year'")or die(mysql_error());
		$site = mysql_fetch_object($query)or die(mysql_error());
		$mtce = $site->mtce;
		
		return $mtce;
	}
	
	function getSiteDieselCost($siteID,$month,$year) {
		$this->connect_db();		
		$query = mysql_query("select sum(cost) as diesel_cost from supplies where site_id = '$siteID' and month = '$month' and year='$year'")or die(mysql_error());
		$site = mysql_fetch_object($query)or die(mysql_error());
		$diesel_cost = $site->diesel_cost;
		
		return $diesel_cost;
	}
	
	function getall_site() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site ORDER BY id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>State</th>
                    <th>Height</th>
                    <th>Land</th>
                    <th>Location</th>
                    <th>Tenants</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$address 		= $site->address;
				$supervisor  	= $site->supervisor;
				$land_acq_type 	= $site->land_acq_type;
				$location_type  = $site->location_type ;
				$status 		= $site->status;
				
				
				$a = $this->getSupplyDateDiff($id);
				
				$tenants = $this->countSiteTenants($id);
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"siteinfo.php?sid=$id\"  title=\"Quick details\" data-toggle=\"modal\" data-target=\"#viewSiteModal\">$siteID</a></td>
                        <td>$bct_id </td>
                        <td>$state</td>
                        <td>$tower_height</td>
                        <td >$land_acq_type</td>
                        <td>$location_type</td>
                        <td>$tenants</td>
                        <td><span class=\"label ";
						if($status=="Live"){echo "label-success";}else{echo "label-danger";}
						echo"\">";
						if($status=="Live"){echo "Live Site";}else{echo $status;}
						echo"</span></td>
                        <td>
                            <a href=\"view_site.php?siteID=$id\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"View Details\"><span class=\"add-on small-size\"><i class=\"fa fa-folder\"></i></span></a>&nbsp;&nbsp;
                            <a href=\"s_tenants.php?siteID=$id\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Tenants\"><span class=\"add-on small-size\"><i class=\"fa fa-signal\"></i></span></a>&nbsp;&nbsp;
                            <a href=\"site_map.php?sid=$id\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"View Map\" target=\"_blank\" title=\"Find site on Map\"><span class=\"add-on small-size\"><i class=\"fa fa-map-marker\"></i></span></a>&nbsp;&nbsp;
							<a href=\"delete_site.php?sid=$id\"  title=\"Delete Site\" data-toggle=\"modal\" data-target=\"#delSiteModal\"><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 Site Yet</div>';   
	   }
	}
	
	function siteAsset() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site ORDER BY id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site No</th>
                    <th>State</th>
                    <th>Height</th>
                    <th>Land Type</th>
                    <th>Location</th>
                    <th>Supervisor</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor;
				$land_acq_type 	= $site->land_acq_type;
				$location_type  = $site->location_type ;
				$status 		= $site->status;
				
				$supvisorData = $this->getSupervisorInfo($supervisor);
				$supvisorName = $supvisorData->name;
				
				$a = $this->getSupplyDateDiff($id);
				
				echo"<tr class=\"";
						if($status=="Live") {echo"success"; }else{echo"danger";}
						echo"\">
                        <td style=\"color:#000\">$sn</td>
                        <td style=\"color:#000\">$siteID</td>
                        <td style=\"color:#000\">$bct_id </td>
                        <td style=\"color:#000\">$site_no</td>
                        <td style=\"color:#000\">$state</td>
                        <td style=\"color:#000\">$tower_height</td>
                        <td style=\"color:#000\">$land_acq_type</td>
                        <td style=\"color:#000\">$location_type </td>
                        <td style=\"color:#000\">$supvisorName</td>
                        <td style=\"color:#000\">$status</td>
                        <td style=\"color:#000\">
                            <a href=\"view_site.php?siteID=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-folder-o\"></i> Details</span></a>&nbsp;&nbsp;
							<a href=\"site_map.php?sid=$id\" target=\"_blank\" title=\"Find site on Map\"><span class=\"add-on small-size\"><i class=\"fa fa-map-marker\"></i> Map</span></a>
						</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Site Yet</div>';   
	   }
	}
	
	function siteAssetNOC() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site where status = 'Live' ORDER BY id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site No</th>
                    <th>State</th>
                    <th>Height</th>
                    <th>Land Type</th>
                    <th>Location</th>
                    <th>Supervisor</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor;
				$land_acq_type 	= $site->land_acq_type;
				$location_type  = $site->location_type ;
				$status 		= $site->status;
				
				$supvisorData = $this->getSupervisorInfo($supervisor);
				$supvisorName = $supvisorData->name;
				
				$a = $this->getSupplyDateDiff($id);
				
				echo"<tr class=\"";
						if($status=="Live") {echo"success"; }else{echo"danger";}
						echo"\">
                        <td style=\"color:#000\">$sn</td>
                        <td style=\"color:#000\">$siteID</td>
                        <td style=\"color:#000\">$bct_id </td>
                        <td style=\"color:#000\">$site_no</td>
                        <td style=\"color:#000\">$state</td>
                        <td style=\"color:#000\">$tower_height</td>
                        <td style=\"color:#000\">$land_acq_type</td>
                        <td style=\"color:#000\">$location_type </td>
                        <td style=\"color:#000\">$supvisorName</td>
                        <td style=\"color:#000\">$status</td>
                        <td style=\"color:#000\">
                            <a href=\"view_site.php?siteID=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-folder-o\"></i> Details</span></a>&nbsp;&nbsp;
							<a href=\"site_map.php?sid=$id\" target=\"_blank\" title=\"Find site on Map\"><span class=\"add-on small-size\"><i class=\"fa fa-map-marker\"></i> Map</span></a>
						</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Site Yet</div>';   
	   }
	}
	
	function getAssignedSites($type) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_users where user_id='".$_SESSION['userid']."'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>BCT ID</th>
                    <th>State</th>
                    <th>Site No</th>
                    <th>Tower Height</th>
                    <th>Location Type</th>
                    <th>Supervisor</th>
                    <th>Status</th>
                    <th width=\"16%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($engrSite = mysql_fetch_object($result)) {
				
				$site = $this->getSiteInfo($engrSite->site_id);
				
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor;
				$location_type 	= $site->location_type;
				$tankMode	  	= $site->tankMode;
				$status 		= $site->status;
				
				$supvisorData = $this->getSupervisorInfo($supervisor);
				$supvisorName = $supvisorData->name;
				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$bct_id</td>
                        <td>$state</td>
                        <td>$site_no</td>
                        <td>$tower_height Meters</td>
                        <td>$location_type</td>
                        <td>$supvisorName</td>
                        <td>$status</td>
						<td><a href=\"site_map.php?sid=$id\" target=\"_blank\" title=\"Find site on Map\"><span class=\"add-on small-size\"><i class=\"fa fa-map-marker\"></i> Map</span></a>&nbsp;&nbsp;
						";
						if($status=="Live") {
							if($type=="supply") {
								echo"<a href=\"supply.php?siteID=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-table\"></i> Report</span></a>";
							}elseif($type=="service"){
								echo"<a href=\"servicing.php?siteID=$id \"><span class=\"add-on small-size\"><i class=\"fa fa-table\"></i> Report</span></a>";
							}elseif($type=="week"){
								echo"<a href=\"";
								if($_SESSION['level']=='Engineer'){echo"weekreport.php";}elseif($_SESSION['level']=='QA'){echo"qa_weekreport.php";}
								echo"?siteID=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-table\"></i> Report</span></a>";
							}elseif($type=="ticket"){
								echo"<a href=\"tickets.php?sid=$id \"><span class=\"add-on small-size\"><i class=\"fa fa-ticket\"></i> Open Ticket</span></a>";						
							}
						}
						echo"</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Site For Enger</div>';   
	   }
	}
	
	function getQAServiceReportSites() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_users where user_id='".$_SESSION['userid']."'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>BCT ID</th>
                    <th>State</th>
                    <th>Site No</th>
                    <th>Tower Height</th>
                    <th>Location Type</th>
                    <th>Report</th>
                    <th>Status</th>
                    <th width=\"16%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($engrSite = mysql_fetch_object($result)) {
				
				$site = $this->getSiteInfo($engrSite->site_id);
				
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$tower_height	= $site->tower_height;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor;
				$location_type 	= $site->location_type;
				$tankMode	  	= $site->tankMode;
				$status 		= $site->status;
				
				$CountPendingReports = $this->SitePendingSeriveReport($id);				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$bct_id</td>
                        <td>$state</td>
                        <td>$site_no</td>
                        <td>$tower_height Meters</td>
                        <td>$location_type</td>
                        <td><span class=\"label label-";
						if($CountPendingReports>0){echo"danger";}else{echo"success";}
						echo"\">$CountPendingReports Pending</span></td>
                        <td>$status</td>
						<td><a href=\"site_map.php?sid=$id\" target=\"_blank\" title=\"Find site on Map\"><span class=\"add-on small-size\"><i class=\"fa fa-map-marker\"></i> Map</span></a>&nbsp;&nbsp;
						";
						if($status=="Live") {
							echo"<a href=\"servicing.php?siteID=$id \"><span class=\"add-on small-size\"><i class=\"fa fa-table\"></i> Report</span></a>";
						}
						echo"</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Site For Enger</div>';   
	   }
	}
	
	function getEngrSupplyBatchSites($batchID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supply_batch_site where batch_id = '$batchID' ORDER BY id Desc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>State</th>
                    <th>Site No</th>
                    <th>Tower Height</th>
                    <th>Location Type</th>
                    <th>Supervisor</th>
                    <th>Status</th>
                    <th width=\"16%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($batch = mysql_fetch_object($result)) {
				$sn += 1;
								
				$id 		= $batch->id;
				$batchID	= $batch->batch_id;
				$site_id	= $batch->site_id;
				$userid 	= $batch->userid;
				
				$siteInfo = $this->getSiteInfo($site_id);
				
				$siteID 		= $siteInfo->site_id;
				$state 			= $siteInfo->state;
				$tower_height	= $siteInfo->tower_height;
				$site_no 		= $siteInfo->site_no;
				$supervisor  	= $siteInfo->supervisor;
				$location_type 	= $siteInfo->location_type;
				$siteStatus		= $siteInfo->status;
				
				$supvisorData = $this->getSupervisorInfo($supervisor);
				$supvisorName = $supvisorData->name;
				
				//chek if site is assigned to engr and display.
				$checkengrSite = $this->checkEngrSite($site_id,$_SESSION['userid']);
				
				if($checkengrSite==1) {
				
					echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$state</td>
                        <td>$site_no</td>
                        <td>$tower_height Meters</td>
                        <td>$location_type</td>
                        <td>$supvisorName</td>
                        <td>$siteStatus</td>
						<td><a href=\"site_map.php?sid=$id\" target=\"_blank\" title=\"Find site on Map\"><span class=\"add-on small-size\"><i class=\"fa fa-map-marker\"></i> Map</span></a>&nbsp;&nbsp;
						";
						if($siteStatus=="Live") {
								echo"<a href=\"";
								if($_SESSION['level']=='Engineer'){echo"supply.php";}elseif($_SESSION['level']=='QA'){echo"site-supplies.php";}
								echo"?sbid=$id&siteID=$site_id\"><span class=\"add-on small-size\"><i class=\"fa fa-table\"></i> Report</span></a>";
						}
						echo"</td>
                     </tr>";
				}
			 }
			 
			// print the navigation link
			echo"</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Site For Enger</div>';   
	   }
	}
	
	function SiteSupplyReport($level) {	
		$date = date("Y-m-d",time());
		$this->connect_db();	
		
		$sql = "SELECT  * FROM supplies where date_submitted = '$date' ORDER BY site_id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		  
	    if($num_rows > 0){
	   
			//generate excel File
				$excelFile = $this->generateExcel($sql,"supply");
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Reports
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
				
			echo"<table id=\"example\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Site ID</th>
						<th>Site Engr.</th>
						<th>Supply Date</th>
						<th>Initial Stock</th>
						<th>Qty Supplied</th>
						<th>Total Stock</th>
						<th>Next Supply</th>
						<th>Time submitted</th>
						<th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $supply->id;
				$siteID 		= $supply->site_id;
				$engrID 		= $supply->engr_id;
				$supply_date	= $supply->supply_date;
				$initial_stock	 = $supply->initial_stock;
				$order_qty	 	= $supply->order_qty;
				$next_date 		= $supply->next_supply_date;
				$cpd 			= $supply->cpd;
				$submitted		= date("Y-m-d, h:i:s a",$supply->time_created);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$state = $siteData->state;
				
				
				//get site engr name
				$EngrData = $this->getUserInfo($engrID);
				$EngrName = $EngrData->name;		
				
				//get total current stock
				$supplyData = $this->getSupplyDetails($id,$siteID);
				$initialStock = $supplyData->stock;
				$suppliedQty = $supplyData->qty;
				$totalStock = $supplyData->total;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$EngrName</td>
                        <td>$supply_date</td>
                        <td>$initialStock</td>
                        <td>$suppliedQty</td>
                        <td>$totalStock</td>
                        <td>$next_date</td>
                        <td>$submitted</td>
                        <td>
						<a href=\"";
						if($searchQA=="yes"){ echo "opensupplyreportqa.php"; }else{ echo "opensupplyreport.php"; }
						echo"?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\" title=\"View all Details\">View Details</a> |
						<a href=\"#\" title=\"Delete Report\">Delete</a> 
						</td>
                     </tr>";
			 }
			echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No Supplies Report for selected Date</div>";   
	   }
	}
	
	function SiteWeekReport() {	
		$date = date("Y-m-d",time());
		$this->connect_db();	
		
		$sql = "SELECT  * FROM weekly_report where date_submitted = '$date' ORDER BY site_id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		  
	   if($num_rows > 0){
	   
	   //generate excel File
				$excelFile = $this->generateExcel($sql,"weekreport");
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Today's Report ( $date )
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
			echo"<table border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Report Date</th>
                    <th>Engr</th>
                    <th>Comment</th>
                    <th>Date Submitted</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $week->id;
				$siteID 		= $week->site_id;
				$engrID 		= $week->engr_id;
				$report_date 	= date("Y-m-d",strtotime($week->report_date));
				$comment 		= $this->limit_words($week->comment,10);
				$posted 		= date("Y-M-d h:ma",$week->time_created);
				
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				$userData = $this->getUserInfo($engrID);
				$EngrName = $userData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$report_date</td>
                        <td>$EngrName</td>
                        <td>$comment...</td>
                        <td>$posted</td>
                        <td>";
						if($_SESSION['level']!="Supervisor") {
							echo "N/A";
						}else{
							echo"<a href=\"openweekreport.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\"><span class=\"add-on small-size\"> View Details</span></a> | 
							<a href=\"".$_SERVER['PHP_SELF']."?rid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			 

			// print the navigation link
			echo "</tbody></table>";
				echo"<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"sendEmail\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Weekly Report Submitted for today Yet '.$date.'</div>';   
	   }
	}
	
	function SiteSupplyReportDate($dateString) {
		$this->connect_db();	
		
		if(strlen($dateString)>10) {
			$from = strtotime(substr($dateString,0,10));
			$to   = strtotime(substr($dateString,13,10));
			
			$fromDate = date("Y-m-d",$from);
			$toDate = date("Y-m-d",$to);
						
			$sql = "SELECT * FROM supplies where approve_status = 'Approved' and date_submitted between '$fromDate' and '$toDate' ORDER BY site_id asc";
		}else {
			$date = strtotime($dateString);
			$formatDate = date("Y-m-d",$date);
			$sql = "SELECT  * FROM supplies where approve_status = 'Approved' and date_submitted = '$formatDate' ORDER BY site_id asc";
		}
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		
		   
	   if($num_rows > 0){
	   
			//generate excel File
			$excelFile = $this->generateExcel($sql,"supply");
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Reports
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
				
			echo"<table id=\"example\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Site ID</th>
						<th>Site Engr.</th>
						<th>Supply Date</th>
						<th>Initial</th>
						<th>Supplied</th>
						<th>Total Stock</th>
						<th>Next Supply</th>
						<th>Time submitted</th>
						<th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $supply->id;
				$siteID 		= $supply->site_id;
				$engrID 		= $supply->engr_id;
				$supply_date	= $supply->supply_date;
				$initial_stock	=$supply->initial_stock;
				$order_qty	 	= $supply->order_qty;
				$next_date 		= $supply->next_supply_date;
				$cpd 			= $supply->cpd;
				$submitted		= date("Y-m-d, h:i:s a",$supply->time_created);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$state = $siteData->state;
				
				
				//get site engr name
				$EngrData = $this->getUserInfo($engrID);
				$EngrName = $EngrData->name;		
				 
				$supplyData = $this->getSupplyDetails($id,$siteID);
				$initialStock = $supplyData->stock;
				$suppliedQty = $supplyData->qty;
				$totalStock = $supplyData->total;
				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$EngrName</td>
                        <td>$supply_date</td>
                        <td>$initialStock</td>
                        <td>$suppliedQty</td>
                        <td>$totalStock</td>
                        <td>$next_date</td>
                        <td>$submitted</td>
                        <td>
						<a href=\"opensupplyreport.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\" title=\"View all Details\">View Details</a> |
						<a href=\"#\" title=\"Delete Report\">Delete</a> 
						</td>
                     </tr>";
			 }
			echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No Supplies Report for selected Date</div>";   
	   }
	}
	
	function SiteExpenseReportDate($dateString, $mode=null, $level) {
		
		
			$from = strtotime(substr($dateString,0,10));
			$to   = strtotime(substr($dateString,13,10));
			$fromDate = date("Y-m-d",$from);
			$toDate = date("Y-m-d",$to);
		
		$this->connect_db();	
		
		if($mode=="single"){
			$date = trim($dateString);
			$sql = "SELECT  * FROM expenses where ex_date = '$date' ORDER BY expense_id desc";
		}else{
			$sql = "SELECT  * FROM expenses where ex_date between '$fromDate' and '$toDate' ORDER BY expense_id desc";
		}
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		
		   
	   if($num_rows > 0){
	   
			//generate excel File
				$excelFile = $this->generateExcel($sql,"expenses");
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Expenses Reports - <small>$num_rows Expense(s) Found
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
				
			echo"<table id=\"example\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Site ID</th>
						<th>Date</th>
						<th>Amount</th>
						<th>Description</th>
						<th>Issued to</th>
						<th>Added by</th>
						<th>Time Added</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amount = 0;
			 while($expenses = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $expenses->expense_id;
				$siteID 		= $expenses->site_id;
				$exDate			= date("Y-m-d",strtotime($expenses->ex_date));
				$exDesc			= $expenses->ex_desc;
				$amount	 		= $expenses->ex_amount;
				$issuedTo 		= $expenses->issued_to;
				$submitted		= date("Y-m-d, h:i:s a",$expenses->time_created);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;		
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$exDate</td>
                        <td>₦".number_format($amount,2)."</td>
                        <td>$exDesc</td>
                        <td>$issuedTo</td>
                        <td></td>
                        <td>$submitted</td>
                     </tr>";
					 
					 $total_amount +=$amount;
			 }
			echo"<tr>
				<td colspan=\"3\" align=\"right\"><strong>Total</strong></td>
				<td><strong>₦".number_format($total_amount,2)."</strong></td>
				<td colspan=\"4\"></td>
			</tr>
			</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No Expenses Report for selected Date</div>";   
	   }
	}
	
	function InvoiceDueTodayReport() {	
		$date = date("Y-m-d",time());
		$this->connect_db();	
		
		$sql = "SELECT  * FROM  invoice_customer where due_date  = '$date' and payment_status = 'Not Paid' ORDER BY customer_id  asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		  
	   if($num_rows > 0){
	   
	   //generate excel File
				$excelFile = $this->generateExcel($sql,"invoice");
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Today's Report ( $date )
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
			echo"
				<table id=\"example\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Customer</th>
						<th>Site ID</th>
						<th>Invoice Date</th>
						<th>Due Date</th>
						<th>Amount</th>
						<th>Status</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($invoice = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $invoice->id;
				$customer_id 	= $invoice->customer_id;
				$invoice_date	= $invoice->invoice_date;
				$due_date	 	= $invoice->due_date;
				$amount 		= number_format($invoice->amount ,2);
				$status	 		= $invoice->payment_status;
				
				//get site engrid
				$CustomerData = $this->getCustomerInfo($customer_id);
				$siteID = $CustomerData->site_id;
				$customerName = $CustomerData->customer_name;
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customerName</td>
                        <td>$site_id</td>
                        <td>$invoice_date</td>
                        <td>$due_date</td>
                        <td>₦$amount</td>
                        <td>$status</td>
                     </tr>";
			 }
			 

			// print the navigation link
			echo "</tbody></table>";
				echo"<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"sendEmail\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Invoice(s) Due for Payment Today</div>';   
	   }
	}
	
	function InvoiceDueReportbyDate($dateString) {
		
		$from = strtotime(substr($dateString,0,10));
		$to   = strtotime(substr($dateString,13,10));
		
		$fromDate = date("Y-m-d",$from);
		$toDate = date("Y-m-d",$to);
		
		
		$this->connect_db();	
		
		
		$sql = "SELECT  * FROM  invoice_customer where due_date between '$fromDate' and '$toDate' ORDER BY due_date  asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		
		   
	   if($num_rows > 0){
	   
			//generate excel File
				$excelFile = $this->generateExcel($sql,"invoice");
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Report
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
				
			echo"<table id=\"example\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Customer</th>
						<th>Site ID</th>
						<th>Invoice Date</th>
						<th>Due Date</th>
						<th>Amount</th>
						<th>Status</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($invoice = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $invoice->id;
				$customer_id 	= $invoice->customer_id;
				$invoice_date	= $invoice->invoice_date;
				$due_date	 	= $invoice->due_date;
				$amount 		= number_format($invoice->amount ,2);
				$status	 		= $invoice->payment_status;
				
				//get site engrid
				$CustomerData = $this->getCustomerInfo($customer_id);
				$siteID = $CustomerData->site_id;
				$customerName = $CustomerData->customer_name;
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customerName</td>
                        <td>$site_id</td>
                        <td>$invoice_date</td>
                        <td>$due_date</td>
                        <td>₦$amount</td>
                        <td>$status</td>
                     </tr>";
			 }
			echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No Invoice Due for Payment Between $fromDate and $toDate</div>";   
	   }
	}
	
	function ITPReportbyDate($dateString) {
		
		$this->connect_db();	
		
	
		$date = strtotime($dateString);
		$formatDate = date("Y-m-d",$date);
		$sql = "SELECT  * FROM  itp where anniversary = '$formatDate' ORDER BY anniversary  asc";

				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		
		   
	   if($num_rows > 0){
	   
			//generate excel File
				$excelFile = $this->generateExcel($sql,"itp");
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Report
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
				
			echo"<table id=\"example\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Client</th>
						<th>Site ID</th>
						<th>Anniversary</th>
						<th>commercial_terms</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($itp = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $itp->id;
				$client			= $itp->client;
				$siteID		 	= $itp->site_id;
				$commTerms	 	= $itp->commercial_terms;
				$anniversary 	= date("d-M-Y",strtotime($itp->anniversary));
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$client</td>
                        <td>$site_id</td>
                        <td>$anniversary</td>
                        <td>$commTerms</td>
                     </tr>";
			 }
			echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No ITP Record for selected date</div>";   
	   }
	}
	
	function SiteWeekReportDate($dateString,$searchQA="no") {
		
		$this->connect_db();	
		
		//report table to search from
		if($searchQA=="yes"){ $week = "qa_weekly_report"; }else{ $week = "weekly_report"; }
		
		if(strlen($dateString)>10) {
			$from = strtotime(substr($dateString,0,10));
			$to   = strtotime(substr($dateString,13,10));
			
			$fromDate = date("Y-m-d",$from);
			$toDate = date("Y-m-d",$to);
			
			$sql = "SELECT  * FROM $week where date_submitted between '$fromDate' and '$toDate' ORDER BY site_id asc";
		}else {
			$date = strtotime($dateString);
			$formatDate = date("Y-m-d",$date);
			$sql = "SELECT  * FROM $week where date_submitted = '$formatDate' ORDER BY site_id asc";
		}			
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				   
	   if($num_rows > 0){
	   
			//generate excel File
			if($searchQA=="yes"){ $excelFile = $this->generateExcelQA($sql,"weekreport"); }else{ $excelFile = $this->generateExcel($sql,"weekreport"); }
			
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							report
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
				
			echo"<table id=\"example\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Report Date</th>
                    <th>Site ID</th>
                    <th>Engr</th>
                    <th>Comment</th>
                    <th>Date Submitted</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $week->id;
				$siteID 		= $week->site_id;
				$engrID 		= $week->engr_id;
				$report_date 	= date("Y-m-d",strtotime($week->report_date));
				$comment 		= $this->limit_words($week->comment,10);
				$posted 		= date("Y-M-d h:ma",$week->time_created);
				
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				$userData = $this->getUserInfo($engrID);
				$EngrName = $userData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$report_date</td>
                        <td>$site_id</td>
                        <td>$EngrName</td>
                        <td width=\"30%\">$comment...</td>
                        <td>$posted</td>
                        <td>
						<a href=\"";
						if($searchQA=="yes"){ echo"openweekreportqa.php"; }else{ echo"openweekreport.php"; }
						
						echo"?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\"><span class=\"add-on small-size\"> View Details</span></a>"; 
						if($_SESSION['level']=="Supervisor") {
						echo"| <a href=\"".$_SERVER['PHP_SELF']."?sid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No Site Weekly Report for this Date Range ($fromDate to $toDate)</div>";   
	   }
	}
	
	function DieselMetricsExcel($states,$leadQty,$bufferQty) {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = $creator.$time.'.xlsx';
		
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()->setCreator($creator)
					->setLastModifiedBy($creator)
					->setTitle("Diesel Reorder Metrics ".$creator)
					->setSubject("Diesel Reorder Metrics")
					->setDescription("Diesel Reorder Metrics")
					->setKeywords("Diesel Reorder Metrics")
					->setCategory("Diesel Reorder Metrics");
		$objPHPExcel->getActiveSheet()->setTitle('sheet1');

		$objPHPExcel->setActiveSheetIndex(0)
				->setCellValue('A1', 'S/N')
				->setCellValue('B1', 'SITE ID')
				->setCellValue('C1', 'REPORT DATE')
				->setCellValue('D1', 'CURR. Tank 1 LEVEL')
				->setCellValue('E1', 'CURR. Tank 2 LEVEL')
				->setCellValue('F1', 'TOTAL DIESEL LEVEL')
				->setCellValue('G1', 'CONSUMPTION')
				->setCellValue('H1', 'BUFFER QTY')
				->setCellValue('I1', 'LEAD TIME QTY')
				->setCellValue('J1', 'BASE ORDER QTY')
				->setCellValue('K1', 'TANK 1 ORDER QTY')
				->setCellValue('L1', 'TANK 2 ORDER QTY')
				->setCellValue('M1', 'TOTAL ORDER QTY')
				->setCellValue('N1', 'PRICE')
				->setCellValue('O1', 'VALUE')
				->setCellValue('P1', 'TENANTS');
				
				for($col = ord('a'); $col<= ord('p'); $col++){
					$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
					/* $objPHPExcel->setActiveSheetIndex(0)->getStyle(chr($col))->applyFromArray(
						  array(
							  'font'    => array(
								  'name'      => 'Arial',
								  'bold'      => true,
								  'italic'    => false,
								  'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE,
								  'strike'    => false,
								  'color'     => array(
									  'rgb' => '808080'
								  )
							  ),
							  'quotePrefix'    => true
						  )
				  );*/
				}
		$counter = 2;
		for($i=0;$i<count($states);$i++){
		
			//execute query
			$query = "select id,site_id from site where state = '".$states[$i]."' and status='Live'";
			$result = mysql_query($query)or die(mysql_error());
			
			
			$sn = 0;
			//$alphabetCounter = 3;
			while($site = mysql_fetch_object($result)) {	
				
				$sid = $site->id;
				$siteID = $site->site_id;
				
				//get current CPD
				$cpdValue = $this->getCurrentCPD($sid);
				
				//get past days from supply
				$daysPast = $this->getSiteSupplyPastDays($sid);
				
				$cousumption = $cpdValue * $daysPast;
				
				//countTenants
				$tenants = $this->countSiteTenants($sid);
				
				//get the last weekly report
				$sql = mysql_query("select * from weekly_report where site_id = '$sid' order by id desc limit 0,1")or die(mysql_error());
				$countReport = mysql_num_rows($sql);
				if($countReport==1){
					while($report = mysql_fetch_object($sql)){
					$sn += 1;
						$rid = $report->id;
						$rdate = $report->report_date;
								
						$objPHPExcel->getActiveSheet()
								->setCellValue('A'.$counter, $sn)
								->setCellValue('B'.$counter, $siteID)
								->setCellValue('C'.$counter, $rdate);
								
						$reportDetails = mysql_query("SELECT * FROM weekly_diesel_level where week_id = '$rid' order by tank asc")or die(mysql_error());
						$alpha = 'D';
						while($dieselData = mysql_fetch_object($reportDetails)) {
							$liters = $dieselData->diesel_level;
							
							$objPHPExcel->getActiveSheet(0)
							  ->setCellValue($alpha.$counter, $liters);
							$alpha++;
						}
						
						$objPHPExcel->getActiveSheet()
								->setCellValue('F'.$counter, '=SUM(D'.$counter.',E'.$counter.')')
								->setCellValue('G'.$counter, $cousumption)
								->setCellValue('H'.$counter, $bufferQty)
								->setCellValue('I'.$counter, $leadQty)
								->setCellValue('J'.$counter, '=SUM(G'.$counter.',H'.$counter.',I'.$counter.')-F'.$counter)
								->setCellValue('K'.$counter, '=J'.$counter.'/2')
								->setCellValue('L'.$counter, '=J'.$counter.'/2')
								->setCellValue('M'.$counter, '=SUM(K'.$counter.',L'.$counter.')')
								->setCellValue('N'.$counter, '0')
								->setCellValue('O'.$counter, '=M'.$counter.'*N'.$counter)
								->setCellValue('P'.$counter, $tenants);
					
					}					
				$counter++;
				}
			}		
			$counter++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// If you want to output e.g. a PDF file, simply do:
		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
		$objWriter->save("exports/".$FileName);
			
		return $FileName;
	}
	
	function dieselMetrics($post, $process) {
		$this->connect_db();
		
		if(isset($process)) {
			
			$time = time();
			
			$states = $post['states'];
			$reorderLevel = $post['reoderLevel'];
			$leadQty = $post['leadQty'];
			$bufferQty = $post['bufferQty'];
			
			$getExcelFile = $this->DieselMetricsExcel($states,$leadQty,$bufferQty);
			
			$desc = "Diesel Metrics for ";
			$stateLength = count($states);
			foreach($states as $state){
				if($stateLength==1){
					$description = $desc."$state State";
				}elseif($states[$stateLength-1]==$state) {
					$description = chop($desc,", ");
					$description .= " and $state States";
				}else{
					$desc .= "$state, ";
				}
			}
			
			$sql = "insert into diesel_metrics values('','$description','$reorderLevel','$leadQty','$bufferQty','$getExcelFile','".$_SESSION['userid']."','$time')";
			$result = mysql_query($sql)or die(mysql_error());
			
			if($result) {
				return "<div class=\"alert alert-success\"> Metrics created. <a href=\"exports/$getExcelFile\" target=\"_new\">download excel file here</a></div>";
			}
		}
	}
	
	function getMetrics() {
		$this->connect_db();
		
		$sql = "SELECT  * FROM diesel_metrics ORDER BY id DESC";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		if($num_rows > 0){
			echo"
				<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th>sn</th>
						<th>Description</th>
						<th>Reorder Level</th>
						<th>Buffer Qty.</th>
						<th>Lead Time Qty.</th>
						<th>Time Created</th>
						<th>Action</th>
                    </tr>
				</thead>
				<tbody>";
			$sn = 0;
			while($metrics = mysql_fetch_object($result)){
				$sn =+1;
				$rand = rand();
				$id = $metrics->id;
				$desc = $metrics->description;
				$reorder = $metrics->reorder_level;
				$leadQty = $metrics->lead_time_qty;
				$buffer = $metrics->buffer_qty;
				$file = $metrics->file_name;
				$created = date("Y-m-d",$metrics->time_created);
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$desc</td>
                        <td>$reorder</td>
                        <td>$buffer</td>
                        <td>$leadQty</td>
                        <td>$created</td>
                        <td>
							<a href=\"exports/$file\" target=\"_new\">Download Metrics</a> |  
							<a href=\"".$_SERVER['PHP_SELF']."?mid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\" title=\"Delete metrics\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
					</tr>";
			}
			echo"</tbody></table>";
		}else {
			echo"<div class=\"alert alert-info\">No Metrics created yet</div>";
		}
	}
	
	function SiteServiceReport() {	
		$date = date("Y-m-d",time());
		$this->connect_db();	
		
		$sql = "SELECT  * FROM servicing where date_submitted = '$date' and approve_status = 'Approved' ORDER BY site_id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		
	   if($num_rows > 0){
	   
			//generate excel File
				$excelFile = $this->generateExcel($sql,"service");
				
		   echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Today's Report ( $date )
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
					
			echo"
				<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Site ID</th>
						<th>Site Engr.</th>
						<th>service Date</th>
						<th>Cost</th>
						<th>Comments</th>
						<th>Next Service</th>
						<th>Time submitted</th>
						<th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($service = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $service->id;
				$siteID 		= $service->site_id;
				$service_date	= $service->service_date;
				$engr	 		= $service->engr_id;
				$cost			= number_format($service->cost,2);
				$comment	 	= $this->limit_words($service->comment,10);
				$nextDate		= $service->next_service_date;
				$submitted		= date("Y-m-d, h:i:s a",$service->time_created);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$state = $siteData->state;
				
				//get site engr name
				$EngrData = $this->getUserInfo($engr);
				$EngrName = $EngrData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$EngrName</td>
                        <td>$service_date</td>
                        <td>N$cost</td>
                        <td>$comment</td>
                        <td>$nextDate</td>
                        <td>$submitted</td>
                        <td>
						<a href=\"openservicereport.php?rid=$id\" data-toggle=\"modal\" data-target=\"#reportModal\" title=\"View Details\">View Details</a>";
						if($_SESSION['level']!="Supervisor") { 
						echo" | <a href=\"#?sid=$id\" title=\"Delete\">Delete</a>";
						}
                         echo"</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
				 
			 echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Report Submitted for today Yet '.$date.'</div>';   
	   }
	}
	
	function SiteServiceReportDate($dateString) {
		
		$this->connect_db();	
		
		if(strlen($dateString)>10) {
			$from = strtotime(substr($dateString,0,10));
			$to   = strtotime(substr($dateString,13,10));
			
			$fromDate = date("Y-m-d",$from);
			$toDate = date("Y-m-d",$to);
			
			$sql = "SELECT  * FROM servicing where date_submitted between '$fromDate' and '$toDate' and approve_status = 'Approved' ORDER BY site_id asc";
		}else {
			$date = strtotime($dateString);
			$fromDate = date("Y-m-d",$date);
			$sql = "SELECT  * FROM servicing where date_submitted = '$fromDate' and approve_status = 'Approved' ORDER BY site_id asc";
		}
			
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
	   
	    $excelFile = $this->generateExcel($sql,"service");
		
	  
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Report
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
					
			echo"
				<table id=\"example\"	class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">sn</th>
						<th>Site ID</th>
						<th>Site Engr.</th>
						<th>service Date</th>
						<th>Cost</th>
						<th>Comments</th>
						<th>Next Service</th>
						<th>Time submitted</th>
						<th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($service = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $service->id;
				$siteID 		= $service->site_id;
				$service_date	= $service->service_date;
				$engr	 		= $service->engr_id;
				$cost			= number_format($service->cost,2);
				$comment	 	= $this->limit_words($service->comment,10);
				$nextDate		= $service->next_service_date;
				$submitted		= date("Y-m-d, h:i:s a",$service->time_created);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$state = $siteData->state;
				
				//get site engr name
				$EngrData = $this->getUserInfo($engr);
				$EngrName = $EngrData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$EngrName</td>
                        <td>$service_date</td>
                        <td>N$cost</td>
                        <td>$comment</td>
                        <td>$nextDate</td>
                        <td>$submitted</td>
                        <td>
							<a href=\"openservicereport.php?rid=$id\" data-toggle=\"modal\" data-target=\"#reportModal\" title=\"View Details\">View Details</a>";
						if($_SESSION['level']!="Supervisor") { 
							echo" | <a href=\"#?sid=$id\" title=\"Delete\">Delete</a>";
						}
                     echo"</td>
                     </tr>";
			 }
				 echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No Service Report on selected Date</div>";   
	   }
	}
	
	function siteBulkLoad($file) {
		$this->connect_db();
		//set rows Inserted
		$rowsInserted = 0;
				
		//create error file;
		$creator = $_SESSION['username'];
		$time = date("y-d-m _ H-i-sa",time());
		$ErrorFileName = "site_Error_".$creator.$time.'.xlsx';
		$objPHPExcel_xls = new PHPExcel();
			// Set properties
			$objPHPExcel_xls->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Site Load Error File ".$creator)
						->setSubject("Site Load Error File")
						->setDescription("Site Load Error File")
						->setKeywords("Site Load Error File")
						->setCategory("Site Load Error File");
			$objPHPExcel_xls->getActiveSheet()->setTitle('sheet1');
			
			$objPHPExcel_xls->setActiveSheetIndex(0)
					->setCellValue('A1', 'Reason for Error')
					->setCellValue('B1', 'landtype')
					->setCellValue('C1', 'leaseamount')
					->setCellValue('D1', 'leasedate')
					->setCellValue('E1', 'leaseDuration')
					->setCellValue('F1', 'duration_alert')
					->setCellValue('G1', 'SiteID')
					->setCellValue('H1', 'BCT ID')
					->setCellValue('I1', 'Address')
					->setCellValue('J1', 'Region')
					->setCellValue('K1', 'Longitude')
					->setCellValue('L1', 'Latitude')
					->setCellValue('M1', 'State')
					->setCellValue('N1', 'Location Type')
					->setCellValue('O1', 'tower height')
					->setCellValue('P1', 'Site no')
					->setCellValue('Q1', 'Supervisor')
					->setCellValue('R1', 'Security')
					->setCellValue('S1', 'Supplier')
					->setCellValue('T1', 'gen1')
					->setCellValue('U1', 'gen2')
					->setCellValue('V1', 'tank_mode');
	
	
		$startRow = 2;
		$objPHPExcel = PHPExcel_IOFactory::load($file);
		foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
			$worksheetTitle     = $worksheet->getTitle();
			$highestRow         = $worksheet->getHighestRow(); // e.g. 10
			$highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
			$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
			$nrColumns = ord($highestColumn) - 64;
		}
		//if($highestColumnIndex != 21) {
		if(1 != 1) {
			return "<div class=\"alert alert-danger\">Oops! the excel format is totally Wrong... Download Correct Format <a href=\"Load_site_format.xlsx\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Format\"><i class=\"fa fa-download\"></i></a></div>";
		}else {
			$rowCount = 2;
			for ($row = $startRow; $row <= $highestRow; ++ $row) {
				$val=array();
				 
				for ($col = 0; $col < $highestColumnIndex; ++ $col) {
				   $cell = $worksheet->getCellByColumnAndRow($col, $row);
				   $val[] = $cell->getValue();

				} 
				
				
				//check site_id exists before now
				$checkSiteID = $this->checkSiteID($val[5]);
				//check bct_id exists before now
				$checkBCTID = $this->checkBCTID($val[6]);
					
				if($checkSiteID==1) {
					$objPHPExcel_xls->setActiveSheetIndex(0);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('A'.$rowCount, "Site ID Already Exists");
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('B'.$rowCount, $val[0]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('C'.$rowCount, $val[1]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('D'.$rowCount, $val[2]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('E'.$rowCount, $val[3]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('F'.$rowCount, $val[4]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('G'.$rowCount, $val[5]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('H'.$rowCount, $val[6]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('I'.$rowCount, $val[7]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('J'.$rowCount, $val[8]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('K'.$rowCount, $val[9]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('L'.$rowCount, $val[10]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('M'.$rowCount, $val[11]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('N'.$rowCount, $val[12]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('O'.$rowCount, $val[13]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('P'.$rowCount, $val[14]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('Q'.$rowCount, $val[15]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('R'.$rowCount, $val[16]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('S'.$rowCount, $val[17]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('T'.$rowCount, $val[18]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('U'.$rowCount, $val[19]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('V'.$rowCount, $val[20]);
					//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
					$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel_xls, 'Excel2007'); 
					$objWriter->save("error_files/".$ErrorFileName);
						$rowCount++;
					//return '<div class="alert alert-danger"><i class="fa fa-ban"></i>Site ID already exists, try another.</div>';
				}elseif($checkBCTID==1) {
					$objPHPExcel_xls->setActiveSheetIndex(0);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('A'.$rowCount, "Site ID Already Exists");
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('B'.$rowCount, $val[0]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('C'.$rowCount, $val[1]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('D'.$rowCount, $val[2]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('E'.$rowCount, $val[3]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('F'.$rowCount, $val[4]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('G'.$rowCount, $val[5]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('H'.$rowCount, $val[6]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('I'.$rowCount, $val[7]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('J'.$rowCount, $val[8]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('K'.$rowCount, $val[9]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('L'.$rowCount, $val[10]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('M'.$rowCount, $val[11]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('N'.$rowCount, $val[12]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('O'.$rowCount, $val[13]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('P'.$rowCount, $val[14]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('Q'.$rowCount, $val[15]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('R'.$rowCount, $val[16]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('S'.$rowCount, $val[17]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('T'.$rowCount, $val[18]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('U'.$rowCount, $val[19]);
						$objPHPExcel_xls->getActiveSheet()->SetCellValue('V'.$rowCount, $val[20]);
					//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
					$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel_xls, 'Excel2007'); 
					$objWriter->save("error_files/".$ErrorFileName);
					$rowCount++;
					//return '<div class="alert alert-danger"><i class="fa fa-ban"></i>Site ID already exists, try another.</div>';
				}
				if($checkSiteID!=1 && $checkBCTID!=1){
					$time = time();
					//insert each of the excel rows
					$query_I = "insert into site values('','".$this->mysql_prepare_value($val[5])."','".$this->mysql_prepare_value($val[6])."','".$this->mysql_prepare_value($val[7])."','".$this->mysql_prepare_value($val[8])."','".$this->mysql_prepare_value($val[9])."',
					'".$this->mysql_prepare_value($val[10])."','".$this->mysql_prepare_value($val[11])."','".$this->mysql_prepare_value($val[12])."','".$this->mysql_prepare_value($val[13])."','".$this->mysql_prepare_value($val[14])."','".$this->mysql_prepare_value($val[15])."','".$this->mysql_prepare_value($val[16])."','".$this->mysql_prepare_value($val[17])."',
					'".$this->mysql_prepare_value($val[0])."','".$this->mysql_prepare_value($val[1])."','".$this->mysql_prepare_value($val[3])."','".$this->mysql_prepare_value($val[2])."','".$this->mysql_prepare_value($val[4])."','".$this->mysql_prepare_value($val[20])."',
					'Not Live','0','0')";
					
					$result_I = mysql_query($query_I)or die(mysql_error());
					$sitekey = mysql_insert_id();
					
					//gen1
					$insertGen1 = "insert into power_source values('','$sitekey','Gen','".$this->mysql_prepare_value($var[18])."','Gen 1','250','0','".$_SESSION['userid']."','$time')";
					$resGen1 = mysql_query($insertGen1)or die(mysql_error()." 4");
					$Genkey = mysql_insert_id();
					
					//setup genrunning hours at sites
					$insertGenHrs1 = "insert into site_running_hours values('','$Genkey','0')";
					$resGenHrs1 = mysql_query($insertGenHrs1)or die(mysql_error()." 5");
					
					//setup gen current service data
					$SerqueryGen1 = "insert into service_curr_stats values('','$sitekey','$Genkey','0000-00-00','0','0','0000-00-00','0')";
					$Serviceresult1 = mysql_query($SerqueryGen1)or die(mysql_error()." 6");
					
					//setup gen current supply data
					$query_Gen1 = "insert into supply_curr_stats values('','$sitekey','Tank 1','0000-00-00','0','0','0','0000-00-00')";
					$result_Gen1 = mysql_query($query_Gen1)or die(mysql_error()." 11");
					
					///////////////////////////
					
					//gen2
					$insertGen2 = "insert into power_source values('','$sitekey','Gen','".$this->mysql_prepare_value($var[19])."','Gen 2','250','0','".$_SESSION['userid']."','$time')";
					$resGen2 = mysql_query($insertGen2)or die(mysql_error()." 4");
					$Genkey2 = mysql_insert_id();
					
					//setup genrunning hours at sites
					$insertGenHrs2 = "insert into site_running_hours values('','$Genkey2','0')";
					$resGenHrs2 = mysql_query($insertGenHrs2)or die(mysql_error()." 5");
					
					//setup gen current service data
					$SerqueryGen2 = "insert into service_curr_stats values('','$sitekey','$Genkey2','0000-00-00','0','0','0000-00-00','0')";
					$Serviceresult2 = mysql_query($SerqueryGen2)or die(mysql_error()." 6");
					
					$query_Gen2 = "insert into supply_curr_stats values('','$sitekey','Tank 2','0000-00-00','0','0','0','0000-00-00')";
					$result_Gen2 = mysql_query($query_Gen2)or die(mysql_error()." 11");
					
					$rowsInserted++;
				}
			}
			
			if($rowsInserted>0) {
				
				if($checkSiteID==1 || $checkBCTID==1){
					return "<div class=\"alert alert-warning\">Oops,Some sites failed to load. Only $rowsInserted was successful..<a href=\"error_files/$ErrorFileName\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Log\">Download Error Log</a></div>";
				}else{
					return "<div class=\"alert alert-success\"> Upload Successfull. $rowsInserted Sites Loaded</div>";
				}
			}else{
				return "<div class=\"alert alert-danger\">Operation failed. Sites Could not be loaded. <a href=\"error_files/$ErrorFileName\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Log\">Download Error Log</a></div>";
			}
		}
	}
	
	function getSitebySiteID($siteID) {
		$this->connect_db();
		
		$query = "select id,site_id from site where site_id='$siteID'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow>0) {
			$Sitedata = mysql_fetch_object($result)or die(mysql_error());
			$sid = $Sitedata->id;
			
			return $sid;
		}
	}
	
	function CustomerBulkLoad($file) {
		$this->connect_db();
		//set rows Inserted
		$rowsInserted = 0;
				
		$objPHPExcel_xls = new PHPExcel();
		
	
		$startRow = 2;
		$objPHPExcel = PHPExcel_IOFactory::load($file);
		foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
			$worksheetTitle     = $worksheet->getTitle();
			$highestRow         = $worksheet->getHighestRow(); // e.g. 10
			$highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
			$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
			//$nrColumns = ord($highestColumn) - 64;
		}
		
			for ($row = $startRow; $row <= $highestRow; ++ $row) {
				$val=array();
				 
				for ($col = 0; $col < $highestColumnIndex; ++ $col) {
				   $cell = $worksheet->getCellByColumnAndRow($col, $row);
				   $val[] = $cell->getValue();

				} 
				
					//get site primary key by site_id
					$siteid = $this->getSitebySiteID($val[0]);
						
					$time = time();
					//insert each of the excel rows
					$query_I = "insert into site_tenants values('','$siteid','".$val[1]."','".$val[2]."','".$val[3]."','".$val[4]."','".$val[5]."','0','0','$time','$time','ITP','0','Not Invoiced')";
					
					$result_I = mysql_query($query_I)or die(mysql_error());
					
					$rowsInserted++;
			}
			
			if($rowsInserted>0) {
				return "<div class=\"alert alert-success\"> Upload Successfull. $rowsInserted Customers Loaded</div>";
			}else{
				return "<div class=\"alert alert-danger\">Operation failed. Sites Could not be loaded. <a href=\"error_files/$ErrorFileName\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Log\">Download Error Log</a></div>";
			}
	}
	
	function Dash_SiteSupplyReport() {	
		$date = date("Y-m-d",time());
		$this->connect_db();
		
		$sql = "SELECT  * FROM supplies ORDER BY supply_date desc Limit 0,12";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		  
	   if($num_rows > 0){
			echo"
				<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">Site ID</th>
						<th width=\"5%\">Date</th>
						<th width=\"20%\">Stock</th>
						<th width=\"20%\">Supplied</th>
						<th width=\"20%\">Total Stock</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $supply->id;
				$siteID 		= $supply->site_id;
				$supply_date 	= date("Y-m-d",strtotime($supply->supply_date));
				$cpd	 		= $supply->cpd;
				$next_date 		= date("Y-m-d",strtotime($supply->next_supply_date));
				$posted 		= date("Y-M-d h:ma",strtotime($supply->time_created));
				
				$SiteInitialStock = $this->SiteInitialStock($id,$siteID);
				$SiteSupplied = $this->SiteSupplied($id,$siteID);
				$SiteTotalStock = $this->SiteTotalStock($id,$siteID);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$state = $siteData->state;
				
				
				echo"<tr>
                        <td>$site_id</td>
                        <td>$supply_date</td>
                        <td>$SiteInitialStock Liters</td>
                        <td>$SiteSupplied Liters</td>
                        <td>$SiteTotalStock Liters</td>
					</tr>";
			 }
			 echo"</tbody></table>";
			 
	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Report Submitted Yet.</div>';   
	   }
	}
	
	function getProjects() {	
		$date = date("Y-m-d",time());
		$this->connect_db();
		
		$sql = "SELECT  * FROM bj_projects ORDER BY project_name";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		  
	   if($num_rows > 0){
			echo"
				<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped table-hover\" id=\"example\">
               <thead>
                    <tr>
						<th>Sn</th>
						<th>Project Name</th>
						<th>Description</th>
						<th>Sites</th>
						<th>Manager</th>
						<th width=\"12%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($project = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $project->project_id;
				$projectName	= $project->project_name;
				$projectDesc	= $project->project_desc;
								
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$projectName</td>
                        <td>$projectDesc</td>
                        <td>0</td>
                        <td>Manager</td>
                        <td><a href=\"edit_project.php?pid=$id\" data-toggle=\"modal\" data-target=\"#editProject\"><i class=\"fa fa-edit\"></i> Edit</a>
						<a href=\"delete_project.php?pid=$id\" data-toggle=\"modal\" data-target=\"#deleteProject\"><i class=\"fa fa-trash\"></i> Delete</a></td>
					</tr>";
			 }
			 echo"</tbody></table>";
			 
	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Project Created Yet.</div>';   
	   }
	}
	
	function Dash_SiteServiceReport() {	
		$date = date("Y-m-d",time());
		$this->connect_db();
		
		$sql = "SELECT  * FROM servicing ORDER BY service_date desc Limit 0,12";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		
	   if($num_rows > 0){
				
			echo"
				<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">Site ID</th>
						<th>Service Date</th>
						<th>Service Next</th>
						<th>Service Cost</th>
						<th width=\"5%\">Count</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($service = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $service->id;
				$siteID 		= $service->site_id;
				$service_date	= $service->service_date;
				$service_cost	= number_format($service->cost,2);
				$service_count	= $service->count;
				$nextDate		= $service->next_service_date;
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$state = $siteData->state;
				
				echo"<tr>
                        <td>$site_id</td>
                        <td>$service_date</td>
                        <td>$nextDate</td>
                        <td>N$service_cost</td>
                        <td>$service_count</td>
					</tr>";
			 }
			 echo"</tbody></table>";
	   }else{
			echo'<div class="alert alert-danger"><strong>Oops!</strong> No Service Report Submitted Yet.</div>';   
	   }
	}
	
	function getall_site_userss($engrID) {	
		$this->connect_db();
		
		$sql = "SELECT e.id,e.site_id,e.engr_id,e.time_created,s.id,s.archived
		FROM site_users e join site s on e.site_id = s.id
		where e.engr_id = '$engrID' and s.archived = '0' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th><input id=\"selectall\" type=\"checkbox\"></th>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site Type</th>
                    <th>Supervisor</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($Engrsite = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $Engrsite->id;
				$siteID 		= $Engrsite->site_id;
				
				$siteInfo = $this->getSiteInfo($siteID);
				
				$sID 		= $siteInfo->site_id;
				$bct_id 		= $siteInfo->bct_id;
				$state 			= $siteInfo->state;
				$site_type 		= $siteInfo->site_type;
				$site_no 		= $siteInfo->site_no;
				$supervisor 		= $siteInfo->supervisor;
				$status 		= $siteInfo->status;
				
				$supvisorData = $this->getSupervisorInfo($supervisor);
				$supvisorName = $supvisorData->name;
				
				echo"<tr>
                        <td><input class=\"case\" name=\"siteID[]\" value=\"$id\" type=\"checkbox\"></td>
                        <td>$sn</td>
                        <td><div data-toggle=\"tooltip\" title=\"State - $state\">$sID</div></td>
                        <td>$bct_id </td>
                        <td><div data-toggle=\"tooltip\" title=\"Site No - $site_no\">$site_type</div></td>
                        <td>$supvisorName</td>
                        <td><div class=\"badge ";
						if($status=="Live") {echo"bg-green"; }else{echo"bg-red";}
						echo"\">$status</div></td>
                        <td><a href=\"view_site.php?siteID=$id \">
					  <span class=\"add-on small-size\"> View</span></a></td>
                        <td><a href=\"edit_site.php?sid=$id\">
					  <span class=\"add-on small-size\">Edit</span></a></td>
                        <td><a href=\"".$_SERVER['PHP_SELF']."?ac=del&sid=$id#deletesite\" 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 Site added for this engre</div>';   
	   }
	}	
	
	function SiteInitialStock($SupplyID,$siteID) {
		$this->connect_db();
		$query = "select SUM(initial_stock) as totalInitial from supplies_details where supply_id = '$SupplyID' and site_id ='$siteID'";
		$result = mysql_query($query)or die(mysql_error());
			$supply = mysql_fetch_object($result)or die(mysql_error());
			$initialSupply = $supply->totalInitial;
			return $initialSupply;
	}	
	
	function SiteInitialStockQA($SupplyID,$siteID) {
		$this->connect_db();
		$query = "select SUM(initial_stock) as totalInitial from qa_supplies_details where supply_id = '$SupplyID' and site_id ='$siteID'";
		$result = mysql_query($query)or die(mysql_error());
			$supply = mysql_fetch_object($result)or die(mysql_error());
			$initialSupply = $supply->totalInitial;
			return $initialSupply;
	}
	
	function SiteSupplied($SupplyID,$siteID) {
		$this->connect_db();
		$query = "select SUM(supplied_qty) as totalSupplied from supplies_details where supply_id = '$SupplyID' and  site_id ='$siteID'";
		$result = mysql_query($query)or die(mysql_error());
			$supply = mysql_fetch_object($result)or die(mysql_error());
			$qtySupply = $supply->totalSupplied;
			return $qtySupply;
	}
	
	function SiteSuppliedQA($SupplyID,$siteID) {
		$this->connect_db();
		$query = "select SUM(supplied_qty) as totalSupplied from qa_supplies_details where supply_id = '$SupplyID' and  site_id ='$siteID'";
		$result = mysql_query($query)or die(mysql_error());
			$supply = mysql_fetch_object($result)or die(mysql_error());
			$qtySupply = $supply->totalSupplied;
			return $qtySupply;
	}
	
	function SiteTotalStock($SupplyID,$siteID) {
		$this->connect_db();
		$query = "select SUM(new_stock) as totalStock from supplies_details where supply_id = '$SupplyID' and  site_id ='$siteID'";
		$result = mysql_query($query)or die(mysql_error());
			$supply = mysql_fetch_object($result)or die(mysql_error());
			$TotalStock = $supply->totalStock;
			return $TotalStock;
	}
	
	function SiteTotalStockQA($SupplyID,$siteID) {
		$this->connect_db();
		$query = "select SUM(new_stock) as totalStock from qa_supplies_details where supply_id = '$SupplyID' and  site_id ='$siteID'";
		$result = mysql_query($query)or die(mysql_error());
			$supply = mysql_fetch_object($result)or die(mysql_error());
			$TotalStock = $supply->totalStock;
			return $TotalStock;
	}
	
	function getall_supply($siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supplies where site_id = '$siteID' order by id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Engr</th>
                    <th>Supply Date</th>
                    <th>Initial</th>
                    <th>Supplied.</th>
                    <th>Total</th>
                    <th>CPD</th>
                    <th>Supply Date</th>
                    <th>Posted</th>
                    <th>Approval</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $supply->id;
				$siteID 		= $supply->site_id;
				$sBatch_id 		= $supply->site_batch_id;
				$engrID 		= $supply->engr_id;
				$supply_date 	= $supply->supply_date;
				$cpd	 		= $supply->cpd;
				$approval 		= $supply->approve_status;
				$next_date 		= $supply->next_supply_date;
				$posted 		= date("Y-M-d h:ma",$supply->time_created);
				
				$SiteInitialStock = $this->SiteInitialStock($id,$siteID);
				$SiteSupplied = $this->SiteSupplied($id,$siteID);
				$SiteTotalStock = $this->SiteTotalStock($id,$siteID);
				
				$engrData = $this->getUserInfo($engrID);
				$engrName = $engrData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$engrName</td>
                        <td>$supply_date</td>
                        <td>$SiteInitialStock Lit.</td>
                        <td>$SiteSupplied Lit.</td>
                        <td>$SiteTotalStock Lit.</td>
                        <td>$cpd Lit.</td>
                        <td>$next_date</td>
                        <td>$posted</td>
                        <td><span class=\"label ";
						if($approval=="Approved") {echo"label-success";}elseif($approval=="Pending") {echo"label-danger";}
						echo"\">$approval</td>
                        <td>";
						if($_SESSION['level']!="Supervisor") {
							echo "<a href=\"";
							if($_SESSION['level']=="QA") {echo"approvesupplyreport.php?rid=$id&sbid=$sBatch_id&siteID=$siteID";}else{echo"opensupplyreport.php?rid=$id&siteID=$siteID";}
							
							echo"\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> View</span></a>";
						}else{
							echo"<a href=\"opensupplyreport.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> View</span></a> | 
							<a href=\"editsupply.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> Edit</span></a> | 
							<a href=\"".$_SERVER['PHP_SELF']."?rid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Supply Report Submitted on Site Yet</div>';   
	   }
	}
	
	function getQAsupply($siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM qa_supplies where site_id = '$siteID' order by id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Engr</th>
                    <th>Supply Date</th>
                    <th>Initial</th>
                    <th>Supplied.</th>
                    <th>Total</th>
                    <th>Unit Cost</th>
                    <th>Cost</th>
                    <th>CPD</th>
                    <th>Supply Date</th>
                    <th>Posted</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $supply->id;
				$siteID 		= $supply->site_id;
				$engrID 		= $supply->engr_id;
				$supply_date 	= $supply->supply_date;
				$cpd	 		= $supply->cpd;
				$ucost	 		= $supply->unit_cost;
				$cost	 		= $supply->cost;
				$next_date 		= $supply->next_supply_date;
				$posted 		= date("Y-M-d h:ma",$supply->time_created);
				
				$SiteInitialStock = $this->SiteInitialStockQA($id,$siteID);
				$SiteSupplied = $this->SiteSuppliedQA($id,$siteID);
				$SiteTotalStock = $this->SiteTotalStockQA($id,$siteID);
				
				$engrData = $this->getUserInfo($engrID);
				$engrName = $engrData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$engrName</td>
                        <td>$supply_date</td>
                        <td>$SiteInitialStock Lit.</td>
                        <td>$SiteSupplied Lit.</td>
                        <td>$SiteTotalStock Lit.</td>
                        <td>N".number_format($ucost,2)."</td>
                        <td>N".number_format($cost,2)."</td>
                        <td>$cpd Lit.</td>
                        <td>$next_date</td>
                        <td>$posted</td>
                        <td>";
						if($_SESSION['level']!="Supervisor") {
							echo "<a href=\"opensupplyreportqa.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> View</span></a>";
						}else{
							echo"<a href=\"opensupplyreportqa.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> View</span></a> | 
							<a href=\"editsupply.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> Edit</span></a> | 
							<a href=\"".$_SERVER['PHP_SELF']."?rid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Supply Report Submitted on Site Yet</div>';   
	   }
	}
	
	function getall_WeeklyReports($siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM weekly_report where site_id = '$siteID' order by time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Report Date</th>
                    <th>Engr</th>
                    <th>Comment</th>
                    <th>Date Submitted</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $week->id;
				$siteID 		= $week->site_id;
				$engrID 		= $week->engr_id;
				$report_date 	= date("Y-m-d",strtotime($week->report_date));
				$comment 		= $this->limit_words($week->comment,10);
				$posted 		= date("Y-M-d h:ma",$week->time_created);
				
				$userData = $this->getUserInfo($engrID);
				$EngrName = $userData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$report_date</td>
                        <td>$EngrName</td>
                        <td>$comment...</td>
                        <td>$posted</td>
                        <td>";
						if($_SESSION['level']!="Supervisor") {
							echo "<a href=\"openweekreport.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\"><span class=\"add-on small-size\"> View Details</span></a>";
						}else{
							echo"<a href=\"openweekreport.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\"><span class=\"add-on small-size\"> View Details</span></a> | 
							<a href=\"".$_SERVER['PHP_SELF']."?rid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Weekly Report on Site Yet or Reports Deleted</div>';   
	   }
	}
	
	function getQAWeeklyReports($siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM qa_weekly_report where site_id = '$siteID' order by time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Report Date</th>
                    <th>Engr</th>
                    <th>Comment</th>
                    <th>Date Submitted</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $week->id;
				$siteID 		= $week->site_id;
				$engrID 		= $week->engr_id;
				$report_date 	= date("Y-m-d",strtotime($week->report_date));
				$comment 		= $this->limit_words($week->comment,10);
				$posted 		= date("Y-M-d h:ma",$week->time_created);
				
				$userData = $this->getUserInfo($engrID);
				$EngrName = $userData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$report_date</td>
                        <td>$EngrName</td>
                        <td>$comment...</td>
                        <td>$posted</td>
                        <td>";
						if($_SESSION['level']!="Supervisor") {
							echo "<a href=\"openweekreportqa.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\"><span class=\"add-on small-size\"> View Details</span></a>";
						}else{
							echo"<a href=\"openweekreport.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#reportModal\"><span class=\"add-on small-size\"> View Details</span></a> | 
							<a href=\"".$_SERVER['PHP_SELF']."?rid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Weekly Report on Site Yet or Reports Deleted</div>';   
	   }
	}
	
	function getSupplyReportDetails($reportID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supplies_details where supply_id = '$reportID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				 <thead>
					<tr>
						<th>Tank</th>
						<th>Initial Stock</th>
						<th>Supplied Quantity</th>
						<th>Total Stock</th>
					</tr>
                </thead>
				<tbody>";
			while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $supply->id;
				$sid 		= $supply->supply_id;
				$tank 		= $supply->tank;
				$fse_initstock 	= $supply->fse_initial_stock;
				$fse_supplied 	= $supply->fse_supplied_qty;
				$fse_newstock 	= $supply->fse_new_stock;
				
				echo"<tr>
                        <td>$tank</td>
                        <td>$fse_initstock Liters</td>
                        <td>$fse_supplied Liters</td>
                        <td>$fse_newstock Liters</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function getSupplyReportApproval($reportID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supplies_details where supply_id = '$reportID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				 <thead>
                    <tr>
                    <th>Tank</th>
                    <th>Initial Stock</th>
                    <th>Supplied Quantity</th>
                    <th>Total Stock</th>
					</tr>
                </thead>
				<tbody>";
			while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $supply->id;
				$sid 		= $supply->supply_id;
				$tank 		= $supply->tank;
				$initstock 	= $supply->initial_stock;
				$supplied 	= $supply->supplied_qty;
				$newstock 	= $supply->new_stock;
				
				echo"<tr>
                        <td>$tank</td>
                        <td><input type=\"hidden\" name=\"tanks[]\" class=\"form-control\" value=\"$id\"/>
						<input type=\"text\" name=\"init_stock_$id\" class=\"form-control\" value=\"$initstock\"/></td>
                        <td><input type=\"text\" name=\"supplied_qty_$id\" class=\"form-control\" value=\"$supplied\"/></td>
                        <td>$newstock Liters</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function getSupplyReportDetailsQA($reportID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supplies_details where supply_id = '$reportID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				 <thead>
                    <tr>
                    <th>Tank</th>
                    <th>Initial Stock</th>
                    <th>Supplied Quantity</th>
                    <th>Total Stock</th>
					</tr>
                </thead>
				<tbody>";
			while($supply = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $supply->id;
				$sid 		= $supply->supply_id;
				$tank 		= $supply->tank;
				$initstock 	= $supply->initial_stock;
				$supplied 	= $supply->supplied_qty;
				$newstock 	= $supply->new_stock;
				
				echo"<tr>
                        <td>$tank</td>
                        <td>$initstock Liters</td>
                        <td>$supplied Liters</td>
                        <td>$newstock Liters</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function getRunningHoursDetails($siteid) {
		$this->connect_db();
		$query = mysql_query("select * from power_source where site_id = '$siteid' and source_type='Gen'");
		echo"<table border=\"0\" class=\"table table-striped\">
				 <thead>
                    <tr>
                    <th>Power</th>
                    <th>Running Hours</th>
					</tr>
                </thead>
				<tbody>";
		while($powerSource = mysql_fetch_object($query)) {
			$powerID = $powerSource->power_id;
			$sourceName = $powerSource->source_name;
			
			$sql = mysql_query("select * from site_running_hours where power_id = '$powerID'");
			$hoursData = mysql_fetch_object($sql);
			$runningHours = $hoursData->running_hrs;
			
			echo"<tr>
					<td>$sourceName</td>					
					<td>$runningHours Hours</td>
				</tr>";
		}
		echo"</tbody></table>";
	}
	
	function getRunningHoursDetailsQA($siteid) {
		$this->connect_db();
		$query = mysql_query("select * from power_source where site_id = '$siteid' and source_type='Gen'");
		echo"<table border=\"0\" class=\"table table-striped\">
				 <thead>
                    <tr>
                    <th>Power</th>
                    <th>Running Hours</th>
					</tr>
                </thead>
				<tbody>";
		while($powerSource = mysql_fetch_object($query)) {
			$powerID = $powerSource->power_id;
			$sourceName = $powerSource->source_name;
			
			$sql = mysql_query("select * from qa_site_running_hours where power_id = '$powerID'");
			$hoursData = mysql_fetch_object($sql);
			$runningHours = $hoursData->running_hrs;
			
			echo"<tr>
					<td>$sourceName</td>
					<td>$runningHours Hours</td>
				</tr>";
		}
		echo"</tbody></table>";
	}
	
	function getWeekDieselReport($weekID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM weekly_diesel_level where week_id = '$weekID' order by tank";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				<tbody>";
			while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $week->id;
				$tank 		= $week->tank;
				$diesel_level = $week->diesel_level;
				
				echo"<tr>
                        <td>$tank</td>
                        <td>$diesel_level Liters</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function getQAWeekDieselReport($weekID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM qa_weekly_diesel_level where week_id = '$weekID' order by tank";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				<tbody>";
			while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $week->id;
				$tank 		= $week->tank;
				$diesel_level = $week->diesel_level;
				
				echo"<tr>
                        <td>$tank</td>
                        <td>$diesel_level Liters</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function getWeekRunHours($weekID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM weekly_running_hours where week_id = '$weekID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				<tbody>";
			while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $week->id;
				$pid 		= $week->power_id;
				$runHr 		= $week->run_hours;
				
				//get Power Source info
				$powerData = $this->getPowerInfo($pid);
				$powerSource = $powerData->source_name;
				echo"<tr>
                        <td>$powerSource</td>
                        <td>$runHr Hours</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function getQAWeekRunHours($weekID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM qa_weekly_running_hours where week_id = '$weekID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				<tbody>";
			while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $week->id;
				$pid 		= $week->power_id;
				$runHr 		= $week->run_hours;
				
				//get Power Source info
				$powerData = $this->getPowerInfo($pid);
				$powerSource = $powerData->source_name;
				echo"<tr>
                        <td>$powerSource</td>
                        <td>$runHr Hours</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function showServiceDetails($rID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM servicing_details where service_id='$rID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				<tbody>";
			while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $week->id;
				$pid 		= $week->power_id;
				$currHr		= $week->curr_running_hrs;
				$nextHr 	= $week->next_running_hrs;
				
				//get Power Source info
				$powerData = $this->getPowerInfo($pid);
				$powerSource = $powerData->source_name;
				echo"<tr>
                        <td>$powerSource</td>
                        <td>Current Hours : $currHr Hours</td>
                        <td>Next Service : $nextHr Hours</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function showServiceItems($rID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM service_item where service_id='$rID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				<tbody>";
			while($items = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $items->id;
				$item		= $items->service_item;
				$qty 		= $items->qty;
				
				echo"<tr>
                        <td>$item - $qty</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}else{
			echo"<div class=\"alert alert-info\">No Items specified for this service</div>";
		}
	}
	
	function showQAServiceDetails($rID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM qa_servicing_details where service_id='$rID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table border=\"0\" class=\"table table-striped\">
				<tbody>";
			while($week = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $week->id;
				$pid 		= $week->power_id;
				$currHr		= $week->curr_running_hrs;
				$nextHr 	= $week->next_running_hrs;
				
				//get Power Source info
				$powerData = $this->getPowerInfo($pid);
				$powerSource = $powerData->source_name;
				echo"<tr>
                        <td>$powerSource</td>
                        <td>Current Hours : $currHr Hours</td>
                        <td>Next Service : $nextHr Hours</td>
					</tr>";
			}
			echo "</tbody>
				 </table>";
		}
	}
	
	function tankSupplyHistory($siteID,$tankNumber) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supplies_details where site_id = '$siteID' and tank = 'Tank $tankNumber' order by id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Supply Date</th>
                    <th>Initial Stock</th>
                    <th>Supplied Quantity</th>
                    <th>Total Stock</th>
                    <th>CPD</th>
                    <th>Next Supply Date</th>
                    <th>Date Posted</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($supplyDetails = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $supplyDetails->id;
				$supplyID 		= $supplyDetails->supply_id;
				$initStock 		= $supplyDetails->initial_stock;
				$qtySupplied	= $supplyDetails->supplied_qty;
				$newStock 		= $supplyDetails->new_stock;
				
				
				$supplyData 	= $this->getSupplyInfo($supplyID);
				$supply_date 	= date("Y-m-d",strtotime($supplyData->supply_date));
				$next_date 		= date("Y-m-d",strtotime($supplyData->next_supply_date));
				$cpd	 		= $supplyData->cpd;
				$posted 		= date("Y-M-d h:ma",strtotime($supplyData->time_created));
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$supply_date</td>
                        <td>$initStock Liters</td>
                        <td>$qtySupplied Liters</td>
                        <td>$newStock Liters</td>
                        <td>$cpd Liters</td>
                        <td>$next_date</td>
                        <td>$posted</td>
                        <td>";
						if($_SESSION['level']!="Supervisor") {
							echo "N/A";
						}else{
							echo"<a href=\"".$_SERVER['PHP_SELF']."?sid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Supply on Tank Yet</div>';   
	   }
	}
	
	function allweeklyReport($siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM weekly_report where site_id = '$siteID' ORDER BY id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>Site ID</th>
                    <th>Gen1 Diesel</th>
                    <th>Gen2 Diesel</th>
                    <th>Gen1 Run Hrs</th>
                    <th>Gen2 Run Hrs</th>
                    <th>Comment</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($report = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $report->id;
				$siteID 		= $report->site_id;
				$g1_diesel	 		= $report->g1_diesel;
				$g2_diesel	 		= $report->g2_diesel;
				$running_hours	 		= $report->running_hours;
				$comment	 		= $report->comment;
				
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td>$site_id</td>
                        <td>$g1_diesel </td>
                        <td>$g2_diesel</td>
                        <td>$running_hours</td>
                        <td>$comment</td>
                        <td>
						<a href=\"view_weekreport.php?rid=$id\"><span class=\"add-on small-size\"> Edit</span></a> |
						<a href=\"".$_SERVER['PHP_SELF']."?rid=$id&siteID=$siteID&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 Report Yet</div>';   
	   }
	}
	
	function getall_servicing($siteID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM servicing where site_id = '$siteID' ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>SN</th>
                    <th>Serviced Date</th>
                    <th>Comment</th>
                    <th>Cost</th>
                    <th>Count</th>
                    <th>Report</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($service = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $service->id;
				$siteID 		= $service->site_id;
				$serviceDate 	= $service->service_date;
				$comment 		= $service->comment;
				$Cost			= number_format($service->cost,2);
				$count 			= $service->count;
				$approved 		= $service->approve_status;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$serviceDate </td>
                        <td>$comment </td>
                        <td>N$Cost</td>
                        <td>$count </td>
                        <td><span class=\"label label-";
						if($approved=="Pending"){echo"danger";}else{echo"success";}
						echo"\">$approved</span></td>
						<td>";
						if($_SESSION['level']!="Supervisor") {
							echo"<a href=\"";
							if($_SESSION['level']!="QA"){echo"openservicereport";}else{echo"approveservicereport";}
							echo".php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> View</span></a>";
						}else {
							echo"<a href=\"openservicereport.php?rid=$id&siteID=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\"><span class=\"add-on small-size\"> View</span></a> |
							<a href=\"".$_SERVER['PHP_SELF']."?sid=$id&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
						}
						echo"</td>
                     </tr>";
			 }
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Service made on Site Yet</div>';   
	   }
	}
	
	function getall_siteCustomers($siteID) {	
		$this->connect_db();		
		$sql = "SELECT * FROM site_tenants where site_id = '$siteID' and state !='Decommissioned' ORDER BY id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>Name</th>
                    <th>RF</th>
                    <th>MW</th>
                    <th>Height</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Status Date</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$siteID 		= $customer->site_id;
				$custid			= $customer->customer_id;
				$rf 			= $customer->rf;
				$mw 			= $customer->mw;
				$height 		= $customer->height_occupied ;
				$amount 		= $customer->amount ;
				$dateAdded 		= date("d M, Y",$customer->time_added);
				$lastUpdate		= date("d M, Y",$customer->last_update);
				$liveDate		= date("d M, Y",$customer->live_date);
				$state	 		= $customer->state;
				
				//get term Data
				$custData = $this->getCustomerInfo($custid);
				$customerName = $custData->customer_name;
				$short_name = $custData->short_name;
				$criteria = $custData->commercial_term;
				
				echo"<tr>
                        <td>$short_name</td>
                        <td>$rf</td>
                        <td>$mw</td>
                        <td>$height Meters</td>
                        <td>N".number_format($amount,2)."</td>
                        <td><div class=\"label ";
						if($state=="Live") {echo"label-success"; }else{echo"label-danger";}
						echo"\">$state</div></td>
                        <td><div data-toggle=\"tooltip\" title=\"Last Update - $lastUpdate\">";
						if($customer->live_date=="0") {
							echo"Not Live";
						}else {
							echo"$liveDate";
						}					
						echo"</div></td>
                        <td>
							<a href=\"t_level.php?cid=$id\" data-toggle=\"modal\" data-target=\"#levelmodal\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Update Customer State\"><i class=\"fa fa-upload\"></i></div></a>  
							<a href=\"".$_SERVER['PHP_SELF']."?custid=$id&siteID=$siteID\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Edit Customer Record\"><i class=\"fa fa-pencil\"></i></div></a>  
                            <a href=\"".$_SERVER['PHP_SELF']."?cid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Delete Customer\"><i class=\"fa fa-eraser\"></i></div></a>
							</td>
                     </tr>";
					 
					 $total_amt =$total_amt+$amount;
			 }
				echo"<tr>
					<td align=\"right\" colspan=\"4\"><strong>Total</strong></td>
					<td><strong>N".number_format($total_amt,2)."</strong></td>
					<td colspan=\"3\"></td>
				</tr>
				</table>";
		}else{
			echo'<div class="alert alert-danger">No Customer for site</div>';   
	   }
	}
	
	function siteDecommissionedCustomers($siteID) {	
		$this->connect_db();		
		$sql = "SELECT * FROM site_tenants where site_id = '$siteID' and state ='Decommissioned' ORDER BY id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo'<div class="col-md-8">
					<div class="panel panel-piluku">
						<div class="panel-heading">
							<h3 class="panel-title">Decommissioned Sites</h3>
						</div>
						<div class="panel-body">
							<a name="delcust"></a>
							<?php echo $delete_customer; ?>
                            <div class="small-size">';
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Name</th>
                    <th>RF</th>
                    <th>MW</th>
                    <th>Height</th>
                    <th>Commercial Terms</th>
                    <th>State</th>
                    <th>Decommissioned</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			$sn = 0;
			$total_amt = 0;
			while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$siteID 		= $customer->site_id;
				$custid			= $customer->customer_id;
				$rf 			= $customer->rf;
				$mw 			= $customer->mw;
				$height 		= $customer->height_occupied ;
				$decomm			= date("d M, Y",$customer->decommissioned_date);
				$state	 		= $customer->state;
				
				//get term Data
				$custData = $this->getCustomerInfo($custid);
				$customerName = $custData->customer_name;
				$short_name = $custData->short_name;
				$criteria = $custData->commercial_term;
				
				//get term Data
				$termData = $this->getTermInfo($criteria);
				$term = $termData->commercial_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$short_name</td>
                        <td>$rf</td>
                        <td>$mw</td>
                        <td>$height Meters</td>
                        <td>$term</td>
                        <td><div class=\"label ";
						if($state=="Live") {echo"label-success"; }else{echo"label-danger";}
						echo"\">$state</div></td>
                        <td>$decomm</td>
                        <td>
							<a href=\"t_level.php?cid=$id\" data-toggle=\"modal\" data-target=\"#levelmodal\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Update Customer State\"><i class=\"fa fa-upload\"></i></div></a>  
							<a href=\"".$_SERVER['PHP_SELF']."?custid=$id&siteID=$siteID\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Edit Customer Record\"><i class=\"fa fa-pencil\"></i></div></a>  
                            <a href=\"".$_SERVER['PHP_SELF']."?cid=$id&siteID=$siteID&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Delete Customer\"><i class=\"fa fa-eraser\"></i></div></a>
							</td>
                     </tr>";
			}
			echo'</tbody><table></div>
						</div>
					</div>
				</div>';
		}
	}
	
	function getAllCustomers() {	
		$this->connect_db();		
		$sql = "SELECT * FROM customer ORDER BY customer_name asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Name</th>
                    <th>Commercial Terms</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Phone</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 			= $customer->id;
				$customerName	= $customer->customer_name;
				$short_name		= $customer->short_name;
				$address		= $this->limit_words($customer->address,5);
				$city			= $customer->city;
				$cterm 			= $customer->commercial_term;
				$phone 			= $customer->phone;
				$email 			= $customer->email;
				
				//get commercial term Data
				$termData = $this->getTermInfo($cterm);
				$term = $termData->commercial_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customerName ($short_name)</td>
                        <td>$term</td>
                        <td>$address...</td>
                        <td>$city</td>
                        <td>$phone</td>
                        <td> 
							<a href=\"view_customer.php?custid=$id\" data-toggle=\"modal\" data-target=\"#custModal\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Edit Customer Record\"><i class=\"fa fa-folder-o\"></i></div></a>  
							<a href=\"customer.php?custid=$id&ed=$rand\" data-toggle=\"modal\" data-target=\"#custModal\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Edit Customer Record\"><i class=\"fa fa-pencil\"></i></div></a>  
                            <a href=\"".$_SERVER['PHP_SELF']."?cid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Delete Customer\"><i class=\"fa fa-trash-o\"></i></div></a>
							</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Customer Added Yet</div>'; 
	   }
	}
	
	function getall_CommercialTerms() {	
		$this->connect_db();		
		$sql = "SELECT * FROM commercial_terms ORDER BY time_created desc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table  class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Commercial Name</th>
                    <th>Period</th>
                    <th>Criteria</th>
                    <th>Net Days</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$commName 		= $customer->commercial_name;
				$period			= $customer->period;
				$criteria		= $customer->criteria;
				$net_days		= $customer->net_days;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$commName</td>
                        <td>$period Months</td>
                        <td>$criteria</td>
                        <td>$net_days Days</td>
                        <td>
							<a href=\"".$_SERVER['PHP_SELF']."?termid=$id&ac=ed\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Edit Term\"><i class=\"fa fa-pencil\"></i></div></a>  
                            <a href=\"".$_SERVER['PHP_SELF']."?tid=$id&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\"><div style=\"float:left; margin-right:5px;\" data-toggle=\"tooltip\" title=\"Delete Term\"><i class=\"fa fa-trash\"></i></div></a>
							</td>
                     </tr>";
			 }
			   
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Term created Yet</div>';   
	   }
	}
	
	function siteCustomers($siteID) {	
		$this->connect_db();		
		$sql = "SELECT * FROM site_tenants where site_id = '$siteID' and state !='Decommissioned' ORDER BY id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Name</th>
                    <th>Live Date</th>
                    <th>State</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$siteID 		= $customer->site_id;
				$custid			= $customer->customer_id;
				$rf 			= $customer->rf;
				$mw 			= $customer->mw;
				$height 		= $customer->height_occupied ;
				$dateAdded 		= date("d M, Y",$customer->time_added);
				$lastUpdate		= date("d M, Y",$customer->last_update);
				$liveDate		= date("d M, Y",$customer->live_date);
				$state	 		= $customer->state;
				
				//get term Data
				$custData = $this->getCustomerInfo($custid);
				$customerName = $custData->short_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"sitetanent.php?tid=$id\" data-toggle=\"modal\" data-target=\"#siteModal\">$customerName</a></td>
                        <td><div data-toggle=\"tooltip\" title=\"Last Update - $lastUpdate\">";
						if($customer->live_date=="0") {
							echo"Not Live";
						}else{
							echo"$liveDate";
						}						
						echo"</div></td>
                        <td><div class=\"label ";
						if($state=="Live") {echo"label-success"; }else{echo"label-danger";}
						echo"\">$state</div></td>
                     </tr>";
			 }
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Customer for site</div>';   
	   }
	}
	
	function updateProject($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$projectid    		= $this->mysql_prepare_value(trim($post['project_id']));
			$project_name		= $this->mysql_prepare_value(trim($post['project_name']));
			$project_desc		= $this->mysql_prepare_value(trim($post['project_desc']));	
			

			$query_I = "update bj_projects set 
			project_name = '$project_name',
			project_desc = '$project_desc'
			where project_id = '$projectid'";	
		
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Project Updated Successful</div>';
			}
		}
	}
	
	function updateCustomer($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$Custid    			= $this->mysql_prepare_value(trim($post['custID']));
			$customerName		= $this->mysql_prepare_value(trim($post['customername']));
			$short_name			= $this->mysql_prepare_value(trim($post['acro']));
			$custType			= $this->mysql_prepare_value(trim($post['custType']));
			$terms				= $this->mysql_prepare_value(trim($post['terms']));
			$city				= $this->mysql_prepare_value(trim($post['city']));
			$address			= $this->mysql_prepare_value(trim($post['address']));			
			$phone				= $this->mysql_prepare_value(trim($post['phone']));			
			$email				= $this->mysql_prepare_value(trim($post['email']));	
			

			$query_I = "update customer set 
			customer_name = '$customerName',
			short_name = '$short_name',
			ctype_id = '$custType',
			commercial_term = '$terms',
			address = '$address',
			city = '$city',
			phone = '$phone',
			email = '$email'
			where id = '$Custid'";	
		
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Customer Updated Successful</div>';
			}
		}
	}
	
	function updateTenant($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$Custid    		= $this->mysql_prepare_value(trim($post['customerID']));
			$customerName		= $this->mysql_prepare_value(trim($post['cus_name']));
			$rf					= $this->mysql_prepare_value(trim($post['rf']));
			$mw					= $this->mysql_prepare_value(trim($post['mw']));			
			$height				= $this->mysql_prepare_value(trim($post['height']));			
			$cost				= $this->mysql_prepare_value(trim($post['cost']));			
			$state				= $this->mysql_prepare_value(trim($post['state']));
			

			$query_I = "update site_tenants set 
			customer_id = '$customerName',
			rf = '$rf',
			mw = '$mw',
			height_occupied = '$height',
			amount = '$cost',
			state = '$state'
			where id = '$Custid'";	
		
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Updated Successful</div>';
			}
		}
	}
	
	function updateCommercialTerms($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$commid    		= $this->mysql_prepare_value(trim($post['commid']));
			$comm_name    	= $this->mysql_prepare_value(trim($post['comm_name']));
			$period			= $this->mysql_prepare_value(trim($post['period']));
			$criteria		= $this->mysql_prepare_value(trim($post['criteria']));
			$netdays		= $this->mysql_prepare_value(trim($post['net_days']));		
			

			$query_I = "update commercial_terms set 
			commercial_name = '$comm_name',
			period = '$period',
			criteria = '$criteria',
			net_days = '$netdays'
			where id = '$commid'";	
		
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Updated Successful</div>';
			}
		}
	}
	
	function deleteProject($post, $delete) {
		$this->connect_db();
		if(isset($delete)) {
			$id = $post['project_id'];
			$query = "delete from bj_projects WHERE project_id = $id";
			$result = mysql_query($query)or die(mysql_error());
			return  "<div class=\"alert alert-success\">Project deleted Successfully.</div>";
		}
	}
	
	function getall_Livesites() {	
		$this->connect_db();
		$q = mysql_query("SELECT * FROM site where status='Live'");
		$Countrows = mysql_num_rows($q);
		// how many rows to show per page
		$rowsPerPage = 21;
		// by default we show first page
		$pageNum = 1;
		// if $_GET['page'] defined, use it as page number
		if(isset($_GET['page'])){
			$pageNum = $_GET['page'];
		}
		// counting the offset
		$offset = ($pageNum - 1) * $rowsPerPage;
		
		$sql = "SELECT * FROM site where status='Live' ORDER BY id asc LIMIT {$offset}, {$rowsPerPage}";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<div class=\"alert alert-info alert-dismissable\">
                <i class=\"fa fa-info\"></i> 
				total of $Countrows Records</div>
			<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site Type</th>
                    <th>Gen Power</th>
                    <th>Capacity</th>
                    <th>Live Date</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$site_type 		= $site->site_type;
				$site_no 		= $site->site_no;
				$gen_power 		= $site->gen_power_rating;
				$capacity 		= $site->capacity;
				$liveDate 		= date("D d, M, Y",$site->live_date);
				
				echo"<tr>
                        <td>$sn</td>
                        <td><div data-toggle=\"tooltip\" title=\"State - $state\">$siteID</div></td>
                        <td>$bct_id </td>
                        <td><div data-toggle=\"tooltip\" title=\"Site No - $site_no\">$site_type</div></td>
                        <td>$gen_power</td>
                        <td>$capacity </td>
                        <td>$liveDate</td>
                        <td><a href=\"view_site.php?siteID=$id\"><span class=\"add-on small-size\"> View</span></a></td>
                     </tr>";
			 }
			 $sel_advice_count   = "SELECT COUNT(*) AS numrows from site where status='Live'";
			$result_sel_user_count  = mysql_query($sel_advice_count) or die('Error, query failed');
			$row = mysql_fetch_array($result_sel_user_count);
			$numrows = $row['numrows'];	

			// how many pages we have when using paging?
			$maxPage = ceil($numrows/$rowsPerPage);
			// print the link to access each page
			$self = $_SERVER['PHP_SELF'];
			$nav  = '';
			
			if ($pageNum > 1) {
			   $page  = $pageNum - 1;
			   $prev  = "<li class=\"prev\"><a href=\"$self?page=$page\">

    ← Previous</a></li> ";

			   $first = "<li><a href=\"$self?page=1\">First Page</a> </li>";
			} else {
			   $prev  = '&nbsp;'; // we're on page one, don't print previous link
			   $first = '&nbsp;'; // nor the first page link
			}

			if ($pageNum < $maxPage) {
			   $page = $pageNum + 1;
			   $next = "<li class=\"next\"><a href=\"$self?page=$page\">    Next → </a></li>";

			   $last = "<li><a href=\"$self?page=$maxPage\">Last Page</a></li>";
			} else {
			   $next = '&nbsp;'; // we're on the last page, don't print next link
			   $last = '&nbsp;'; // nor the last page link
			}

			// print the navigation link
			echo "</tbody>
				 </table><br /><table width=\"100%\"><tr><td>
				 <div class=\"col-xs-9\">
				 <div class=\"dataTables_paginate paging_bootstrap\"><ul class=\"pagination\">". $first . $prev . $nav . $next . $last."</ul></div></div></td></tr></table>";
	   }else{
			echo'<div class="alert alert-danger">No Site Has gone Live Yet</div>';   
	   }
	}
	
	function getall_Customers4Invoice($invoiced) {	
		$this->connect_db();
		$today = date("Y-m-d",time());
		
		$sql = "SELECT * FROM invoice_customer where next_invoice_date <= '$today' and invoiced_next ='$invoiced' ORDER BY id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Customer Name</th>
                    <th>Criteria</th>
                    <th>Live Date</th>
                    <th>Invoice Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($invoice = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $invoice->id;
				$custid			= $invoice->customer_id;
				
				//get customer site_id;
				$custData = $this->getCustomerinfo($custid);
				$customerName = $custData->customer_name;
				$shortName = $custData->short_name;
				$cterm = $custData->commercial_term;
				
				//get customer site_id;
				$termData = $this->getTermInfo($cterm);
				$term = $termData->commercial_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customerName</td>
                        <td>$term</td>
                        <td><a href=\"invoice_site.php?tid=$id\"><span class=\"add-on small-size\">Issue Invoice</span></a></td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-success">No Customer Due for Invoice</div>';   
	   }
	}
	
	function getall_LiveTenants() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_tenants where state='Live' ORDER BY last_update desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Customer Name</th>
                    <th>Site ID</th>
                    <th>RF</th>
                    <th>MW</th>
                    <th>Criteria</th>
                    <th>Live Date</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$siteID 		= $customer->site_id;
				$customerName	= $customer->customer_name;
				$rf 			= $customer->rf;
				$mw		 		= $customer->mw;
				$criteria 		= $customer->criteria;
				$liveDate 		= date("D d, M, Y",$customer->last_update);
				
				//get customer site_id;
				$siteData = $this->getSiteInfo($siteID);
				$siteID = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customerName</td>
                        <td>$siteID</td>
                        <td>$rf</td>
                        <td>$mw</td>
                        <td>$criteria</td>
                        <td>$liveDate</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Site Has gone Live Yet</div>';   
	   }
	}
	
	function getall_DecomTenants() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_tenants where state='Decommissioned' ORDER BY last_update desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Customer Name</th>
                    <th>Site ID</th>
                    <th>RF</th>
                    <th>MW</th>
                    <th>Height</th>
                    <th>Criteria</th>
                    <th>Decommission Date</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$custid			= $customer->customer_id;
				$siteID 		= $customer->site_id;
				$rf 			= $customer->rf;
				$mw		 		= $customer->mw;
				$height	 		= $customer->height_occupied;
				$criteria 		= $customer->criteria;
				$DecommDate 		= date("D d, M, Y",$customer->decommissioned_date);
				
				//get customer site_id;
				$siteData = $this->getSiteInfo($siteID);
				$siteID = $siteData->site_id;
				
				//get customer name;
				$custData = $this->getCustomerInfo($custid);
				$customer = $custData->short_name;
				$criteria = $custData->commercial_term;
				
				//get term Data
				$termData = $this->getTermInfo($criteria);
				$term = $termData->commercial_name;
				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customer</td>
                        <td>$siteID</td>
                        <td>$rf</td>
                        <td>$mw</td>
                        <td>$height Meters</td>
                        <td>$term</td>
                        <td>$DecommDate</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Decommisioned Tenant Yet</div>';   
	   }
	}
	
	function getall_ITPTenants() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_tenants where state='ITP' ORDER BY last_update desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Customer Name</th>
                    <th>Site ID</th>
                    <th>RF</th>
                    <th>MW</th>
                    <th>Criteria</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$siteID 		= $customer->site_id;
				$customerName	= $customer->customer_name;
				$rf 			= $customer->rf;
				$mw		 		= $customer->mw;
				$criteria 		= $customer->criteria;
				$liveDate 		= date("D d, M, Y",$customer->last_update);
				
				//get customer site_id;
				$siteData = $this->getSiteInfo($siteID);
				$siteID = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customerName</td>
                        <td>$siteID</td>
                        <td>$rf</td>
                        <td>$mw</td>
                        <td>$criteria</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Tenant is on this Level</div>';   
	   }
	}
	
	function getall_ProvisionTenants() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_tenants where state='Site Provision' ORDER BY last_update desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Customer Name</th>
                    <th>Site ID</th>
                    <th>RF</th>
                    <th>MW</th>
                    <th>Criteria</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($customer = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $customer->id;
				$siteID 		= $customer->site_id;
				$customerName	= $customer->customer_name;
				$rf 			= $customer->rf;
				$mw		 		= $customer->mw;
				$criteria 		= $customer->criteria;
				$liveDate 		= date("D d, M, Y",$customer->last_update);
				
				//get customer site_id;
				$siteData = $this->getSiteInfo($siteID);
				$siteID = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$customerName</td>
                        <td>$siteID</td>
                        <td>$rf</td>
                        <td>$mw</td>
                        <td>$criteria</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody></table>";
		}else{
			echo'<div class="alert alert-danger">No Tenant is on this Level</div>';   
	   }
	}
	
	function getall_customerInvoiced($customerID) {	
		$this->connect_db();
		
		$sql = "SELECT id,invoice_date,due_date,payment_status,amount,DATEDIFF(due_date,CURDATE()) as remaing_days FROM invoice_customer 
				where customer_id ='$customerID' ORDER BY id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Invoice Date</th>
                    <th>Amount</th>
                    <th>Due Date</th>
                    <th>Days Left</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($invoice = mysql_fetch_object($result)) {
				$sn += 1;
				$id 				= $invoice->id;
				$start_date 		= $invoice->invoice_date;
				$due_date			= $invoice->due_date;
				$amount				= number_format($invoice->amount,2);
				$status				= $invoice->payment_status;
				$remaingDays		= $invoice->remaing_days;
				
				//get customer site_id;
				$siteData = $this->getSiteInfo($siteID);
				$siteID = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$start_date</td>
                        <td>₦$amount</td>
                        <td>$due_date</td>
                        <td>";
						if($status=="Paid") {echo"N/A";}else{echo"$remaingDays ";}
						echo"Day(s)</td>
                        <td><div class=\"label  ";
						if($status=="Not Paid") {echo"label-danger";}else{echo"label-success";}
						echo"\">$status</div></td>
                        <td>
						<a href=\"update_invoice.php?invID=$id&custID=$customerID\" data-toggle=\"modal\" data-target=\"#invoiceModal\"><span class=\"add-on small-size\">update</span></a> | 
						<a href=\"".$_SERVER['PHP_SELF']."?invID=$id&custID=$customerID&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 Invoice Yet</div>';   
	   }
	}
	
	function addUser($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$name    	= $this->mysql_prepare_value($post['fname']);
			$phone		= $this->mysql_prepare_value($post['phone']);
			$email		= $this->mysql_prepare_value($post['email']);
			$address	= $this->mysql_prepare_value($post['address']);
			$username	= $this->mysql_prepare_value($post['username']);
			$password	= $this->mysql_prepare_value($post['password']);
			$Level		= $this->mysql_prepare_value($post['level']);
			
			$time = time();
			

			$query_I = "insert into app_users values('','$name','$email','$phone','$address','$username','".md5($password)."','','no','','0','$Level','','Live','yes','yes','yes','yes','yes','yes','yes')";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			$engrID = mysql_insert_id();
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i>Engineer Added</div>';
			}
		}
	}
	
	function updateUser($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$user_id    = $this->mysql_prepare_value($post['user_id']);
			$name    	= $this->mysql_prepare_value($post['fname']);
			$phone		= $this->mysql_prepare_value($post['phone']);
			$email		= $this->mysql_prepare_value($post['email']);
			$address	= $this->mysql_prepare_value($post['address']);
			$username	= $this->mysql_prepare_value($post['username']);
			$password	= $this->mysql_prepare_value($post['password']);
			$level		= $this->mysql_prepare_value($post['level']);
			
			$time = time();		

			$query_I = "update app_users set name = '$name', 
			phone = '$phone', 
			email = '$email', 
			address = '$address', 
			username = '$username'";
			if($password!="") { $query_I .= ",password = '".md5($password)."'";}
			$query_I .= ", user_level = '$level' WHERE id = '$user_id'";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			$engrID = mysql_insert_id();
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> User Updated</div>';
			}
		}
	}
	
	function addCustomerType($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$typeName    	= $this->mysql_prepare_value($post['typeName']);
			$kilowatts		= $this->mysql_prepare_value($post['kilowatts']);
			
			$time = time();
			

			$query_I = "insert into customer_type values('','$typeName','$kilowatts','".$_SESSION['userid']."','$time')";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i>Customer Type Added</div>';
			}
		}
	}
	
	function updateCustomerType($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$tid		    = $this->mysql_prepare_value($post['tid']);
			$typeName    	= $this->mysql_prepare_value($post['typeName']);
			$kilowatts		= $this->mysql_prepare_value($post['kilowatts']);	

			$query_I = "update customer_type set type_name = '$typeName', 
			kilowatts = '$kilowatts'
			WHERE id = '$tid'";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			$engrID = mysql_insert_id();
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> User Updated</div>';
			}
		}
	}
	
	function updatePreferences($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			if(isset($post['nemail'])){ $nemail = "yes"; }else{ $nemail = "no"; }
			if(isset($post['nsupply'])){ $nsupply = "yes"; }else{ $nsupply = "no"; }
			if(isset($post['nservice'])){ $nservice = "yes"; }else{ $nservice = "no"; }
			if(isset($post['nreorder'])){ $nreorder = "yes"; }else{ $nreorder = "no"; }
			if(isset($post['nticket'])){ $nticket = "yes"; }else{ $nticket = "no"; }
			if(isset($post['nweek'])){ $nweek = "yes"; }else{ $nweek = "no"; }
			if(isset($post['ndowntime'])){ $ndowntime = "yes"; }else{ $ndowntime = "no"; }

			$query_I = "update app_users set email_notify = '$nemail', 
			supply_notify = '$nsupply', 
			service_notify = '$nservice', 
			dieselreorder_notify = '$nreorder',
			ticket_notify = '$nticket',
			week_notify = '$nweek', 
			downtime_notify = '$ndowntime'";				
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Preferences Saved Successfully</div>';
			}
		}
	}
	
	function addVendor($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$vendor_name    	= $this->mysql_prepare_value($post['vendor_name']);
			$state				= $this->mysql_prepare_value($post['state']);
			$region				= $this->mysql_prepare_value($post['region']);
			$qty				= $this->mysql_prepare_value($post['qty']);
			$city				= $this->mysql_prepare_value($post['city']);
			$email				= $this->mysql_prepare_value($post['email']);
			$contact			= $this->mysql_prepare_value($post['contact']);
			$phone				= $this->mysql_prepare_value($post['phone']);
			

			$query_I = "insert into vendors values('','$vendor_name','$state','$region','$qty','$city','$email','$contact','$phone')";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i>Vendor Added</div>';
			}
		}
	}
	
	
	function updateVendor($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$vid    			= $this->mysql_prepare_value($post['vID']);
			$vendor_name    	= $this->mysql_prepare_value($post['vendor_name']);
			$state				= $this->mysql_prepare_value($post['state']);
			$region				= $this->mysql_prepare_value($post['region']);
			$qty				= $this->mysql_prepare_value($post['qty']);
			$city				= $this->mysql_prepare_value($post['city']);
			$email				= $this->mysql_prepare_value($post['email']);
			$contact			= $this->mysql_prepare_value($post['contact']);
			$phone				= $this->mysql_prepare_value($post['phone']);
			

			$query_I = "update vendors set 
			name = '$vendor_name',
			state = '$state',
			region = '$region',
			site_qty = '$qty',
			city = '$city',
			email = '$email',
			contact = '$contact',
			phone = '$phone'
			where id = '$vid'";	
		
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i>Updated Successful</div>';
			}
		}
	}
	
	function addEngrSite($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			$siteID		= $this->mysql_prepare_value($post['site']);
			$userID		= $this->mysql_prepare_value($post['user']);
			
			$time = time();
			
			//check if engr has been added to this site before
			$checkQuery = "select site_id,user_id from site_users where site_id = '$siteID' and user_id = '$userID'";
			$checkResult = mysql_query($checkQuery)or die(mysql_error());
			$countRow = mysql_num_rows($checkResult);
			if($countRow==0) {
				$query_I = "insert into site_users values('','$siteID','$userID','$time')";					
				$result_I = mysql_query($query_I)or die(mysql_error());
				if($result_I) {
					return '<div class="alert alert-success"><i class="fa fa-check"></i> Site Added for Engr.</div>';
				}
			}else{
				return'<div class="alert alert-info"><i class="fa fa-check"></i> Engr is aleady on this site.</div>';
			}
		}
	}
	
	function addITPs($tenant,$site_id,$anniversary,$term) {
		$this->connect_db(); 

		$client				= $this->mysql_prepare_value($tenant);
		$siteID		    	= $this->mysql_prepare_value($site_id);
		$anniversary		= $this->mysql_prepare_value($anniversary);
		$term				= $this->mysql_prepare_value($term);
		
		//$day = trim(substr($anniversary,0,2));
		//$mon   = trim(substr($anniversary,3,2));
		//$yr   = trim(substr($anniversary,6,4));
		
		//$anniversaryDate = strtotime("$yr-$mon-$day");

		$query_I = "insert into itp values('','$client','$siteID','$anniversary','$term')";			
		$result_I = mysql_query($query_I)or die(mysql_error());
		if($result_I) {
			return '<div class="alert alert-success"><i class="fa fa-check"></i>ITPs Added</div>';
		}
	}
	
	function addBatch($post,$process) {
		if(isset($process)) {
			$this->connect_db(); 

			$batch_name	= $this->mysql_prepare_value($post['batch_name']);
			$litercost	= $this->mysql_prepare_value($post['litercost']);
			$time = time();
			

			$query_I = "insert into supply_batch values('','$batch_name','$litercost','".$_SESSION['userid']."','Open','$time')";			
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Batch Saved</div>';
			}
		}
	}
	
	function addBatchSites($post,$process) {
		if(isset($process)) {
			$this->connect_db(); 

			$batchID	= $post['batchID'];
			$sites		= $post['sites'];
			$time = time();
			
			$siteCount = count($sites);
			
			for($i=0;$i<$siteCount;$i++) {
				$query_I = "insert into supply_batch_site values('','$batchID','".$sites[$i]."','".$_SESSION['userid']."','not reported','$time')";			
				$result_I = mysql_query($query_I)or die(mysql_error());			
			}
			
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Site(s) added to Batch</div>';
			}
		}
	}
	
	function addPO($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$ref			= $this->mysql_prepare_value($post['ref']);
			$vendor		    = $this->mysql_prepare_value($post['vendor']);
			$address		= $this->mysql_prepare_value($post['address']);
			$odate			= $this->mysql_prepare_value($post['odate']);
			$terms			= $this->mysql_prepare_value($post['terms']);
			$comment		= $this->mysql_prepare_value($post['comment']);
			$time = time();

			$query_I = "insert into purchase_order values('','$ref','$vendor','$address','$odate','$terms','$comment','0000-00-00','Not Received','Not Invoiced','$time')";			
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success">Purchase Order Saved</div>';
			}
		}
	}
	
	function addPO_Item($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$poid			= $this->mysql_prepare_value($post['poid']);
			$item_name	    = $this->mysql_prepare_value($post['item_name']);
			$desc			= $this->mysql_prepare_value($post['desc']);
			$qty			= $this->mysql_prepare_value($post['qty']);
			$cost			= $this->mysql_prepare_value($post['cost']);
			$total			= $qty * $cost;
			$time = time();

			$query_I = "insert into po_items values('','$poid','$item_name','$desc','$qty','$cost','$total','$time')";			
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success">Item Added to Order</div>';
			}
		}
	}
	
	function addSiteDoc($post,$file,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			$siteID		= $this->mysql_prepare_value($post['site']);
			$docDesc		= $this->mysql_prepare_value($post['docDesc']);
			$time = time();
			
			//upload docment
			$fileExtension = strrchr($file['doc_file']['name'], ".");
			$doc_path = "asset_docs/$time$fileExtension";
			move_uploaded_file($file['doc_file']['tmp_name'], $doc_path);
				
			$query = "insert into site_doc values('','$siteID','$docDesc','$doc_path','".$_SESSION['userid']."','$time')";			
			$result = mysql_query($query)or die(mysql_error());
			if($result) {
				return '<div class="alert alert-success">Document Uploaded Successfull</div>';
			}
		}
	}
	
	function addAssetDoc($post,$file,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$assetid		= $this->mysql_prepare_value($post['aid']);
			$docName		= $this->mysql_prepare_value($post['docName']);
			$docDesc		= $this->mysql_prepare_value($post['docDesc']);
			$time = time();
			
			//upload docment
			$fileExtension = strrchr($file['doc_file']['name'], ".");
			$doc_path = "asset_docs/$time$fileExtension";
			move_uploaded_file($file['doc_file']['tmp_name'], $doc_path);
				
			$query = "insert into asset_doc values('','$assetid','$docName','$docDesc','$doc_path','".$_SESSION['userid']."','$time')";			
			$result = mysql_query($query)or die(mysql_error());
			if($result) {
				return '<div class="alert alert-success">Document Upload was Successfull</div>';
			}
		}
	}
	
	function addAsset($post,$file,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$asset_name		= $this->mysql_prepare_value($post['asset_name']);
			$serial		    = $this->mysql_prepare_value($post['serial']);
			$desc			= $this->mysql_prepare_value($post['desc']);
			$date_bought	= $this->mysql_prepare_value($post['date_bought']);
			$amount			= $this->mysql_prepare_value($post['amount']);
			$life_sapn		= $this->mysql_prepare_value($post['life_sapn']);
			$asset_alert	= $this->mysql_prepare_value($post['asset_alert']);
			$time = time();
			
			//check if serial already exist fopr another asset
			$checkSerial = "select asset_serial from assets where asset_serial='$serial'";
			$checkSerial_res = mysql_query($checkSerial)or die(mysql_error());
			$countRow = mysql_num_rows($checkSerial_res);
			if($countRow>0) {
				return '<div class="alert alert-danger"><i class="fa fa-ban"></i> Serial already exists for another Asset.</div>';
			}

			$query = "insert into assets values('','$serial','$asset_name','$desc','','0','0','0','0','$date_bought','$amount','$life_sapn','$asset_alert',";
			
			if($file['asset_img']['size'] !=0){
				//*******check if upload file is an image file*******//
				// array of valid extensions
				$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
				// get extension of the uploaded file
				$fileExtension = strrchr($file['asset_img']['name'], ".");
				if (in_array($fileExtension, $validExtensions)) {
					$surfix = time();
					//resize profile picture
					$manipulator = new ImageManipulator($file['asset_img']['tmp_name']);
					// resizing to 1170x711
					$newImage = $manipulator->resample(215, 215);
					$target_path = "asset_img/";
					$target_path = $target_path . basename($file['asset_img']['name']);
					$manipulator->save($target_path);
					$imagePath = $target_path;
					//convert to binary
					$img2Binary = $this->loadImage($imagePath);
					
					
					$query .= "'yes','$img2Binary',";
							
				}else {
					return "<div class=\"alert alert-danger\">The file you tried to upload is not a valid Image</div>";
				}
			}else {
					$query .= "'no','',";
			}
			
			$query .= "'".$_SESSION['userid']."','$time')";			
			$result = mysql_query($query)or die(mysql_error());
			if($result) {
				unlink($imagePath);
				return '<div class="alert alert-success">Asset Added to Successfully</div>';
			}
		}
	}
	
	function addGenAsset($post,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$serial		    = $this->mysql_prepare_value($post['serial']);
			$rating			= $this->mysql_prepare_value($post['rating']);
			$capacity		= $this->mysql_prepare_value($post['capacity']);
			$running_hrs	= $this->mysql_prepare_value($post['running_hrs']);
			$service_hrs	= $this->mysql_prepare_value($post['service_hrs']);
			$replace_hrs	= $this->mysql_prepare_value($post['replace_hrs']);
			$date_bought	= $this->mysql_prepare_value($post['date_bought']);
			$amount			= $this->mysql_prepare_value($post['amount']);
			$time = time();
			
			//check if serial already exist fopr another asset
			$checkSerial = "select asset_serial from assets where asset_serial='$serial'";
			$checkSerial_res = mysql_query($checkSerial)or die(mysql_error());
			$countRow = mysql_num_rows($checkSerial_res);
			if($countRow>0) {
				return '<div class="alert alert-danger"><i class="fa fa-ban"></i> Serial already exists for another Gen.</div>';
			}

			$query = "insert into assets values('','$serial','Generator','','$rating','$capacity','$running_hrs','$service_hrs','$replace_hrs','$date_bought','$amount','','','','','".$_SESSION['userid']."','$time')";			
			$result = mysql_query($query)or die(mysql_error());
			if($result) {
				return '<div class="alert alert-success">Generator Added Successfully</div>';
			}
		}
	}
	
	function moveAsset($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$aid			= $this->mysql_prepare_value($post['aid']);
			$destination	= $this->mysql_prepare_value($post['destination']);
			$desc			= $this->mysql_prepare_value($post['desc']);
			$date_moved	    = strtotime($this->mysql_prepare_value($post['date_moved']));
			$time = time();
	
			$query = "insert into asset_history values('','$aid','$destination','$desc','$date_moved','".$_SESSION['userid']."','$time')";			
			$result = mysql_query($query)or die(mysql_error());
			if($result) {
				//attach this asset to a site if it was move to a site
				if($destination!="Office" && $destination!="Warehouse" && $destination!="Others") {
					$queryI = "insert into site_asset values('','$aid','$destination','$time')";			
					$resultI = mysql_query($queryI)or die(mysql_error());
					if($resultI) {
						return '<div class="alert alert-success">Asset Moved Successfully</div>';
					}
				}
				
			}
		}
	}
	
	function addExpenses($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$site		= $this->mysql_prepare_value($post['site']);
			$type		= $this->mysql_prepare_value($post['type']);
			$exdate		= $this->mysql_prepare_value($post['exdate']);
			$desc		= $this->mysql_prepare_value($post['desc']);
			$amount		= $this->mysql_prepare_value($post['amount']);
			$issued_to	= $this->mysql_prepare_value($post['issued_to']);
			$time = time();

			$query_I = "insert into expenses values('','$site','$type','$exdate','$desc','$amount','$issued_to','".$_SESSION['userid']."','$time')";			
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success">Expense Added</div>';
			}
		}
	}
	
	function updateExpenses($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$exid		= $this->mysql_prepare_value($post['exid']);
			$site		= $this->mysql_prepare_value($post['site']);
			$type		= $this->mysql_prepare_value($post['type']);
			$exdate		= $this->mysql_prepare_value($post['exdate']);
			$desc		= $this->mysql_prepare_value($post['desc']);
			$amount		= $this->mysql_prepare_value($post['amount']);
			$issued_to	= $this->mysql_prepare_value($post['issued_to']);
			

			$query_I = "update expenses set site_id = '$site',ex_type='$type',ex_date='$exdate',ex_desc='$desc',ex_amount='$amount',issued_to='$issued_to' where expense_id = '$exid'";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success">Expense Updated</div>';
			}
		}
	}

	
	function updateITPs($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$itpID				= $this->mysql_prepare_value($post['itpID']);
			$client				= $this->mysql_prepare_value($post['client']);
			$siteID		    	= $this->mysql_prepare_value($post['site']);
			$anniversary		= $this->mysql_prepare_value($post['anniversary']);
			$term				= $this->mysql_prepare_value($post['term']);
			

			$query_I = "update itp set client = '$client',site_id='$siteID',anniversary='$anniversary',commercial_terms='$term' where id = '$itpID'";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i>ITPs Updated</div>';
			}
		}
	}
	
	function updatePO($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$poID				= $this->mysql_prepare_value($post['poID']);
			$vendor		    	= $this->mysql_prepare_value($post['vendor']);
			$address			= $this->mysql_prepare_value($post['address']);
			$odate				= $this->mysql_prepare_value($post['odate']);
			$terms				= $this->mysql_prepare_value($post['term']);
			$delivery_status	= $this->mysql_prepare_value($post['delivery_status']);
			$billing_status		= $this->mysql_prepare_value($post['billing_status']);
			$ddate				= $this->mysql_prepare_value($post['ddate']);
			$comment			= $this->mysql_prepare_value($post['comment']);
			

			$query_I = "update purchase_order set vendor_id = '$vendor',
						address='$address',
						order_date ='$odate',
						payment_terms='$terms', 
						comments ='$comment', 
						delivery_date='$ddate', 
						delivery_status='$delivery_status', 
						billing_status='$billing_status' 
						where po_id = '$poID'";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success">Purchase Order Updated</div>';
			}
		}
	}
	
	function updatePO_item($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$itemID			= $this->mysql_prepare_value($post['itemid']);
			$item_name	    = $this->mysql_prepare_value($post['item_name']);
			$desc			= $this->mysql_prepare_value($post['desc']);
			$qty			= $this->mysql_prepare_value($post['qty']);
			$cost			= $this->mysql_prepare_value($post['cost']);
			$total			= $this->mysql_prepare_value($post['total']);
			

			$query_I = "update po_items set item_name = '$item_name',
						item_desc = '$desc',
						qty_ordered = '$qty',
						cost = '$cost', 
						total ='$total' 
						where item_id = '$itemID'";					
			$result_I = mysql_query($query_I)or die(mysql_error());
			if($result_I) {
				return '<div class="alert alert-success">Item Updated</div>';
			}
		}
	}
	
	function updateAsset($post,$file,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$aid			= $this->mysql_prepare_value($post['aid']);
			$asset_name		= $this->mysql_prepare_value($post['asset_name']);
			$serial		    = $this->mysql_prepare_value($post['serial']);
			$desc			= $this->mysql_prepare_value($post['desc']);
			$time = time();
			
			//check if serial already exist fopr another asset
			$checkSerial = "select asset_id, asset_serial from assets where asset_id != '$aid' and asset_serial='$serial'";
			$checkSerial_res = mysql_query($checkSerial)or die(mysql_error());
			$countRow = mysql_num_rows($checkSerial_res);
			
			if($countRow>0) {
				return '<div class="alert alert-danger"><i class="fa fa-ban"></i> Serial already exists for another Asset. '.$countRow.'</div>';
			}
			

			$query = "update assets set asset_serial = '$serial', asset_name = '$asset_name', asset_desc = '$desc'";
			
			if($file['asset_img']['size'] !=0){
				//*******check if upload file is an image file*******//
				// array of valid extensions
				$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
				// get extension of the uploaded file
				$fileExtension = strrchr($file['asset_img']['name'], ".");
				if (in_array($fileExtension, $validExtensions)) {
					$surfix = time();
					//resize profile picture
					$manipulator = new ImageManipulator($file['asset_img']['tmp_name']);
					// resizing to 1170x711
					$newImage = $manipulator->resample(215, 215);
					$target_path = "asset_img/";
					$target_path = $target_path . basename($file['asset_img']['name']);
					$manipulator->save($target_path);
					$imagePath = $target_path;
					//convert to binary
					$img2Binary = $this->loadImage($imagePath);
					
					
					$query .= ", has_img = 'yes', asset_img = '$img2Binary'";
							
				}else {
					return "<div class=\"alert alert-danger\">The file you tried to upload is not a valid Image</div>";
				}
			}
			
			$query .= "where asset_id = '$aid'";					
			$result = mysql_query($query)or die(mysql_error());
			if($result) {
				return '<div class="alert alert-success">Asset Updated. If you updated the Asset image, it will reflect next time you open this page.</div>';
			}
		}
	}
	
	function updateAssetMovement($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {

			$hid			= $this->mysql_prepare_value($post['hid']);
			$aid			= $this->mysql_prepare_value($post['aid']);
			$destination	= $this->mysql_prepare_value($post['destination']);
			$desc			= $this->mysql_prepare_value($post['desc']);
			$date_moved	    = strtotime($this->mysql_prepare_value($post['date_moved']));
			

			$query = "update asset_history set asset_id = '$aid',
						destination = '$destination',
						move_desc = '$desc',
						date_moved = '$date_moved'
						where history_id = '$hid'";					
			$result = mysql_query($query)or die(mysql_error());
			if($result) {
				return '<div class="alert alert-success">Asset Movement Updated</div>';
			}
		}
	}
	
	function getallUsers() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM app_users ORDER BY id Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   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 = mysql_fetch_object($result)) {
				$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\"><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 getCustomerTypes() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM customer_type ORDER BY type_name";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   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\">Type Name</th>
					<th class=\"tbli_headder\">Kilowatts </th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ctype = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $ctype->id;
				$tname 		= $ctype->type_name;
				$kw 		= $ctype->kilowatts;
								
				echo"<tr>
                        <td>$sn</td>
                        <td>$tname</td>
                        <td>$kw kw</td>
                        <td>
							<a href=\"".$_SERVER['PHP_SELF']."?tid=$id&ac=ed\"><span class=\"add-on small-size\">Edit</span></a> | 
							<a href=\"".$_SERVER['PHP_SELF']."?tid=$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 Type Added</div>';   
	   }
	}
	
	
	function getNOCUsers() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM app_users where user_level = 'NOC Team' ORDER BY id Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   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 = mysql_fetch_object($result)) {
				$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\"><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 getall_supervisor() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM app_users where user_level='Supervisor' ORDER BY id Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   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\">Region </th>
					<th class=\"tbli_headder\">ID </th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($supervisor = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $supervisor->id;
				$name 		= $supervisor->name;
				$phone 		= $supervisor->phone;
				$region 	= $supervisor->region;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$name</td>
                        <td>$phone </td>
                        <td>$region</td>
                        <td>$id</td>
                        <td>
							<div class=\"btn-group pull-right\">
                                <button class=\"btn btn-info dropdown-toggle\" data-toggle=\"dropdown\"> Select <i class=\"fa fa-angle-down\"></i>
                                </button>
                                <ul class=\"dropdown-menu pull-right\">
                                    <li><a href=\"#\"><span class=\"add-on small-size\">Edit</span></a></li>
                                    <li><a href=\"#\"><span class=\"add-on small-size\">Delete</span></a></li>
                                </ul>
                            </div>
						</td>
                     </tr>";
				
			 }
			 // print the navigation link
			echo "</tbody> </table>";
		}else{
			echo'<div class="alert alert-danger">No Supervisor Yet</div>';   
	   }
	}
	
	function getall_vendors() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM vendors ORDER BY id Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Name</th>
					<th class=\"tbli_headder\">State </th>
					<th class=\"tbli_headder\">Region </th>
					<th class=\"tbli_headder\"><div data-toggle=\"tooltip\" title=\"Site Quantity\">Qty</div></th>
					<th class=\"tbli_headder\">Contact</th>
					<th class=\"tbli_headder\">Phone</th>
					<th class=\"tbli_headder\">ID</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($vendor = mysql_fetch_object($result)) {
				$sn += 1;
				$id 		= $vendor->id;
				$name 		= $vendor->name;
				$state 		= $vendor->state;
				$region		= $vendor->region;
				$qty		= $vendor->site_qty;
				$city		= $vendor->city;
				$email 		= $vendor->email;
				$contact 	= $vendor->contact;
				$phone 		= $vendor->phone;
				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$name</td>
                        <td><div data-toggle=\"tooltip\" title=\"City - $city\">$state</div></td>
                        <td>$region</td>
                        <td>$qty</td>
                        <td><div data-toggle=\"tooltip\" title=\"Email - $email\">$contact</div></td>
                        <td>$phone</td>
                        <td>$id</td>
                        <td>
							<div class=\"btn-group pull-right\">
                                <button class=\"btn btn-info dropdown-toggle\" data-toggle=\"dropdown\"> Select <i class=\"fa fa-angle-down\"></i>
                                </button>
                                <ul class=\"dropdown-menu pull-right\">
                                    <li><a href=\"edit_vendor.php?vid=$id\"><span class=\"add-on small-size\">Edit</span></a></li>
                                    <li><a href=\"".$_SERVER['PHP_SELF']."?vid=$id&ac=del\"  onclick=\"return confirm('Are you sure you want to delete this?');\"><span class=\"add-on small-size\">Delete</span></a></li>
                                </ul>
                            </div>
						</td>
                     </tr>";
				
			 }
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Vendor Yet</div>';   
	   }
	}
	
	function getall_ITPs() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM itp ORDER BY id Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Client</th>
					<th class=\"tbli_headder\">Site ID</th>
					<th class=\"tbli_headder\">Anniversary </th>
					<th class=\"tbli_headder\"><div data-toggle=\"tooltip\" title=\"Commercial Terms\">Terms</div></th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($itp = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $itp->id;
				$client			= $itp->client;
				$siteID 		= $itp->site_id;
				$anniversary 	= strtotime($itp->anniversary);
				$term			= $itp->commercial_terms;
				
				$siteInfo = $this->getSiteInfo($siteID);
				$site_id = $siteInfo->site_id;
				$sitebct_id = $siteInfo->bct_id;
				
				$anniDate = date("d-M-Y",$anniversary);
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$client</td>
                        <td><div data-toggle=\"tooltip\" title=\"BCTID - $sitebct_id\">$site_id</div></td>
                        <td>$anniDate</td>
                        <td>$term</td>
                        <td>
							<div class=\"btn-group pull-right\">
                                <button class=\"btn btn-info dropdown-toggle\" data-toggle=\"dropdown\"> Select <i class=\"fa fa-angle-down\"></i>
                                </button>
                                <ul class=\"dropdown-menu pull-right\">
                                    <li><a href=\"".$_SERVER['PHP_SELF']."?id=$id&ac=ed\"><span class=\"add-on small-size\">Edit</span></a></li>
                                    <li><a href=\"".$_SERVER['PHP_SELF']."?id=$id&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\"><span class=\"add-on small-size\">Delete</span></a></li>
                                </ul>
                            </div>
					  </td>
                     </tr>";
				
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No ITPs Yet</div>';   
	   }
	}
	
	function getBatch() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supply_batch ORDER BY batch_id Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Batch Name</th>
					<th class=\"tbli_headder\"># Sites</th>
					<th class=\"tbli_headder\">Supply Cost</th>
					<th class=\"tbli_headder\">Status</th>
					<th class=\"tbli_headder\">Date Created</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($batch = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 		= $batch->batch_id;
				$bname		= $batch->batch_name;
				$cost		= $batch->supply_cost;
				$userid 	= $batch->userid;
				$status 	= $batch->status;
				$date 		= date("d-M-Y H:ma",$batch->time_created);
				
				$userInfo = $this->getUserInfo($userid);
				$uname = $userInfo->name;
				
				//count supply batche sites under this batch
				$BatchSites = $this->countSupplyBatchSites($id);				
			
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$bname</td>
                        <td>";
						if($_SESSION['level']=="Supervisor") {
							echo $BatchSites;
						}else {
							echo "-";
						}
						echo"</td>
                        <td>$cost per Lit.</td>
                        <td>";
						if($_SESSION['level']=="Supervisor") {
							echo"<a href=\"".$_SERVER['PHP_SELF']."?bid=$id&st=$rand&ty=";
							if($status=="Open") {echo"1";}else{echo"0";}
							echo"\" class=\"label label-";
							if($status=="Open") {echo"success";}else{echo"danger";}
							echo"\" onclick =\"return confirm('Are you sure you want to change this status?')\">$status</a>";
						} else {
							echo"<span class=\"label label-success\">$status</span>";
						}
						echo"</td>
                        <td>$date</td>
                        <td>";
							if($_SESSION['level']=="Supervisor") {
								echo"<a href=\"batchsites.php?bid=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-plus\"></i></span></a> |
								<a href=\"".$_SERVER['PHP_SELF']."?bid=$id&ed=$rand\"><span class=\"add-on small-size\"><i class=\"fa fa-edit\"></i></span></a>";
								if($BatchSites==0) { 
									echo" | <a href=\"".$_SERVER['PHP_SELF']."?bid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><span class=\"add-on small-size\"><i class=\"fa fa-trash-o\"></i></span></a>"; 
								}
							} else {
								echo"<a href=\"engr_sites_supply.php?bid=$id\"><span class=\"add-on small-size\"><i class=\"fa fa-folder-open\"></i></span></a>";
							}
					  echo"</td>
                     </tr>";
				
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Batch Yet</div>';   
	   }
	}
	
	function getBatchSites($batchID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supply_batch_site where batch_id = '$batchID' ORDER BY id Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Site</th>
					<th class=\"tbli_headder\">Report Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($batch = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 		= $batch->id;
				$batchID	= $batch->batch_id;
				$siteID		= $batch->site_id;
				$userid 	= $batch->userid;
				$status		= $batch->status;
				
				
				$siteInfo = $this->getSiteInfo($siteID);
				$site_id = $siteInfo->site_id;			
			
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"view_supply.php?siteID=$siteID&id=$id&bid=$batchID&del=$rand\">$site_id</a></td>
                        <td><span class=\"label ";
						if($status=="not reported") { echo "label-danger";}else{echo "label-success";}						
						echo"\">".strtoupper($status)."</span></td>
                        <td>";
							if($status=="not reported") { 
								echo"<a href=\"".$_SERVER['PHP_SELF']."?id=$id&bid=$batchID&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><span class=\"add-on small-size\"><i class=\"fa fa-trash-o\"></i></span></a>"; 
							}else {
								echo "N/A";
							}
					  echo"</td>
                     </tr>";
				
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Sub Batch Yet</div>';   
	   }
	}
	
	function getSupplyBatches() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM supply_batch ORDER BY time_created Desc";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Batch</th>
					<th class=\"tbli_headder\">Sub Batches</th>
					<th class=\"tbli_headder\">Time Created </th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($batch = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $batch->batch_id;
				$batchName		= $batch->batch_name;
				$timeSaved	 	= date("M d, Y; H:ma",$batch->time_created);
				
				$siteInfo = $this->getSiteInfo($siteID);
				$site_id = $siteInfo->site_id;
				$sitebct_id = $siteInfo->bct_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$client</td>
                        <td><div data-toggle=\"tooltip\" title=\"BCTID - $sitebct_id\">$site_id</div></td>
                        <td>$anniDate</td>
                        <td>
							<div class=\"btn-group pull-right\">
                                <button class=\"btn btn-info dropdown-toggle\" data-toggle=\"dropdown\"> Select <i class=\"fa fa-angle-down\"></i>
                                </button>
                                <ul class=\"dropdown-menu pull-right\">
                                    <li><a href=\"".$_SERVER['PHP_SELF']."?id=$id&ac=ed\"><span class=\"add-on small-size\">Edit</span></a></li>
                                    <li><a href=\"".$_SERVER['PHP_SELF']."?id=$id&ac=del\" onclick=\"return confirm('Are you sure you want to delete this?');\"><span class=\"add-on small-size\">Delete</span></a></li>
                                </ul>
                            </div>
					  </td>
                     </tr>";
				
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No ITPs Yet</div>';   
	   }
	}
	
	function getPurchaseOrderWorth($poid) {
		$this->connect_db();
		$query = mysql_query("select sum(total) as worth from po_items where po_id = '$poid'");
		$Data = mysql_fetch_object($query);
		$worth = $Data->worth;
		
		return $worth;
	}
	
	function getall_POs() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM purchase_order ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-hover table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">Ref #</th>
					<th class=\"tbli_headder\">Order Date</th>
					<th class=\"tbli_headder\">Vendor </th>
					<th class=\"tbli_headder\">Delivery</th>
					<th class=\"tbli_headder\">Billing</th>
					<th class=\"tbli_headder\">Amounts</th>
					<th class=\"tbli_headder\">Delivery Date</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $rand = rand();
			 while($po = mysql_fetch_object($result)) {
				$sn += 1;
				$poid 			= $po->po_id;
				$poref			= $po->po_ref;
				$vendor			= $po->vendor_id;
				$odate			= date("d M,Y",strtotime($po->order_date));
				$ddate			= $po->delivery_date;
				$delivery		= $po->delivery_status;
				$billing		= $po->billing_status;
				
				$vendorInfo = $this->getVendorInfo($vendor);
				$vendorName = $vendorInfo->name;
				
				//get Purchase Order Worth
				$orderWorth = $this->getPurchaseOrderWorth($poid);
				
				echo"<tr>
                        <td>PO-$poref</td>
                        <td>$odate</td>
                        <td>$vendorName</td>
                        <td><div class=\"btn btn-sm ";
						if($delivery=="Not Received"){echo"btn-danger";}elseif($delivery=="Partially Received"){echo"btn-warning";}elseif($delivery=="Received"){echo"btn-success";}
						echo"\">$delivery</div></td>
                        <td><div class=\"btn btn-sm ";
						if($billing=="Not Invoiced"){echo"btn-danger";}elseif($billing=="Invoiced"){echo"btn-success";}elseif($billing=="Cancelled"){echo"btn-info";}
						echo"\">$billing</></td>
                        <td>N".number_format($orderWorth,2)."</td>
                        <td>";
							if($ddate=="0000-00-00"){echo"-";}else{echo date("d M,Y",strtotime($po->delivery_date));}
						echo"</td>
                        <td>
							<a href=\"po_item.php?poid=$poid&ac=$rand\" data-toggle=\"tooltip\" title=\"Add Item\"><i class=\"fa fa-plus\"></i></a>&nbsp;&nbsp; 
							<a href=\"order.php?id=$poid&ac=$rand\" data-toggle=\"tooltip\" title=\"Update PO\"><i class=\"fa fa-edit\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?id=$poid&del=$rand\" data-toggle=\"tooltip\" title=\"Delete PO\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
				
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No purchase order yet</div>';   
	   }
	}
	
	function getPOsbyStatus($colunm,$status) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM purchase_order where $colunm = '$status' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-hover table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">Ref #</th>
					<th class=\"tbli_headder\">Order Date</th>
					<th class=\"tbli_headder\">Vendor </th>
					<th class=\"tbli_headder\">Status</th>
					<th class=\"tbli_headder\">Amounts</th>
					<th class=\"tbli_headder\">Delivery Date</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			  $rand = rand();
			 while($po = mysql_fetch_object($result)) {
				$sn += 1;
				$poid 			= $po->po_id;
				$poref			= $po->po_ref;
				$vendor			= $po->vendor_id;
				$odate			= date("d M,Y",strtotime($po->order_date));
				$ddate			= $po->delivery_date;
				$delivery		= $po->delivery_status;
				$billing		= $po->billing_status;
				
				$vendorInfo = $this->getVendorInfo($vendor);
				$vendorName = $vendorInfo->name;
				
				//get Purchase Order Worth
				$orderWorth = $this->getPurchaseOrderWorth($poid);
				
				echo"<tr>
                        <td>PO-$poref</td>
                        <td>$odate</td>
                        <td>$vendorName</td>
                        <td>";
						if($colunm=="delivery_status"){echo $delivery;}elseif($colunm=="billing_status"){echo $billing;}
						echo"</td>
                        <td>N".number_format($orderWorth,2)."</td>
                        <td>";
							if($ddate=="0000-00-00"){echo"-";}else{echo date("d M,Y",strtotime($po->delivery_date));}
						echo"</td>
                        <td>
							<a href=\"po_item.php?poid=$poid&ac=$rand\" data-toggle=\"tooltip\" title=\"Add Item\"><i class=\"fa fa-plus\"></i></a>&nbsp;&nbsp; 
							<a href=\"order.php?id=$poid&ac=$rand\" data-toggle=\"tooltip\" title=\"Update PO\"><i class=\"fa fa-edit\"></i></a>&nbsp;&nbsp; 
							<a href=\"".$_SERVER['PHP_SELF']."?id=$poid&del=$rand\" data-toggle=\"tooltip\" title=\"Delete PO\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
				
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No purchase order '.$status.'</div>';   
	   }
	}
	
	
	
	function getall_PO_item($poid) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM po_items where po_id = '$poid' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			$rand = rand();
			$totalCost = 0;
			while($item = mysql_fetch_object($result)) {
				$sn += 1;
				$itemid		= $item->item_id;
				$itemName	= $item->item_name;
				$desc		= $item->item_desc;
				$qty		= $item->qty_ordered;
				$cost		= $item->cost;
				$total		= $item->total;
				
				echo"<tr>
                        <td>$itemName</td>
                        <td>$desc</td>
                        <td>$qty</td>
                        <td>N".number_format($cost,2)."</td>
                        <td>N".number_format($total,2)."</td>
                        <td>
							<a href=\"".$_SERVER['PHP_SELF']."?poid=$poid&id=$itemid&ed=$rand\" data-toggle=\"tooltip\" title=\"Update\"><i class=\"fa fa-edit\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?poid=$poid&id=$itemid&del=$rand\" data-toggle=\"tooltip\" title=\"Delete\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
				$totalCost +=$total;
			}
			echo"<tr>
					<td colspan=\"4\" align=\"right\"><strong>Total</strong></td>
					<td><strong>N".number_format($totalCost,2)."</strong></td>
					<td></td>
				</tr>";
		}
	}
	
	function getAsset() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM assets where asset_name != 'Generator' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			$rand = rand();
			$totalCost = 0;
			$sn = 0;
				echo"<table id=\"example\" class=\"table table-bordered table-striped\">
					<thead>
						<tr>
						<th class=\"tbli_headder\">#</th>
						<th class=\"tbli_headder\" width=\"5%\"></th>
						<th class=\"tbli_headder\">Asset Serial</th>
						<th class=\"tbli_headder\">Asset Name</th>
						<th>Action</th>
						</tr>
					</thead>
					<tbody>";
			while($asset = mysql_fetch_object($result)) {
				$sn += 1;
				$assetid	= $asset->asset_id;
				$serial		= $asset->asset_serial;
				$assetName	= $asset->asset_name;
				$desc		= $asset->asset_desc;
				$hasImg		= $asset->has_img;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>
						<div class=\"imgLiquidFill imgLiquid\" style=\"width:50px; height:50px;\">";
							if($hasImg=="yes") {
								echo"<img src=\"asset-images.php?id=$assetid\" alt=\"$assetName\" title=\"$assetName\">";
							}else {
								echo"<img src=\"assets/images/asset.jpg\" alt=\"$assetName\">";
							}
				   echo"</div>
						</td>
                        <td>$serial</td>
                        <td>$assetName</td>
                        <td>
							<a href=\"asset_details.php?aid=$assetid\" data-toggle=\"tooltip\" title=\"Details\"><i class=\"fa fa-folder\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?id=$assetid&ed=$rand\" data-toggle=\"tooltip\" title=\"Update\"><i class=\"fa fa-edit\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?id=$assetid&im=$rand\" data-toggle=\"tooltip\" title=\"Remove Image\" onclick=\"return confirm('Are you sure?');\"><i class=\"fa fa-times\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?id=$assetid&del=$rand\" data-toggle=\"tooltip\" title=\"Delete\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
			}
			echo"</tbody></table>";
		}else{
			echo"<div class=\"alert alert-danger\">No Asset Recorded Yet</div>";
		}
	}
	
	function getGenAsset() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM assets where asset_name = 'Generator' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			$rand = rand();
			$totalCost = 0;
			$sn = 0;
				echo"<table id=\"example\" class=\"table table-bordered table-striped\">
					<thead>
						<tr>
						<th class=\"tbli_headder\">#</th>
						<th class=\"tbli_headder\">Asset Serial</th>
						<th class=\"tbli_headder\">Power Rating</th>
						<th class=\"tbli_headder\">Capacity</th>
						<th class=\"tbli_headder\">Expected hours</th>
						<th>Action</th>
						</tr>
					</thead>
					<tbody>";
			while($asset = mysql_fetch_object($result)) {
				$sn += 1;
				$assetid	= $asset->asset_id;
				$serial		= $asset->asset_serial;
				$power_rating = $asset->power_rating;
				$capacity	= $asset->capacity;
				$hrs		= number_format($asset->total_hours);
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$serial</td>
                        <td>$power_rating KW</td>
                        <td>$capacity KVA</td>
                        <td>$hrs Hours</td>
                        <td>
							<a href=\"".$_SERVER['PHP_SELF']."?id=$assetid&ed=$rand\" data-toggle=\"tooltip\" title=\"Update\"><i class=\"fa fa-edit\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?id=$assetid&del=$rand\" data-toggle=\"tooltip\" title=\"Delete\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
			}
			echo"</tbody></table>";
		}else{
			echo"<div class=\"alert alert-danger\">No Gen Asset Added Yet</div>";
		}
	}
	
	function getAssetHistory($aid) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM asset_history where asset_id = '$aid' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			$rand = rand();
			$totalCost = 0;
			$sn = 0;
				echo"<table id=\"example\" class=\"table table-bordered table-striped\">
					<thead>
						<tr>
						<th class=\"tbli_headder\">#</th>
						<th class=\"tbli_headder\">Date Moved</th>
						<th class=\"tbli_headder\">Destination</th>
						<th class=\"tbli_headder\">Description </th>
						<th>Action</th>
						</tr>
					</thead>
					<tbody>";
			while($history = mysql_fetch_object($result)) {
				$sn += 1;
				$historyid		= $history->history_id;
				$assetid		= $history->asset_id;
				$destination	= $history->destination;
				$move_desc		= $history->move_desc;
				$dateMoved		= date("d M, Y",$history->date_moved);
				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$dateMoved</td>
                        <td>";
							if($destination=="Office" || $destination=="Warehouse" || $destination=="Others"){
								echo $destination;								
							}else {
								//get site Info
								$siteData = $this->getSiteInfo($destination);
								echo $siteData->site_id;
							}
						echo"</td>
                        <td>$move_desc</td>
                        <td>
							<a href=\"".$_SERVER['PHP_SELF']."?aid=$aid&id=$historyid&ed=$rand\" data-toggle=\"tooltip\" title=\"Update\"><i class=\"fa fa-edit\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?aid=$aid&id=$historyid&del=$rand\" data-toggle=\"tooltip\" title=\"Delete\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
			}
			echo"</tbody></table>";
		}else{
			echo"<div class=\"alert alert-danger\">Asset Not Yet Moved</div>";
		}
	}
	
	function getAssetDocs($aid) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM asset_doc where asset_id = '$aid' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			$rand = rand();
			$totalCost = 0;
			$sn = 0;
				echo"<table id=\"example2\" class=\"table table-bordered table-striped\">
					<thead>
						<tr>
						<th class=\"tbli_headder\">#</th>
						<th class=\"tbli_headder\">Docment Name</th>
						<th class=\"tbli_headder\">Description</th>
						<th>Action</th>
						</tr>
					</thead>
					<tbody>";
			while($doc = mysql_fetch_object($result)) {
				$sn += 1;
				$docid			= $doc->history_id;
				$doc_name		= $doc->doc_name;
				$description	= $doc->description;
				$doc_path		= $doc->doc_path;
				
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$doc_name</td>
                        <td>$description</td>
                        <td>
							<a href=\"$doc_path\" target=\"_blank\" data-toggle=\"tooltip\" title=\"download Docment\"><i class=\"fa fa-download\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?aid=$aid&del=$rand\" data-toggle=\"tooltip\" title=\"Delete\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
			}
			echo"</tbody></table>";
		}else{
			echo"<div class=\"alert alert-danger\">No Asset Document</div>";
		}
	}
	
	function getSiteDocs($siteid=null) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_doc ";
		if($siteid!=null) {
			$sql .= "where site_id = '$siteid' ";
		}
		$sql .= "ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			$rand = rand();
			$sn = 0;
				echo"<table id=\"example2\" class=\"table table-bordered table-striped\">
					<thead>
						<tr>
						<th class=\"tbli_headder\">#</th>";
						if($siteid==null) {
							echo"<th class=\"tbli_headder\">Site ID</th>";
						}
						echo"<th class=\"tbli_headder\">Description</th>
						<th>Action</th>
						</tr>
					</thead>
					<tbody>";
			while($doc = mysql_fetch_object($result)) {
				$sn += 1;
				$docid			= $doc->doc_id;
				$sID			= $doc->site_id;
				$description	= $doc->doc_title;
				$doc_path		= $doc->doc_file;
				
				//get site data
				$siteData = $this->getSiteInfo($sID);
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>";
						if($siteid==null) {
							echo"<td>$site_id</td>";
						}
                       echo"<td>$description</td>
                        <td>
							<a href=\"$doc_path\" target=\"_blank\" data-toggle=\"tooltip\" title=\"download Docment\"><i class=\"fa fa-download\"></i></a>&nbsp;&nbsp;
							<a href=\"".$_SERVER['PHP_SELF']."?did=$docid&del=$rand";
							if($siteid!=null) {
								echo"&siteID=$sID";
							}
							echo"\" data-toggle=\"tooltip\" title=\"Delete\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash-o\"></i></a>
						</td>
                     </tr>";
			}
			echo"</tbody></table>";
		}else{
			echo"<div class=\"alert alert-danger\">No Site Documents</div>";
		}
	}
	
	function getall_expenses() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM expenses ORDER BY expense_id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Site ID</th>
					<th class=\"tbli_headder\">Date </th>
					<th class=\"tbli_headder\">Amount </th>
					<th class=\"tbli_headder\">Description </th>
					<th class=\"tbli_headder\">Issued To</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($expenses = mysql_fetch_object($result)) {
				$rand = rand();
				$sn += 1;
				$id 			= $expenses->expense_id;
				$siteID 		= $expenses->site_id;
				$ex_date		= date("d M, Y",strtotime($expenses->ex_date));
				$ex_amount		= number_format($expenses->ex_amount,2);
				$ex_desc		= $expenses->ex_desc;
				$issued_to		= $expenses->issued_to;
				
				$siteInfo = $this->getSiteInfo($siteID);
				$site_id = $siteInfo->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$ex_date</td>
                        <td>₦$ex_amount</td>
                        <td>$ex_desc</td>
                        <td>$issued_to</td>
                        <td>
						<a href=\"".$_SERVER['PHP_SELF']."?id=$id&ed=$rand\"><span class=\"add-on small-size\">Edit</span></a> | 
                         <a href=\"".$_SERVER['PHP_SELF']."?id=$id&del=$rand\" 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 Expenses Yet</div>';   
	   }
	}
	
	function getExpenses($period) {	
		$this->connect_db();
		
		$today = date("Y-m-d",time());
		$sunday = date_create()->modify('last Sunday');
		$month = date_create()->modify('first day of this month');
		
		$weekStart = date_format($sunday,"Y-m-d");
		$monthStart = date_format($month,"Y-m-d");
		
		if($period=="today") {
			$sql = "select * from expenses where ex_date = '$today'";
		}elseif($period=="week") {		
			$sql = "select * from expenses where ex_date between '$weekStart' and '$today'";			
		}elseif($period=="month"){
			$sql = "select * from expenses where ex_date between '$monthStart' and '$today'";
		}
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   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\">Site ID</th>
					<th class=\"tbli_headder\">Date </th>
					<th class=\"tbli_headder\">Amount </th>
					<th class=\"tbli_headder\">Description </th>
					<th class=\"tbli_headder\">Issued To</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $tamount = 0;
			 while($expenses = mysql_fetch_object($result)) {
				$rand = rand();
				$sn += 1;
				$id 			= $expenses->expense_id;
				$siteID 		= $expenses->site_id;
				$ex_date		= date("d M, Y",strtotime($expenses->ex_date));
				$ex_amount		= $expenses->ex_amount;
				$ex_desc		= $expenses->ex_desc;
				$issued_to		= $expenses->issued_to;
				
				$siteInfo = $this->getSiteInfo($siteID);
				$site_id = $siteInfo->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$ex_date</td>
                        <td>₦".number_format($ex_amount,2)."</td>
                        <td>$ex_desc</td>
                        <td>$issued_to</td>
                     </tr>";
				$tamount += $ex_amount;
			 }

			// print the navigation link
			echo "<tr>
					<td colspan=\"3\" align=\"right\"><strong>Total</strong></td>
					<td><strong>₦".number_format($tamount,2)."</strong></td>
					<td colspan=\"2\"></td>
				</tr>
				</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">';
				if($period=="today") {
				echo "No Expenses for today yet";
				}elseif($period=="week") {		
					echo "No Expenses for this week yet";			
				}elseif($period=="month"){
					echo "No Expenses for this month yet";
				}
			echo'</div>';   
	   }
	}
	
	function getExpensesDash() {	
		$this->connect_db();
		
		$sql = "select * from expenses order by ex_date desc Limit 0,4";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\">
			   <thead>
					<tr>
					<th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Site ID</th>
					<th class=\"tbli_headder\">expense date</th>
					<th class=\"tbli_headder\">Amount</th>
					<th class=\"tbli_headder\">Description </th>
					<th class=\"tbli_headder\">Issued To</th>
					</tr>
				</thead>
				<tbody>";
			 $sn = 0;
			 $tamount = 0;
			 while($expenses = mysql_fetch_object($result)) {
				$rand = rand();
				$sn += 1;
				$id 			= $expenses->expense_id;
				$siteID			= $expenses->site_id;
				$ex_date		= date("d M, Y",strtotime($expenses->ex_date));
				$ex_amount		= $expenses->ex_amount;
				$ex_desc		= $expenses->ex_desc;
				$issued_to		= $expenses->issued_to;
				
				$siteInfo = $this->getSiteInfo($siteID);
				$site_id = $siteInfo->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$ex_date</td>
                        <td>₦".number_format($ex_amount,2)."</td>
                        <td>$ex_desc</td>
                        <td>$issued_to</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else {
			echo'<div class="alert alert-success alert-dismissable">
				<i class="fa fa-check"></i>
				<b>No Expnses on Sites yet</b>
			</div>';
		}
	}
	
	function getall_EngrSites($engrID) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_users where engr_id = '$engrID' ORDER BY time_created Desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Site ID</th>
					<th class=\"tbli_headder\">BCT ID</th>
					<th class=\"tbli_headder\">State</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				
				$siteInfo = $this->getSiteInfo($siteID);
				$site_id = $siteInfo->site_id;
				$bct_id = $siteInfo->bct_id;
				$state = $siteInfo->state;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$site_id</td>
                        <td>$bct_id</td>
                        <td>$state</td>
                        <td><a href=\"".$_SERVER['PHP_SELF']."?esid=$id&eid=$engrID&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 Site added for this engre</div>';   
	   }
	}
	function getall_Engr() {
	
		$this->connect_db();
		$sql = "SELECT * FROM app_users where user_level = 'Engineer' or user_level = 'QA' ORDER BY id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table id=\"example\" class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th class=\"tbli_headder\">#</th>
					<th class=\"tbli_headder\">Name</th>
					<th class=\"tbli_headder\">Last Logged in</th>
					<th class=\"tbli_headder\">Assigned Sites</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($user = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $user->id;
				$userName 		= $user->name;
				$loggedin 		= date("M d, Y",$user->last_loggedin);
				
				$sites = $this->countUserSites($id);
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$userName</td>
                        <td>$loggedin</td>
                        <td>$sites</td>
                     </tr>";
				
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Engineer Added. <a href="addusers.php">Add Engineer</a></div>';   
	   }
	}
	
	function listDropSite($siteID=null) {
		$this->connect_db();
		$sql = "SELECT * FROM site ORDER BY id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($site = mysql_fetch_object($result)) {
				$id = $site->id;
				$site_id = $site->site_id;
				if($siteID!=null){
				echo"<option value=\"$id\" ";
				if($siteID==$id) {echo "selected";}
				echo">$site_id</option>\n";
				}else{
				echo"<option value=\"$id\">$site_id</option>\n";
				}
			}
		}
	}
	
	function listSite($batchid) {
		$this->connect_db();
		$sql = "SELECT id,site_id FROM site  where status='Live' ORDER BY site_id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($site = mysql_fetch_object($result)) {
				$siteID = $site->id;
				$site_id = $site->site_id;
				
				//check if site has been add to this batch already, if yes, don't display site
				$checkSiteInBatch = $this->checkSiteInBatch($batchid,$siteID);
				if($checkSiteInBatch==0) {
					echo"<option value=\"$siteID\">$site_id</option>\n";
				}
			}
		}
	}
	
	function checkSiteInBatch($batchid,$siteid) {
		
		$query = "select batch_id,site_id from supply_batch_site where batch_id = '$batchid' and site_id = '$siteid'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow >0) {
			return 1;
		}else {
			return 0;
		}
	}
	
	function listDropLiveSite($siteID=null) {
		$this->connect_db();
		$sql = "SELECT * FROM site where status='Live' ORDER BY id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($site = mysql_fetch_object($result)) {
				$id = $site->id;
				$site_id = $site->site_id;
				if($siteID!=null){
				echo"<option value=\"$id\" ";
				if($siteID==$id) {echo "selected";}
				echo">$site_id</option>\n";
				}else{
				echo"<option value=\"$id\">$site_id</option>\n";
				}
			}
		}
	}
	
	function listAssetDestinations($destination) {
		$this->connect_db();
		
		echo"<option value=\"Office\" ";
		if($destination=="Office") {echo "selected";}
		echo">Office</option>\n";
		
		echo"<option value=\"Warehouse\" ";
		if($destination=="Warehouse") {echo "selected";}
		echo">Warehouse</option>\n";
		
		echo"<option value=\"Others\" ";
		if($destination=="Others") {echo "selected";}
		echo">Others</option>\n";
				
		//get sites		
		
		$sql = "SELECT * FROM site ORDER BY id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
			
		if($num_rows>0) {
			while($site = mysql_fetch_object($result)) {
				$id = $site->id;
				$site_id = $site->site_id;				
				
				echo"<option value=\"$id\" ";
				if($destination==$id) {echo "selected";}
				echo">$site_id</option>\n";
			}
		}
	}
	
	function listGeneratorAssets() {
		$this->connect_db();		
		
		$sql = "SELECT * FROM assets where asset_name = 'Generator' ORDER BY asset_id desc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
			
		if($num_rows>0) {
			while($gen = mysql_fetch_object($result)) {
				$id = $gen->asset_id;
				$serial = $gen->asset_serial;	

				//check if this gen has been assigned to another site.
				$checkQuery = mysql_query("select * from power_source where gen_asset_id = '$id'")or die(mysql_error());
				$countRow = mysql_num_rows($checkQuery);
				if($countRow==0) {
					echo"<option value='$id'>Gen - $serial</option>";
				}
			}
		}
	}

	function checkSite4Engr($SiteID,$EngrID) {
	
		$q = "select id from site_users where site_id = '$SiteID' and engr_id = '$EngrID'";
		$r = mysql_query($q)or die(mysql_error());
		$countRow = mysql_num_rows($r);
		
		if($countRow >0) {
			return 1;
		}else{
			return 0;
		}
	
	}
	
	function listTerms($tid=null) {
		$this->connect_db();
		$sql = "SELECT * FROM commercial_terms order by time_created desc";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($site = mysql_fetch_object($result)) {
				$id = $site->id;
				$commName = $site->commercial_name;
				
				echo"<option value=\"$id\"";
				if($tid==$id) {echo " selected";}
				echo">$commName</option>\n";
			}
		}else {
			echo"<option value=\"\"><a href=\"\">empty</a></option>\n";
		}
	}
	
	function listCustomers($cid=null) {
		$this->connect_db();
		$sql = "SELECT * FROM customer order by customer_name";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($cust = mysql_fetch_object($result)) {
				$id = $cust->id;
				$shortName = $cust->short_name;
				
				echo"<option value=\"$id\"";
				if($cid==$id) {echo " selected";}
				echo">$shortName</option>\n";
			}
		}else {
			echo"<option value=\"\"><a href=\"\">empty</a></option>\n";
		}
	}	
	
	function checkDownTimeTenant($downtimeID,$tenantID) {
		$this->connect_db();
		$sql = "SELECT * FROM downtime_tenant where downtime_id = '$downtimeID' and tenant_id = '$tenantID'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0){
			return true;
		}else{
			return false;
		}
	}
	
	function listCustomerTypes($tid=null) {
		$this->connect_db();
		$sql = "SELECT * FROM customer_type order by type_name";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($ctype = mysql_fetch_object($result)) {
				$id = $ctype->id;
				$tName = $ctype->type_name;
				$kw = $ctype->kilowatts;
				
				echo"<option value=\"$id\"";
				if($tid==$id) {echo " selected";}
				echo">$tName [$kw kw]</option>\n";
			}
		}else {
			echo"<option value=\"\"><a href=\"\">empty</a></option>\n";
		}
	}
	
	function listSite4Engr() {
		$this->connect_db();
		$sql = "SELECT id,site_id FROM site ";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($site = mysql_fetch_object($result)) {
				$SiteID = $site->id;
				$site_id = $site->site_id;
				
				echo"<option value=\"$SiteID\">$site_id</option>\n";
			}
		}else {
			echo"<option value=\"\">empty</option>\n";
		}
	}
	
	function listEngr() {
		$this->connect_db();
		$sql = "SELECT * FROM app_users where user_level = 'Engineer' ";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($user = mysql_fetch_object($result)) {
				$userID = $user->id;
				$engr_name = $user->name;
				
				echo"<option value=\"$userID\">$engr_name</option>\n";
			}
		}else {
			echo"<option value=\"\">No Engineer</option>\n";
		}
	}
	
	function listUserAssignList() {
		$this->connect_db();
		$sql = "SELECT id,name,user_level FROM app_users where user_level = 'Engineer' or user_level = 'QA' ";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($user = mysql_fetch_object($result)) {
				$userID = $user->id;
				$engr_name = $user->name;
				$level = $user->user_level;
				
				echo"<option value=\"$userID\">$engr_name ($level)</option>\n";
			}
		}else {
			echo"<option value=\"\">No User</option>\n";
		}
	}		
	
	function listDropSupervisor($sid=null) {
		$this->connect_db();
		$sql = "SELECT * FROM app_users where user_level = 'Supervisor' ORDER BY id Desc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($supervisor = mysql_fetch_object($result)) {
				$supervisorID = $supervisor->id;
				$supervisorName = $supervisor->name;
				if($sid!=null) {
					echo"<option value=\"$supervisorID\" ";
					if($sid == $supervisorID){ echo"selected";}
					echo">$supervisorName</option>\n";
				}else {
					echo"<option value=\"$supervisorID\">$supervisorName</option>\n";
				}
			}
		}
	}	
	
	function listDropVendors($vendID=null) {
		$this->connect_db();
		$sql = "SELECT * FROM vendors ORDER BY id Desc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
				
		if($num_rows>0) {
			while($vendor = mysql_fetch_object($result)) {
				$vendorID = $vendor->id;
				$vendorName = $vendor->name;
				
				if($vendID!=null) {
					echo"<option value=\"$vendorID\" ";
					if($vendID==$vendorID) { echo "selected";}
					echo">$vendorName</option>\n";
				}else {
					echo"<option value=\"$vendorID\">$vendorName</option>\n";
				}
			}
		}
	}
	
	function stock_supplied_Input($siteid,$state=null) {
		$this->connect_db();		
		
			//get number of tanks on site
			$siteData = $this->getSiteInfo($siteid);
			$siteTanks = $siteData->tank_mode;
			
			for($i=1;$i<=$siteTanks;$i++) {
				
				echo"<div class=\"form-group col-sm-6\">
					<label class=\"control-label\">Stock (Tank $i)</label>
					<div class=\"input-group\">
						<span class=\"input-group-addon bg\">
							<i class=\"fa fa-asterisk\"></i>
						</span>
						  <input type=\"text\" class=\"form-control\" placeholder=\"Initial Stock\" name=\"init_stock[]\" required ";
							if($state=="disable") { echo "disabled";}
						 echo" />
					</div>
				</div>
				
				<div class=\"form-group col-sm-6\">
					<label class=\"control-label\">Supplied (Tank $i)</label>
					<div class=\"input-group\">
						<span class=\"input-group-addon bg\">
							<i class=\"fa fa-asterisk\"></i>
						</span>
						<input type=\"text\" class=\"form-control\" placeholder=\"Quantity Supplied\" name=\"supplied_qty[]\" required ";
							if($state=="disable") { echo "disabled";}
						echo"/>
					</div>
				</div>";
			}
	}
	
	function stock_level_Input($siteid,$state=null) {
		$this->connect_db();
		//get number of tanks on site
		$siteData = $this->getSiteInfo($siteid);
		$siteTanks = $siteData->tank_mode;
		
		for($i=1;$i<=$siteTanks;$i++) {
			
			echo"<div class=\"form-group col-sm-6\">
				<label class=\"control-label\">Stock Level (Tank $i)</label>
				<div class=\"input-group\">
					<span class=\"input-group-addon bg\">
						<i class=\"fa fa-asterisk\"></i>
					</span>
					  <input type=\"text\" class=\"form-control\" placeholder=\"Stock Level\" name=\"stock_level[]\" required ";
					if($state=="disable"){ echo"disabled";}
					echo"/>
				</div>
			</div>";
		}
	}
	
	function Single_supplied_Input($siteid,$tankNumber) {
				
		echo"<div class=\"form-group col-sm-6\">
			<label class=\"control-label\">Stock (Tank $tankNumber)</label>
			<div class=\"input-group\">
				<span class=\"input-group-addon bg\">
					<i class=\"fa fa-asterisk\"></i>
				</span>
				  <input type=\"text\" class=\"form-control\" placeholder=\"Initial Stock\" name=\"init_stock\" required />
			</div>
		</div>
		
		<div class=\"form-group col-sm-6\">
			<label class=\"control-label\">Supplied (Tank $tankNumber)</label>
			<div class=\"input-group\">
				<span class=\"input-group-addon bg\">
					<i class=\"fa fa-asterisk\"></i>
				</span>
				<input type=\"text\" class=\"form-control\" placeholder=\"Quantity Supplied\" name=\"supplied_qty\" required />
			</div>
		</div>";
	}
	
	function RunningHoursInput($siteid,$state=null) {
		$this->connect_db();
		$query = mysql_query("select * from power_source where site_id = '$siteid' and source_type='Gen'");
		while($powerSource = mysql_fetch_object($query)) {
			$powerID = $powerSource->power_id;
			$sourceType = $powerSource->source_type;
			$sourceName = $powerSource->source_name;
			
			
			echo"<!-- xinput group-->
					<div class=\"form-group col-sm-6\">
						<label class=\"control-label\">Running Hours for $sourceName</label>
						<div class=\"input-group\">
							<span class=\"input-group-addon bg\">
								<i class=\"fa fa-asterisk\"></i>
							</span>
							<input type=\"text\" class=\"form-control\" placeholder=\"00.00\" name=\"runnhrs[]\" required ";
								if($state=="disable") { echo "disabled";}
							echo"/>
							<input type=\"hidden\" value=\"$powerID\" name=\"sourceid[]\"  />
						</div>
					</div>
				  <!-- /input-group -->";
		}
	}
	
	function RunningHoursInputforService($siteid,$state=null) {
		$this->connect_db();
		$query = mysql_query("select * from power_source where site_id = '$siteid' and source_type='Gen'");
		while($powerSource = mysql_fetch_object($query)) {
			$powerID = $powerSource->power_id;
			$sourceType = $powerSource->source_type;
			$sourceName = $powerSource->source_name;
			
			
			echo"<!-- xinput group-->
					<div class=\"form-group col-sm-6\">
						<label class=\"control-label\">$sourceName Current Running Hours</label>
						<div class=\"input-group\">
							<span class=\"input-group-addon bg\">
								<i class=\"fa fa-asterisk\"></i>
							</span>
							<input type=\"text\" class=\"form-control\" placeholder=\"00.00\" name=\"runnhrs[]\" required ";
								if($state=="disable") { echo "disabled";}
							echo"/>
							<input type=\"hidden\" value=\"$powerID\" name=\"sourceid[]\"  />
						</div>
					</div>
				  <!-- /input-group -->
				  <!-- xinput group-->
					<div class=\"form-group col-sm-6\">
						<label class=\"control-label\">$sourceName Next Running Hours</label>
						<div class=\"input-group\">
							<span class=\"input-group-addon bg\">
								<i class=\"fa fa-asterisk\"></i>
							</span>
							<input type=\"text\" class=\"form-control\" placeholder=\"00.00\" name=\"nxtrunnhrs[]\" required />
						</div>
					</div>
				  <!-- /input-group -->";
		}
	}
		
	function SiteServiceItemInput($siteID) {
		$this->connect_db();
		$query = mysql_query("select * from site_service_item where site_id = '$siteID'");
		$countRow = mysql_num_rows($query);
		if($countRow>0) {
			$sn = 0;
			while($item = mysql_fetch_object($query)) {
				$sn +=1;
				$item_id 		= $item->id;
				$service_item 	= $item->service_item;
				$item_cost	 	= $item->item_cost;
				
				echo"<div class=\"row buttons-demo\">
					<div class=\"col-md-6\">
						<div class=\"input-group demo-group\">
							<span class=\"input-group-addon addon-left\">
								<input type=\"checkbox\" id=\"c$sn\" checked value=\"$service_item\" name=\"sitemid[]\" aria-label=\"Check item\" onclick=\"return false\" />
								<label for=\"c$sn\" class=\"margin-zero\"><span></span></label>
							</span>
							<input type=\"text\" class=\"form-control\" value=\"$service_item\" name=\"sitem[]\" aria-label=\"Service Item\" readonly />
						</div>
					</div>
					<div class=\"col-md-6\">
						<div class=\"input-group demo-group\">
							<input type=\"number\" min=\"1\" class=\"form-control\" name=\"itemqty[]\" aria-label=\"Item Quantity\" placeholder=\"quantity\" required />
							<input type=\"hidden\" class=\"form-control\" name=\"itemcost[]\" value=\"$item_cost\" aria-label=\"Item Cost\" placeholder=\"cost\">
						</div>
					</div>
				</div>
				<br />\n";
			}
		}else {
			echo"<div class=\"alert alert-info\">No service Item Added.</div>";
		}
	}
	function SiteServiceItemInputDisabled($siteID) {
		$this->connect_db();
		$query = mysql_query("select * from site_service_item where site_id = '$siteID'");
		$countRow = mysql_num_rows($query);
		if($countRow>0) {
			$sn = 0;
			while($item = mysql_fetch_object($query)) {
				$sn +=1;
				$item_id 		= $item->id;
				$service_item 	= $item->service_item;
				$item_cost	 	= $item->item_cost;
				
				echo"<div class=\"row buttons-demo\">
					<div class=\"col-md-6\">
						<div class=\"input-group demo-group\">
							<span class=\"input-group-addon addon-left\">
								<input type=\"checkbox\" id=\"c$sn\" checked value=\"$service_item\" name=\"sitemid[]\" aria-label=\"Check item\" onclick=\"return false\" />
								<label for=\"c$sn\" class=\"margin-zero\"><span></span></label>
							</span>
							<input type=\"text\" class=\"form-control\" value=\"$service_item\" name=\"sitem[]\" aria-label=\"Service Item\" readonly />
						</div>
					</div>
					<div class=\"col-md-6\">
						<div class=\"input-group demo-group\">
							<input type=\"number\" min=\"1\" class=\"form-control\" name=\"itemqty[]\" aria-label=\"Item Quantity\" placeholder=\"quantity\" disabled/>
							<input type=\"hidden\" class=\"form-control\" name=\"itemcost[]\" value=\"$item_cost\" aria-label=\"Item Cost\" placeholder=\"cost\">
						</div>
					</div>
				</div>
				<br />\n";
			}
		}else {
			echo"<div class=\"alert alert-info\">No service Item Added.</div>";
		}
	}
	
	function DeleteExpenses($exid) {
		$this->connect_db();
		$queryI = "delete from expenses where expense_id = '$exid'";
		$resultI = mysql_query($queryI)or die(mysql_error());
		if($resultI) {
			return"<div class=\"alert alert-success\">Expense Deleted Successfully</div>";
		}
	}
	
	function SitePendingSeriveReport($siteID) {
		$this->connect_db();
		$query = mysql_query("select * from servicing where site_id = '$siteID' and approve_status = 'Pending'")or die(mysql_error());
		$sites = mysql_num_rows($query);
		return $sites;
	}
	
	function countSupplyBatchSites($batchid) {
		$this->connect_db();
		$query = mysql_query("select * from supply_batch_site where batch_id = '$batchid'");
		$CountBatch = mysql_num_rows($query);
		return $CountBatch;
	}	
	
	function getSiteBatchInfo($sitebatchID) {
		$this->connect_db();
		$query = mysql_query("select * from supply_batch_site where id = '$sitebatchID'");
		$siteBatch = mysql_fetch_object($query);
		return $siteBatch;
	}
	
	function countTenants() {
		$this->connect_db();
		$query = mysql_query("select * from site_tenants");
		$CountCust = mysql_num_rows($query);
		return $CountCust;
	}
	
	function countUserSites($userID) {
		$this->connect_db();
		$query = mysql_query("select * from site_users where user_id = '$userID'");
		$Countsite = mysql_num_rows($query);
		return $Countsite;
	}
	
	function getNotifyInfo($nid) {
		$this->connect_db();
		$query = mysql_query("select * from notifications where notif_id = '$nid'");
		$notifyData = mysql_fetch_object($query);
		return $notifyData;
	}
	
	function getDocInfo($docid) {
		$this->connect_db();
		$query = mysql_query("select * from site_doc where doc_id = '$docid'");
		$DocData = mysql_fetch_object($query);
		return $DocData;
	}
	
	function getTicketInfo($ticketID) {
		$this->connect_db();
		$query = mysql_query("select * from tickets where ticket_id = '$ticketID'");
		$TicketData = mysql_fetch_object($query);
		return $TicketData;
	}
	
	function getEngrSiteInfo($userid) {
		$this->connect_db();
		$query = mysql_query("select * from site_users where user_id = '$userid'");
		$UserSite = mysql_fetch_object($query);
		return $UserSite;
	}
	
	function checkEngrSite($siteID,$userid) {
		$this->connect_db();
		$query = mysql_query("select * from site_users where site_id = '$siteID' and user_id = '$userid'");
		$countRow = mysql_num_rows($query);
		if($countRow>0) {
			return 1;
		}else {
			return 0;
		}
	}
	
	function getSiteEngrInfo($siteID) {
		$this->connect_db();
		$query = mysql_query("select * from site_users where site_id = '$siteID'");
		$SiteEngr = mysql_fetch_object($query);
		return $SiteEngr;
	}
	
	function getSupplyDetails($supplyID,$siteID) {
		$this->connect_db();
		$query = mysql_query("SELECT sum(initial_stock) as stock,sum(supplied_qty) as qty, sum(new_stock)as total FROM supplies_details WHERE supply_id = '$supplyID' and site_id = '$siteID'");
		$details = mysql_fetch_object($query);
		return $details;
	}
	
	function getSupplyDetailsQA($supplyID,$siteID) {
		$this->connect_db();
		$query = mysql_query("SELECT sum(initial_stock) as stock,sum(supplied_qty) as qty, sum(new_stock)as total FROM qa_supplies_details WHERE supply_id = '$supplyID' and site_id = '$siteID'");
		$details = mysql_fetch_object($query);
		return $details;
	}
	
	function getServiceDetails($serviceID,$siteID) {
		$this->connect_db();
		$query = mysql_query("SELECT * FROM servicing_details WHERE service_id = '$serviceID' and site_id = '$siteID'");
		$details = mysql_fetch_object($query);
		return $details;
	}
	
	function getServiceDetailsQA($serviceID,$siteID) {
		$this->connect_db();
		$query = mysql_query("SELECT * FROM qa_servicing_details WHERE service_id = '$serviceID' and site_id = '$siteID'");
		$details = mysql_fetch_object($query);
		return $details;
	}
	
	function getInvoiceInfo($invid) {
		$this->connect_db();
		$query = mysql_query("select * from invoice_customer where id = '$invid'");
		$invoice = mysql_fetch_object($query);
		return $invoice;
	}
	
	function getTermInfo($tid) {
		$this->connect_db();
		$query = mysql_query("select * from commercial_terms where id = '$tid'");
		$Terms = mysql_fetch_object($query);
		return $Terms;
	}
	
	function getProjectInfo($projectID) {
		$this->connect_db();
		$query = mysql_query("select * from bj_projects where project_id = '$projectID'");
		$project = mysql_fetch_object($query);
		return $project;
	}
	
	function getSiteInfo($siteID) {
		$this->connect_db();
		$query = mysql_query("select * from site where id = '$siteID'");
		$site = mysql_fetch_object($query);
		return $site;
	}
	
	function getWeekInfo($reportID) {
		$this->connect_db();
		$query = mysql_query("select * from weekly_report where id = '$reportID'");
		$site = mysql_fetch_object($query);
		return $site;
	}
	
	function getQAWeekInfo($reportID) {
		$this->connect_db();
		$query = mysql_query("select * from qa_weekly_report where id = '$reportID'");
		$site = mysql_fetch_object($query);
		return $site;
	}
	
	function getConfigInfo() {
		$this->connect_db();
		$query = mysql_query("select * from app_config");
		$config = mysql_fetch_object($query);
		return $config;
	}
	
	function getSupplyInfo($supplyID) {
		$this->connect_db();
		$query = mysql_query("select * from supplies where id = '$supplyID'");
		$supply = mysql_fetch_object($query);
		return $supply;
	}
	
	function getQASupplyInfo($supplyID) {
		$this->connect_db();
		$query = mysql_query("select * from qa_supplies where id = '$supplyID'");
		$supply = mysql_fetch_object($query);
		return $supply;
	}
	
	function getServiceInfo($serviceID) {
		$this->connect_db();
		$query = mysql_query("select * from servicing where id = '$serviceID'");
		$service= mysql_fetch_object($query);
		return $service;
	}
	
	function getQAServiceInfo($serviceID) {
		$this->connect_db();
		$query = mysql_query("select * from qa_servicing where id = '$serviceID'");
		$service= mysql_fetch_object($query);
		return $service;
	}
	
	function getITPInfo($itpID) {
		$this->connect_db();
		$query = mysql_query("select * from itp where id = '$itpID'");
		$itp = mysql_fetch_object($query);
		return $itp;
	}
	
	function getPOInfo($poID) {
		$this->connect_db();
		$query = mysql_query("select * from purchase_order where po_id = '$poID'");
		$po = mysql_fetch_object($query);
		return $po;
	}
	
	function getDownTimeInfo($eid) {
		$this->connect_db();
		$query = mysql_query("select * from downtime where id = '$eid'");
		$downtime = mysql_fetch_object($query);
		return $downtime;
	}
	
	function getTransferRequestInfo($id) {
		$this->connect_db();
		$query = mysql_query("select * from transfer_request where id = '$id'");
		$request = mysql_fetch_object($query);
		return $request;
	}
	
	function getItemInfo($itemID) {
		$this->connect_db();
		$query = mysql_query("select * from po_items where item_id = '$itemID'");
		$item = mysql_fetch_object($query);
		return $item;
	}
	
	function getAssetInfo($aid) {
		$this->connect_db();
		$query = mysql_query("select * from assets where asset_id = '$aid'");
		$asset = mysql_fetch_object($query);
		return $asset;
	}
	
	function getPowerInfo($pid) {
		$this->connect_db();
		$query = mysql_query("select * from power_source where power_id = '$pid'");
		$power = mysql_fetch_object($query);
		return $power;
	}
	
	function getAssetHistoryInfo($hid) {
		$this->connect_db();
		$query = mysql_query("select * from asset_history where history_id = '$hid'");
		$history = mysql_fetch_object($query);
		return $history;
	}
	
	function getExpenseInfo($exID) {
		$this->connect_db();
		$query = mysql_query("select * from expenses where expense_id = '$exID'");
		$expense = mysql_fetch_object($query);
		return $expense;
	}
	
	function getGenID($siteID,$gen) {
		$this->connect_db();
		$query = "select gen_id from site_gen where site_id = '$siteID' and  gen_name = '$gen'";
		$result = mysql_query($query)or die(mysql_error());
		$genData = mysql_fetch_object($result);
		return $genData->gen_id;
	}
	
	function getGenInfo($genID) {
		$this->connect_db();
		$query = mysql_query("select * from site_gen where gen_id = '$genID'");
		$gen = mysql_fetch_object($query);
		return $gen;
	}
	
	function getVendorInfo($vendorID) {
		$this->connect_db();
		$query = mysql_query("select * from vendors where id = '$vendorID'")or die(mysql_error());
		$vendor = mysql_fetch_object($query);
		return $vendor;
	}
	
	function getSupervisorInfo($supervisorID) {
		$this->connect_db();
		$query = mysql_query("select * from app_users where id = '$supervisorID'")or die(mysql_error());
		$supervisor = mysql_fetch_object($query);
		return $supervisor;
	}
	
	function getTenantInfo($tid) {
		$this->connect_db();
		$query = mysql_query("select * from site_tenants where id = '$tid'")or die(mysql_error());
		$tenants = mysql_fetch_object($query);
		return $tenants;
	}
	
	function getCustomerInfo($custID) {
		$this->connect_db();
		$query = mysql_query("select * from customer where id = '$custID'")or die(mysql_error());
		$customer = mysql_fetch_object($query);
		return $customer;
	}
	
	function getDieselConfigInfo() {
		$this->connect_db();
		$query = mysql_query("select * from diesel_supply_config")or die(mysql_error());
		$config = mysql_fetch_object($query);
		return $config;
	}
	
	function getMetricsInfo($mid) {
		$this->connect_db();
		$query = mysql_query("select * from diesel_metrics where id='$mid'")or die(mysql_error());
		$metrics = mysql_fetch_object($query);
		return $metrics;
	}
	
	function getUserInfo($userID) {
		$this->connect_db();
		$query = mysql_query("select * from app_users where id = '$userID'")or die(mysql_error());
		$user = mysql_fetch_object($query);
		return $user;
	}
	
	function getCustomerTypeInfo($typeID) {
		$this->connect_db();
		$query = mysql_query("select * from customer_type where id = '$typeID'")or die(mysql_error());
		$type = mysql_fetch_object($query);
		return $type;
	}
	
	function getBatchInfo($bid) {
		$this->connect_db();
		$query = mysql_query("select * from supply_batch where batch_id = '$bid'")or die(mysql_error());
		$batch = mysql_fetch_object($query);
		return $batch;
	}
	
	function getTicketReplyInfo($rid) {
		$this->connect_db();
		$query = mysql_query("select * from ticket_reply where reply_id = '$rid'");
		$reply = mysql_fetch_object($query);
		return $reply;
	}
	
	function getCurrServiceInfo($siteid,$powerid) {
		$this->connect_db();
		$query = mysql_query("select * from service_curr_stats where site_id = '$siteid' and power_id = '$powerid'");
		$stats = mysql_fetch_object($query);
		return $stats;
	}
	
	function getSiteLastStockQty($siteid) {
		$this->connect_db();
		$query = mysql_query("select id,site_id,status from supplies where site_id = '$siteid' and status = '0'")or die(mysql_error());
		$supplyInfo = mysql_fetch_object($query)or die(mysql_error());
		$supplyID = $supplyInfo->id;
		
		//get supply details
		$sql = mysql_query("select supply_id,sum(new_stock) as Total_stock from supplies_details where supply_id = '$supplyID'")or die(mysql_error());
		$detailsInfo = mysql_fetch_object($sql)or die(mysql_error());
		$stock = $detailsInfo->Total_stock;
		return $stock;
	}
	
	function getSupplyDateDiff($supply_id) {
		$this->connect_db();
		$query = mysql_query("select DATEDIFF(next_supply_date,CURDATE()) as Days from supplies where id = '$supply_id'");
		$supply = mysql_fetch_object($query);
		$DayDiff = $supply->Days;
		return $DayDiff;
	}
	
	function getSupplyDateDiffQA($supply_id) {
		$this->connect_db();
		$query = mysql_query("select DATEDIFF(next_supply_date,CURDATE()) as Days from qa_supplies where id = '$supply_id'");
		$supply = mysql_fetch_object($query);
		$DayDiff = $supply->Days;
		return $DayDiff;
	}
	
	function getDaysPastfromSupply($supply_id) {
		$this->connect_db();
		$query = mysql_query("select DATEDIFF(CURDATE(),supply_date) as Days from supplies where id = '$supply_id'");
		$supply = mysql_fetch_object($query);
		$DayPast = $supply->Days;
		return $DayPast;
	}
	
	function getSiteSupplyPastDays($siteID) {
		$this->connect_db();
		$query = mysql_query("select DATEDIFF(CURDATE(),supply_date) as Days from supplies where site_id = '$siteID' and status='0'");
		$supply = mysql_fetch_object($query);
		$DayPast = $supply->Days;
		return $DayPast;
	}
	
	function getDaysPastfromSupplyQA($supply_id) {
		$this->connect_db();
		$query = mysql_query("select DATEDIFF(CURDATE(),supply_date) as Days from qa_supplies where id = '$supply_id'");
		$supply = mysql_fetch_object($query);
		$DayPast = $supply->Days;
		return $DayPast;
	}	
	
	function supply_notification() {
		$this->connect_db();		
		
		$query = "select id,site_id,DATEDIFF(next_supply_date,CURDATE()) as dueDays,
				DATEDIFF(CURDATE(),next_supply_date) as overDays
				from supplies where status = '0'";
				
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		
		if($countRow > 0) {
			while($supply = mysql_fetch_object($result)){
				$supplyID = $supply->id;
				$siteID = $supply->site_id;
				$dueDays = $supply->dueDays;
				$overDays = $supply->overDays;
				
				$siteData = $this->getSiteInfo($siteID);
				$sid = $siteData->id;
				$site_id = $siteData->site_id;
				
				$date = time();
			
				if($dueDays == 10){
				
					//Created Notification (Work Order) for diesel suppy
					$notifQuery = mysql_query("insert into notifications values('','Supply on Site $site_id will be due in $dueDays from ".date("M d, Y",$date)."','supply','$supplyID','$siteID','no','Not Done','$date')")or die(mysql_error());
				
				}elseif($dueDays == 0) {						
						
				}elseif($dueDays < $overDays) {
				
				}
			}
			
			echo "Successful I";
		}
	}
	
	function service_notification() {
		$this->connect_db();		
		$query = "select site_id,DATEDIFF(next_service_date,CURDATE()) as dueDays,
				DATEDIFF(CURDATE(),next_service_date) as overDays
				from servicing where status = '0'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		
		if($countRow > 0) {
			//echo"<div class=\"alert alert-info\">$Countrows Notifications</div>";
		
			while($service = mysql_fetch_object($result)){
				$siteID = $service->site_id;
				$dueDays = $service->dueDays;
				$overDays = $service->overDays;
				
				$siteData = $this->getSiteInfo($siteID);
				$sid = $siteData->id;
				$site_id = $siteData->site_id;
				
				if($dueDays == 10){						
						
					//Created Notification (Work Order) for Site Service 
					$notifQuery = mysql_query("insert into notifications values('','Service on Site $site_id will be due in $dueDays from ".date("M d, Y",$date)."','service','$supplyID','$siteID','Not Seen','Not Done','$date')")or die(mysql_error());
				
				}elseif($dueDays == 0) {
					
				}elseif($dueDays < $overDays) {
					
				}
			}
			echo "Ok";
		}else {
			echo "Sucessful II";
		}
	}
	
	function dieselLevelBar($supplyID) {
		$this->connect_db();
		$query = "select id,site_id,next_supply_date,status,
		 DATEDIFF(next_supply_date,supply_date) as total_days,
		 DATEDIFF(next_supply_date,CURDATE()) as remaining_days
		 from supplies where id = '$supplyID' and status = '0'";
		 
		 
		$result = mysql_query($query)or die(mysql_error());	
		$countRow = mysql_num_rows($result);
		$disel = mysql_fetch_object($result)or die(mysql_error());
		
		$siteID = $disel->site_id;
		$totalDays = $disel->total_days;
		$RemainingDays =  $disel->remaining_days;
		
		//calculate percent of disel remaining
		$percentage = (100*$RemainingDays)/$totalDays;
		$percentRound = round($percentage, 2);
		
		$siteData = $this->getSiteInfo($siteID);
		$site_id = $siteData->site_id;
		
			echo" Current Est. Level : $percentRound%";
	}
	
	function dieselLevel($sid) {
		$this->connect_db();
		$query = "select id,site_id,next_supply_date,status,
		 DATEDIFF(next_supply_date,supply_date) as total_days,
		 DATEDIFF(next_supply_date,CURDATE()) as remaining_days
		 from supplies where site_id = '$sid' and status = '0'";
		 
		 
		$result = mysql_query($query)or die(mysql_error());	
		$countRow = mysql_num_rows($result);
		if($countRow) {
		$disel = mysql_fetch_object($result)or die(mysql_error());
		
		$siteID = $disel->site_id;
		$totalDays = $disel->total_days;
		$RemainingDays =  $disel->remaining_days;
		
		//calculate percent of disel remaining
		$percentage = (100*$RemainingDays)/$totalDays;
		$percentRound = round($percentage, 2);
		
		$siteData = $this->getSiteInfo($siteID);
		$site_id = $siteData->site_id;
		
			return "$percentRound%";
		}else{
			return "-";
		}
	}

	function invoice_notification() {
		$this->connect_db();
		
		$query = "select * from site_tenants where state = 'Live' and invoice = 'Not Invoiced'";
		 
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		
		if($countRow > 0) {
			while($invoice = mysql_fetch_object($result)){
				$siteID = $invoice->site_id;
				$customerName = $invoice->customer_name;
				
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				$siteLiveDate = date("Y-m-d, H:i:sa",$siteData->live_date);
									
				echo'<a href="#">
						<div class="message_list_block">
							<div class="right">
								<span class="name">'.$site_id.'</span>
								<h4>Tenant '.$customerName.' on site '.$site_id.' is due to be invoiced</h4>
							</div>
						</div>
					</a>';
			}
		}else {
			echo'<div class="alert alert-success alert-dismissable">
				<i class="fa fa-check"></i>
				<b>Invoice is ok.</b>
			</div>';
		}
	}
	
	

	function dueToIssueInvoice() {
		$this->connect_db();
		$today = date("Y-m-d", time());
		
		$query = "select * from invoice_customer where next_invoice_date <= '$today' and invoiced_next = 'Not Done'";
		 
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		
		if($countRow > 0) {
			while($invoice = mysql_fetch_object($result)){
				$custid = $invoice->customer_id;
				$invoiceDate = $invoice->next_invoice_date;
				
				$custData = $this->getCustomerInfo($custid);
				$custname = $custData->customer_name;
									
				echo'<a href="#">
						<div class="message_list_block">
							<div class="right">
								<h4>Tenant '.$custname.' is due to be invoiced on '.$invoiceDate.'. </h4>
							</div>
						</div>
					</a>';
			}
		}else {
			echo'<div class="alert alert-success alert-dismissable">
				<i class="fa fa-check"></i>
				<b>Invoice is ok.</b>
			</div>';
		}
	}
	
	//delete site
	function delete_site($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			$del = $post['deletesite'];
			$sid = $post['sid'];
			
			if($del=="yes") {
				
				//delete supply for site
				$delSuppy = "delete from supplies where site_id = '$sid'";
				$delSuppy_result = mysql_query($delSuppy)or die(mysql_error());
				
				//delete gens for site
				$delSiteGen = "delete from site_gen where site_id = '$sid'";
				$delSiteGen_result = mysql_query($delSiteGen)or die(mysql_error());
				
				//delete servicing for site
				$delServicing = "delete from servicing where site_id = '$sid'";
				$delServicing_result = mysql_query($delServicing)or die(mysql_error());
				
				//delete servicing stats for site
				$delServicingStat = "delete from service_curr_stats where site_id = '$sid'";
				$delServicingStat_result = mysql_query($delServicingStat)or die(mysql_error());
				
				//delete servicing stats for site
				$delEngrSite = "delete from site_users where site_id = '$sid'";
				$delEngrSite_result = mysql_query($delEngrSite)or die(mysql_error());
				
				//get all customers associated with site and delete their detials and also delete their invoice details if any
				$getCustomers = "select id,site_id from site_tenants where site_id = '$sid'";
				$getCustomersRes = mysql_query($getCustomers)or die(mysql_error());
				$countCustomers = mysql_num_rows($getCustomersRes);
				if($countCustomers>0) {
					while($customer = mysql_fetch_object($getCustomersRes)) {
						$customerID = $customer->id;
						$deleteInvoice = "delete from invoice_customer where customer_id = '$customerID'";
						$deleteInvoiceRes = mysql_query($deleteInvoice)or die(mysql_error());
					}
				}
				//delete customers
				$delCustomers = "delete from site_tenants where site_id = '$sid'";
				$delCustomersRes = mysql_query($delCustomers)or die(mysql_error());
						
				//finally delete site.
				$del_query = "delete from site where id = '$sid'";
				$del_result = mysql_query($del_query)or die(mysql_error());
				
				if($del_result) {
					return  "<div class=\"alert alert-success\">Site Deleted Successfully.</div>";
				}
			}else {
				return  "<div class=\"alert alert-danger\">Operation Cancelled</div>";
			}
		}
	}
	
	
	//delete supply
	function delete_supply($supplyid) {
		$this->connect_db();
			
		//delete supply	
		$sql_supply = "delete from supplies where id = '$supplyid'";
		$result_supply = mysql_query($sql_supply)or die(mysql_error());
			
		//delete details	
		$sql_details = "delete from supplies_details where supply_id = '$supplyid'";
		$result_details = mysql_query($sql_details)or die(mysql_error());
			
		//delete notifications	
		$sql_notify = "delete from notifications where ntype_id = '$supplyid'";
		$result_notify = mysql_query($sql_notify)or die(mysql_error());
			
		if($result_supply && $result_details && $result_notify) {
			return  1;
		}else {
			return  0;
		}
	}
	
	function bulk_delete($post, $process) {
		$this->connect_db();
		if(isset($process)) {
			$sID = $post['siteID'];
			
			foreach($sID as $site_ID) {
				$this-> delete_site($site_ID);
				
				$sn = $site_ID;
			}
				//return  "<div class=\"alert alert-success\">site deleted Successfully. $sn</div>";
				return   "<div class=\"alert alert-success\">site deleted Successfully ". count($sID) ." </div>";
		}
	}
	
	//archive site
	function archive_site($sid) {
		$this->connect_db();
		$date = time();
		//finally delete site.
		$arc_query = "update site set archived = '1', archived_date = '$date' where id = '$sid'";
		$arc_result = mysql_query($arc_query)or die(mysql_error());
		
		if($arc_result) {
			return  "<div class=\"alert alert-success\">Site Archived Successfully.</div>";
		}
	}
	
	//archive site
	function Unarchive_site($sid) {
		$this->connect_db();
		$date = time();
		//finally delete site.
		$arc_query = "update site_tenants set archived = '0', archived_date = '$date' where id = '$sid'";
		$arc_result = mysql_query($arc_query)or die(mysql_error());
		
		if($arc_result) {
			return  "<div class=\"alert alert-success\">Site Removed Successfully.</div>";
		}
	}
	
	//archive site
	function activeTenant($cid) {
		$this->connect_db();
		$date = time();
		//finally delete site.
		$arc_query = "update site_tenants set state = 'none' where id = '$cid'";
		$arc_result = mysql_query($arc_query)or die(mysql_error());
		
		if($arc_result) {
			return  "<div class=\"alert alert-success\">Site Removed Successfully.</div>";
		}
	}
	
	//delete site
	function delete_customer($cid) {
		$this->connect_db();
		
		$deleteInvoice = "delete from invoice_customer where customer_id = '$cid'";
		$deleteInvoiceRes = mysql_query($deleteInvoice)or die(mysql_error());
		//delete customers
		$delCustomers = "delete from site_tenants where id = '$cid'";
		$delCustomersRes = mysql_query($delCustomers)or die(mysql_error());
		
		if($delCustomersRes) {
			return  "<div class=\"alert alert-success\">Customer deleted Successfully.</div>";
		}
	}
	
	//search
	function getSite_status($status) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site where status='$status' ORDER BY id asc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Bct ID</th>
                    <th>Site Type</th>
                    <th>Supervisor</th>
                    <th>Status</th>
                    <th width=\"15%\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$bct_id 		= $site->bct_id;
				$state 			= $site->state;
				$site_type 		= $site->site_type;
				$site_no 		= $site->site_no;
				$supervisor  	= $site->supervisor ;
				$status 		= $site->status;
				
				$supvisorData = $this->getSupervisorInfo($supervisor );
				$supvisorName = $supvisorData->name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td><div data-toggle=\"tooltip\" title=\"State - $state\">$siteID</div></td>
                        <td>$bct_id </td>
                        <td><div data-toggle=\"tooltip\" title=\"Site No - $site_no\">$site_type</div></td>
                        <td>$supvisorName</td>
                        <td><div class=\"badge ";
						if($status=="Live") {echo"bg-green"; }else{echo"bg-red";}
						echo"\">$status</div></td>
                        <td>
							<a href=\"view_site.php?siteID=$id \"><span class=\"add-on small-size\"> View</span></a> | 
							<a href=\"edit_site.php?sid=$id\"><span class=\"add-on small-size\">Edit</span></a> | 
							<a href=\"".$_SERVER['PHP_SELF']."?ac=del&sid=$id\"> <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 Site Yet</div>';   
			}
	}
	
	function AllInvoices() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM invoice_customer ORDER BY id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Customer Name</th>
                    <th>Criteria</th>
                    <th>Amount</th>
                    <th>Invoice Status</th>
                    <th>Payment Due Date</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($invoice = mysql_fetch_object($result)) {
				$sn += 1;
				$id				= $invoice->id;
				$Custid			= $invoice->customer_id;
				$invoiceDate 	= $invoice->invoice_date;
				$dueDate 		= $invoice->due_date;
				$amount 		= $invoice->amount;
				$paidDate 		= $invoice->date_paid;
				$status 		= $invoice->payment_status;
				
				//get customer name;
				$CustomerData = $this->getCustomerInfo($Custid);
				$site_id = $CustomerData->site_id;
				$CustomerName = $CustomerData->customer_name;
				$cterms = $CustomerData->commercial_term;
				
				//get Term Data;
				$termData = $this->getTermInfo($cterms);
				$criteria = $termData->commercial_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"update_invoice.php?invID=$id&custID=$Custid\" data-toggle=\"modal\" data-target=\"#invoiceModal\">$CustomerName</a></td>
                        <td>$criteria</td>
                        <td>N".number_format($amount,2)."</td>
                        <td><div class=\"label ";
						if($status=="Not Paid") {echo"label-danger";}else{echo" label-success";}
						echo"\">$status</div></td>
                        <td>$dueDate</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Invoice Has Been Paid</div>';   
	   }
	}
	
	function getTicketNotificationUsers() {	
		$this->connect_db();		
		$sql = "SELECT id,ticket_notify,user_level FROM app_users where user_level = 'Supervisor' and ticket_notify = 'yes'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0){
			return $result;
		}else {
			return 0;
		}
	}
	
	function getServiceNotificationUsers() {	
		$this->connect_db();		
		$sql = "SELECT id,service_notify,user_level FROM app_users where user_level = 'Supervisor' and service_notify = 'yes'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0){
			return $result;
		}else {
			return 0;
		}
	}
	
	function getSupplyNotificationUsers() {	
		$this->connect_db();		
		$sql = "SELECT id,supply_notify,user_level FROM app_users where user_level = 'Supervisor' and supply_notify = 'yes'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0){
			return $result;
		}else {
			return 0;
		}
	}
	
	function getDieselOrorderNotificationUsers() {	
		$this->connect_db();		
		$sql = "SELECT id,dieselreorder_notify,user_level FROM app_users where user_level = 'Supervisor' and dieselreorder_notify = 'yes'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0){
			return $result;
		}else {
			return 0;
		}
	}
	
	function getWeeklyReportNotificationUsers() {	
		$this->connect_db();		
		$sql = "SELECT id,week_notify,user_level FROM app_users where user_level = 'Supervisor' and week_notify = 'yes'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if($num_rows>0){
			return $result;
		}else {
			return 0;
		}
	}
	
	function CountAllInvoices() {	
		$this->connect_db();		
		$sql = "SELECT * FROM invoice_customer ORDER BY id desc";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		return $num_rows;
	}
	
	function CountDueInvoices() {	
		$this->connect_db();		
		$sql = "SELECT * FROM invoice_customer where due_date >= '$today' and payment_status = 'Not Paid'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		return $num_rows;
	}
	
	function CountPaidInvoices() {	
		$this->connect_db();		
		$sql = "SELECT * FROM invoice_customer where payment_status = 'Paid'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		return $num_rows;
	}
	
	function CountDueToInvoices() {	
		$this->connect_db();	
		$today = date("Y-m-d",time());
		$sql = "SELECT * FROM invoice_customer where next_invoice_date >= '$today' and invoiced_next ='$invoiced' ORDER BY id desc";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		return $num_rows;
	}
	
	function CountUnpaidInvoices() {	
		$this->connect_db();		
		$sql = "SELECT * FROM invoice_customer where payment_status = 'Not Paid'";				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		return $num_rows;
	}
	
	function getPaidInvoice_status($status) {	
		$this->connect_db();
		$today = date("Y-m-d",time());
		if($status=="Paid") {
			$sql = "SELECT * FROM invoice_customer where payment_status = 'Paid' ORDER BY id desc";
		}elseif($status=="unpaid") {
			$sql = "SELECT * FROM invoice_customer where payment_status = 'Not Paid' ORDER BY id desc";
		}else{
			$sql = "SELECT * FROM invoice_customer where due_date >= '$today' and payment_status = 'Not Paid' ORDER BY id desc";
		}
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Customer Name</th>
                    <th>Start</th>
                    <th>Criteria</th>
                    <th>Amount</th>
                    <th>Due Date</th>
                    <th>Date Paid</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($invoice = mysql_fetch_object($result)) {
				$sn += 1;
				$id				= $invoice->id;
				$Custid			= $invoice->customer_id;
				$invoiceDate 	= $invoice->invoice_date;
				$dueDate 		= $invoice->due_date;
				$amount 		= $invoice->amount;
				$paidDate 		= $invoice->date_paid;
				$status 		= $invoice->status;
				
				//get customer name;
				$CustomerData = $this->getCustomerInfo($Custid);
				$site_id = $CustomerData->site_id;
				$short_name = $CustomerData->short_name;
				$cterms = $CustomerData->commercial_term;
								
				//get Terms name;
				$termData = $this->getTermInfo($cterms);
				$criteria = $termData->commercial_name;
				
				//get customer site_id;
				$CustomerData = $this->getSiteInfo($site_id);
				$siteID = $CustomerData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$short_name</td>
                        <td>$invoiceDate</td>
                        <td>$criteria</td>
                        <td>N".number_format($amount,2)."</td>
                        <td>$dueDate</td>
                        <td>$paidDate</td>
                     </tr>";
			 }

			// print the navigation link
			echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Invoice in this Category</div>';   
	   }
	}
	
	function gettickets_status($status) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM tickets where status = '$status' ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" class=\"table table-bordered table-hover table-striped display\" id=\"example\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Ref</th>
                    <th>Site ID</th>
                    <th>Subject</th>
                    <th>Severity</th>
                    <th>Date Created</th>
                    <th>Status</th>
                    <th width=\"20%\" scope=\"col\" colspan=\"2\">Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$tRef 			= $ticket->ticket_ref;
				$sid 			= $ticket->site_id;
				$Subject 		= $ticket->ticket_subject;				
				$time	 		= date("d M, Y: H:m:i",$ticket->time_created);
				$status 		= $ticket->status;
				$severity 		= $ticket->severity;				
				
				//get site_ID
				$siteData = $this->getSiteInfo($sid );
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>#$tRef </td>
                        <td>$site_id ";
						if($indicator=="new ticket") {echo"<span class=\"badge bg-danger\">New</span>"; }
						echo"</td>
                        <td>$Subject</td>
                        <td><span class=\"label ";
							switch($severity) {
									case "Low Level":
									echo"label-info";
									break;
									case "Normal Level":
									echo"label-primary";
									break;
									case "High Level":
									echo"label-danger";
									break;
								}
							echo"\">$severity</span></td>
                        <td>$time</td>
                        <td><div class=\"label ";
						if($status=="1") {echo"label-success"; }else{echo"label-danger";}
						echo"\">";
						if($status=="1") {echo"Closed Ticket"; }else{echo"Open Ticket";}
						echo"</div></td>
                        <td><a href=\"open_ticket.php?tid=$id \">
					  <span class=\"add-on small-size\"> View</span></a></td>
                        <td><a href=\"#\">
					  <span class=\"add-on small-size\">Edit</span></a></td>
					  </tr>";
			 }
			// print the navigation link
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Ticket Yet</div>';   
	   }
	}
	
	function Open_tickets() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM tickets where status = '0' ORDER BY time_created desc Limit 0,4";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-striped\">
               <thead>
                    <tr>
                    <th>Site</th>
                    <th>Subject</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$sid 			= $ticket->site_id;
				$Subject 		= $ticket->ticket_subject;				
				$time	 		= date("d M, Y: H:m:i",$ticket->time_created);
				$status 		= $ticket->status;
				
				//get site_ID
				$siteData = $this->getSiteInfo($sid );
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td><a href=\"open_ticket.php?tid=$id \">$site_id</a></td>
                        <td>$Subject</td>
					  </tr>";
			 }
			 echo"<tbody></table>";
		}else{
			echo'<div class="alert alert-success">No Ticket Yet</div>';   
	   }
	}
	
	function Closed_tickets() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM tickets where status = '1' ORDER BY time_created desc Limit 0,4";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-striped\">
               <thead>
                    <tr>
                    <th>Site</th>
                    <th>Subject</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($ticket = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $ticket->ticket_id;
				$sid 			= $ticket->site_id;
				$Subject 		= $ticket->ticket_subject;				
				$time	 		= date("d M, Y: H:m:i",$ticket->time_created);
				$status 		= $ticket->status;
				
				//get site_ID
				$siteData = $this->getSiteInfo($sid );
				$site_id = $siteData->site_id;
				
				echo"<tr>
                        <td><a href=\"open_ticket.php?tid=$id \">$site_id</a></td>
                        <td>$Subject</td>
					  </tr>";
			 }
			 echo"<tbody></table>";
		}else{
			echo'<div class="alert alert-success">No Closed Yet</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;
	}
	
	function ChangePassword($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			
			$time = time();

			$user_id    		= $this->mysql_prepare_value($post['user_id']);
			$currPassword   = $this->mysql_prepare_value($post['currPassword']);
			$newPassword1   = $this->mysql_prepare_value($post['newPassword1']);
			$newPassword2   = $this->mysql_prepare_value($post['newPassword2']);
			
			
			$query = "select password from app_users where id = '$user_id' and password = '".md5($currPassword)."'";
			$result = mysql_query($query)or die(mysql_error());
			$countRow = mysql_num_rows($result);
			if($countRow==0) {
				return '<div class="alert alert-danger"><i class="fa fa-check"></i>Current Password is Wrong</div>';
			}elseif($newPassword1!=$newPassword2) {
				return '<div class="alert alert-danger"><i class="fa fa-check"></i>New Password Does not Match</div>';
			}else{
			
				$query_I = "update  $tbl set
							password = '".md5($newPassword1)."'
							where id = '$user_id'";
						
				$result_I = mysql_query($query_I)or die(mysql_error());
				
				if($result_I) {
					return '<div class="alert alert-success"><i class="fa fa-check"></i>Password Changed Successfull</div>';
				}
			}
		}
	}
	
	function addCPD($post,$process) {
		$this->connect_db();
		if(isset($process)) {			
			$time = time();
			$cpd  = $this->mysql_prepare_value($post['cpd']);
			$sid  = $this->mysql_prepare_value($post['sid']);
			
			//update the current cpd to have and end date
			$query = mysql_query("update cpd_tbl set end_time='$time' where site_id = '$sid' and end_time='0'")or die(mysql_error());
			if($query) {
				$queryI = "insert into cpd_tbl values('','$sid','$cpd','$time','0')";
				$resultI = mysql_query($queryI)or die(mysql_error());
				
				return '<div class="alert alert-success">New CPD Added Successfully</div>';
			}
		}
	}
	
	function updateServiceCost($post,$process) {
		$this->connect_db();
		if(isset($process)) {			
			$time = time();
			$servicecost  = $this->mysql_prepare_value($post['servicecost']);
			$sid  = $this->mysql_prepare_value($post['sid']);
			
			//update the current cpd to have and end date
			$query = mysql_query("update site set service_cost='$servicecost' where id = '$sid'")or die(mysql_error());
			if($query) {
				return '<div class="alert alert-success">Site Service Cost Updated</div>';
			}
		}
	}
	
	function updateSiteSettings($post,$process) {
		$this->connect_db();
		if(isset($process)) {			
			$time = time();
			$supply  = $this->mysql_prepare_value($post['supply_approve']);
			$service  = $this->mysql_prepare_value($post['service_approve']);
			$sid  = $this->mysql_prepare_value($post['sid']);
			
			//update the current cpd to have and end date
			$query = mysql_query("update site set approve_supply='$supply', approve_service='$service' where id = '$sid'")or die(mysql_error());
			if($query) {
				return '<div class="alert alert-success">Site Settings Saved</div>';
			}
		}
	}
	
	function addServiceItem($post,$process) {
		$this->connect_db();
		if(isset($process)) {			
			$time = time();
			$serviceitem  = $this->mysql_prepare_value($post['serviceitem']);
			$servicecost  = $this->mysql_prepare_value($post['servicecost']);
			$sid  = $this->mysql_prepare_value($post['sid']);
			
			//update the current cpd to have and end date
			$query = mysql_query("insert into site_service_item values('','$sid','$serviceitem','$servicecost','".$_SESSION['userid']."','$time')")or die(mysql_error());
			if($query) {
				return '<div class="alert alert-success">New Service Item Added Successfully</div>';
			}
		}
	}
	
	function getall_cpd($sid) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM cpd_tbl where site_id = '$sid' ORDER BY id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
			   <thead>
					<tr>
					<th>CPD</th>
					<th>Start Date</th>
					<th>End Date</th>
					<th>Action</th>
					</tr>
				</thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($cpd = mysql_fetch_object($result)) {
				$sn += 1;
				$id 	= $cpd->id;
				$cpdValue 	= $cpd->cpd;
				$sdate  = date("D d M, Y",$cpd->start_time);
				$edate  = $cpd->end_time;
				
				echo"<tr>
				<td>$cpdValue</td>
				<td>$sdate</td>
				<td>";
				if($edate==0) { echo"still current"; }else{echo date("D d M, Y",$cpd->end_time);}
				echo"</td>
				<td>";
				if($edate==0) { echo "none";}else {
					if($_SESSION['level']=='Supervisor') {
						echo"<a href=\"".$_SERVER['PHP_SELF']."?cid=$id&siteID=$sid&ac=del#cpd\" onclick=\"return confirm('Are you sure you want to delete this?');\">
							<span class=\"add-on small-size\"> Delete</span>
							</a>";
					}else{
						echo"NA";
					}
				}
				echo"</td>
			 </tr>";
		}
			// print the navigation link
		echo "</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No CPD Yet</div>';   
		}
	}
	
	function getSiteServiceItems($sid) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site_service_item where site_id = '$sid' ORDER BY id desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table width=\"100%\" border=\"0\" class=\"table table-bordered table-striped\">
			   <thead>
					<tr>
					<th>Sn</th>
					<th>Item</th>
					<th>Cost</th>
					<th>Action</th>
					</tr>
				</thead>
				<tbody>";
			 $sn = 0;
			 $total_cost = 0;
			 while($item = mysql_fetch_object($result)) {
				$rand = rand();
				$sn += 1;
				$id 	= $item->id;
				$itemname 	= $item->service_item;
				$itemcost = $item->item_cost;
				
				echo"<tr>
				<td>$sn</td>
				<td>$itemname </td>
				<td>$itemcost </td>
				<td>";
				if($_SESSION['level']=='Supervisor'){
					echo"<a href=\"".$_SERVER['PHP_SELF']."?itid=$id&siteID=$sid&delit=$rand#serviceitem\" onclick=\"return confirm('Are you sure you want to remove this?');\">
					<span class=\"add-on small-size\"> Remove</span>
					</a>";
				}else{
					echo"NA";
				}
				echo"</td>
			 </tr>";
			 
			 $total_cost +=$itemcost;
		}
			// print the navigation link
		echo "<tr>
			<td align=\"right\" colspan=\"2\">Total</td>
			<td>$total_cost</td>
			</tr>
			</tbody>
				 </table>";
		}else{
			echo'<div class="alert alert-danger">No Service Item Added Yet</div>';   
		}
	}
	
	function updateAcctImg($file,$process) {
		$this->connect_db();
		if(isset($process)) {
			if($file['acct_img']['size'] !=0){
				//*******check if upload file is an image file*******//
				// array of valid extensions
				$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
				// get extension of the uploaded file
				$fileExtension = strrchr($file['acct_img']['name'], ".");
				if (in_array($fileExtension, $validExtensions)) {
					$surfix = time();
					//resize profile picture
					$manipulator = new ImageManipulator($file['acct_img']['tmp_name']);
					// resizing to 1170x711
					$newImage = $manipulator->resample(215, 215);
					$target_path = "acct_img/";
					$target_path = $target_path . basename($file['acct_img']['name']);
					//$imgName = $surfix.basename($_FILES['passport']['name']);
					$manipulator->save($target_path);
					$imagePath = $target_path;
					//convert to binary
					$img2Binary = $this->loadImage($imagePath);
					
					
					$query ="update app_users set has_img = 'yes', acct_img = '$img2Binary' where id='".$_SESSION['userid']."'";
					$result = mysql_query($query)or die(mysql_error());
					
					if($result) {
						unset($_SESSION['profileimg']);
						session_start();
						$_SESSION['profileimg'] = "yes";
						
						return '<div class="alert alert-success">Account Image Updated Successfully</div>';	
					}
							
				}else {
					return "<div class=\"alert alert-danger\">The file you tried to upload is not a valid Image</div>";
				}
			}else {

			}	return "<div class=\"alert alert-danger\">No file selected</div>";
		}
	} 
	
	function getSiteAvailableHeight($sid) {
		$this->connect_db();
		
		$query = mysql_query("select sum(height_occupied) as totalHieght from site_tenants where site_id='$sid'")or die(mysql_error());
		$height = mysql_fetch_object($query);
		$tHieght = $height->totalHieght;
		
		return $tHieght;
	}
	
	function getCurrentCPD($sid) {
		$this->connect_db();
		
		$query = mysql_query("select * from cpd_tbl where site_id='$sid' and end_time='0'")or die(mysql_error());
		$cpd = mysql_fetch_object($query);
		$cpdValue = $cpd->cpd;
		
		return $cpdValue;
	}
	
	function getSiteCurrSupplyStats($sid) {
		$this->connect_db();
		
		$query = mysql_query("select * from supply_curr_stats where site_id='$sid'")or die(mysql_error());
		$Stats = mysql_fetch_object($query);
		
		return $Stats;
	}
	
	function drawCharts($post,$process) {
		$this->connect_db(); 
		
		if(isset($process)) {
			$siteID = $post['siteID'];
			$year = $post['year'];
			$sql = "select sum(supplied_qty) as consumption, month,month_order,year from supplies_details where ";
			
			if($siteID!="all") { $sql .= "site_id = '$siteID' and ";}
			
			$sql .= "year='$year' group by month order by month_order";
			$res = mysql_query($sql)or die(mysql_error());
			$countRow = mysql_num_rows($res);	
				
			if($countRow>0){
				$barData = "";
				$donutData = "";
									
				while($data = mysql_fetch_object($res)) {
					$month = $data->month;
					$consumption = $data->consumption;
								
					$barData .= '{y:"'.$month.'",a:'.$consumption.'},';
					
					$donutData .= '{label:"'.$month.'",value:'.$consumption.'},';
				}
			
			
								
				return '<script type="text/javascript">
				$(function() {

						//BAR CHART
						var bar = new Morris.Bar({
						element: "bar-chart",
						barSizeRatio:0.2,
						data : [
							'.substr($barData,0,-1).'
						],
						barColors: ["#00a65a"],
						xkey: "y",
						ykeys: ["a"],
						labels: ["Diesel"],
						hideHover: "auto"
						});
						
						//DONUT CHART
						var donut = new Morris.Donut({
						  element: "sales-chart",
						  barSizeRatio:0.2,
						  colors: ["#3c8dbc", "#f56954", "#00a65a","#a0d0e0","#fac22a","#c12283","#ff3378","#0abab5","#b25b00","#ff6600","#9a0000","#d2879b"],
						  data: [
							'.substr($donutData,0,-1).'
						  ],
						  hideHover: "auto"
						});
					
					});
					
					</script>
					
					<div class="col-md-6 nopad-right">
				<!-- panel -->
				<div class="panel panel-piluku">
					<div class="panel-heading">
						<h3 class="panel-title">
							Bar Chart of Diesel Consumption in Litres
						</h3>
					</div>
					<div class="panel-body">
					<div class="chart" id="bar-chart" style="height: 300px;"></div>
					</div>
				</div>
				<!-- /panel -->
			</div>
				
				<div class="col-md-6 nopad-right">
				<!-- panel -->
				<div class="panel panel-piluku">
					<div class="panel-heading">
						<h3 class="panel-title">
							Donut Chart of Diesel Consumption in Litres
						</h3>
					</div>
					<div class="panel-body">
					<div class="chart" id="sales-chart" style="height: 300px; position: relative;"></div>
					</div>
				</div>
				<!-- /panel -->
			</div>
			<!-- /col-md-6 -->';
			
			}else{
			
				return "<div class=\"col-md-12 nopad-right\">
					<!-- panel -->
					<div class=\"panel panel-piluku\">
						<div class=\"panel-heading\">
							<h3 class=\"panel-title\">
								Donut Chart of Diesel Consumption in Litres
							</h3>
						</div>
						<div class=\"panel-body\">
						<div class=\"alert alert-danger\">No data for this period</div>
						</div>
					</div>
					<!-- /panel -->
				</div>
				<!-- /col-md-12 -->";
			}
		}
	}	
	
	function DieselExpensesChart() {
		$this->connect_db(); 	
			
			$sql = "select sum(sup.cost) as amount, sup.site_id, s.id,s.region 
					from  supplies sup join site s on sup.site_id = s.id 
					group by s.region order by s.region";
			$res = mysql_query($sql)or die(mysql_error());
			$countRow = mysql_num_rows($res);	
				
			if($countRow>0){
				$barData = "";
				$donutData = "";
									
				while($data = mysql_fetch_object($res)) {
					$region = $data->region;
					$amount = $data->amount;
								
					$barData .= '{y:"'.$region.'",a:'.$amount.'},';
					
					//$donutData .= '{label:"'.$month.'",value:'.$consumption.'},';
				}
			
			
								
				return '<script type="text/javascript">
				$(function() {

						//BAR CHART
						var bar = new Morris.Bar({
						element: "bar-chart-diesel",
						barSizeRatio:0.2,
						data : [
							'.substr($barData,0,-1).'
						],
						barColors: function (row) {
						console.log("--> "+row.label);
						if(row.label == "NC") return "#2196F3";
						else if(row.label == "NE") return "#5CB85C";
						else if(row.label == "NW") return "#D9534F";
						else if(row.label == "SE") return "#F0AD4E";
						else if(row.label == "SS") return "#5BC0DE";
						else if(row.label == "SW") return "#F7941D";
						},
						xkey: "y",
						ykeys: ["a"],
						labels: ["Amount"],
						hideHover: "auto",
						xLabelAngle: 0, 
						xLabelMargin: 10
						});
					
					});
					
					</script>
					
				
				
					<div class="chart" id="bar-chart-diesel"></div>';
			
			}else{
			
				return "<div class=\"alert alert-danger\">No Diesel Expenses yet</div>";
			}
	}	
	
	function ServiceExpensesChart() {
		$this->connect_db(); 		
			
		$sql = "select sum(ser.cost) as amount, ser.site_id, s.id,s.region 
					from  servicing ser join site s on ser.site_id = s.id 
					group by s.region order by s.region";
		$res = mysql_query($sql)or die(mysql_error());
		$countRow = mysql_num_rows($res);	
			
		if($countRow>0){
			$barData = "";
			$donutData = "";
								
			while($data = mysql_fetch_object($res)) {
				$region = $data->region;
				$amount = $data->amount;
							
				$barData .= '{y:"'.$region.'",a:'.$amount.'},';
				
				//$donutData .= '{label:"'.$month.'",value:'.$consumption.'},';
			}
		
		
							
			return '<script type="text/javascript">
			$(function() {

					//BAR CHART
					var bar = new Morris.Bar({
					element: "bar-chart-exp-service",
					barSizeRatio:0.2,
					data : [
						'.substr($barData,0,-1).'
					],
					barColors: function (row) {
					console.log("--> "+row.label);
					if(row.label == "NC") return "#2196F3";
					else if(row.label == "NE") return "#5CB85C";
					else if(row.label == "NW") return "#D9534F";
					else if(row.label == "SE") return "#F0AD4E";
					else if(row.label == "SS") return "#5BC0DE";
					else if(row.label == "SW") return "#F7941D";
					},
					xkey: "y",
					ykeys: ["a"],
					labels: ["Amount"],
					hideHover: "auto",
					xLabelAngle: 0
					});
				
				});
				
				</script>
				
			
			
				<div class="chart" id="bar-chart-exp-service"></div>';
		
		}else{
		
			return "<div class=\"alert alert-danger\">No Service Expenses yet</div>";
		}
	}
	
	function ExpensesChartsType() {
		$this->connect_db(); 		
			
		$sql = "select sum(ex_amount) as amount, exp_type from expenses
		group by exp_type order by exp_type";
		$res = mysql_query($sql)or die(mysql_error());
		$countRow = mysql_num_rows($res);	
			
		if($countRow>0){
			$barData = "";
			$donutData = "";
								
			while($data = mysql_fetch_object($res)) {
				$expType = $data->exp_type;
				$amount = $data->amount;
							
				$barData .= '{y:"'.$expType.'",a:'.$amount.'},';
				
				//$donutData .= '{label:"'.$month.'",value:'.$consumption.'},';
			}
		
		
							
			return '<script type="text/javascript">
			$(function() {

					//BAR CHART
					var bar = new Morris.Bar({
					element: "bar-chart-exptype",
					barSizeRatio:0.2,
					data : [
						'.substr($barData,0,-1).'
					],
					barColors: ["#116493"],
					xkey: "y",
					ykeys: ["a"],
					labels: ["Amount"],
					hideHover: "auto",
					xLabelAngle: 0
					});
				
				});
				
				</script>
				
			
			
				<div class="chart" id="bar-chart-exptype"></div>';
		
		}else{
		
			return "<div class=\"alert alert-danger\">No Exenses yet</div>";
		}
	}
	
	function SiteCharts() {
		$this->connect_db(); 
		
			
			$sql = "select count(site_id) as totatl_sites, region from  site group by region order by region";
			$res = mysql_query($sql)or die(mysql_error());
			$countRow = mysql_num_rows($res);	
				
			if($countRow>0){
				$barData = "";
				$donutData = "";
									
				while($data = mysql_fetch_object($res)) {
					$region = $data->region;
					$totatlSites = $data->totatl_sites;
								
					$barData .= '{y:"'.$region.'",a:'.$totatlSites.'},';
				}			
								
				return '<script type="text/javascript">
				$(function() {

						//BAR CHART
						var bar = new Morris.Bar({
						element: "bar-chart-sites",
						barSizeRatio:0.55,
						data : [
							'.substr($barData,0,-1).'
						],
						barColors: function (row, series, type) {
						console.log("--> "+row.label, series, type);
						if(row.label == "NC") return "#2196F3";
						else if(row.label == "NE") return "#5CB85C";
						else if(row.label == "NW") return "#D9534F";
						else if(row.label == "SE") return "#F0AD4E";
						else if(row.label == "SS") return "#5BC0DE";
						else if(row.label == "SW") return "#F7941D";
						},
						xkey: "y",
						ykeys: ["a"],
						labels: ["Sites"],
						hideHover: "auto",
						xLabelAngle: 0, 
						xLabelMargin: 10
						});
					
					});
					
					</script>
					
				
				
					<div class="chart" id="bar-chart-sites"></div>';
			
			}else{
			
				return "<div class=\"alert alert-danger\">No Sites yet</div>>";
			}
	}
	
	function CustomerCharts() {
		$this->connect_db(); 
		
			
			$sql = "select count(id) as totalcustomer, customer_id from site_tenants group by customer_id order by customer_id";
			$res = mysql_query($sql)or die(mysql_error());
			$countRow = mysql_num_rows($res);	
				
			if($countRow>0){
				$barData = "";
				$donutData = "";
									
				while($data = mysql_fetch_object($res)) {
					$custid = $data->customer_id;
					$totatlCust = $data->totalcustomer;
					
					//customer data
					$custData = $this->getCustomerInfo($custid);
					$customer = $custData->short_name;
								
					$barData .= '{y:"'.$customer.'",a:'.$totatlCust.'},';
				}			
								
				return '<script type="text/javascript">
				$(function() {

						//BAR CHART
						var bar = new Morris.Bar({
						element: "bar-chart-customer",
						barSizeRatio:0.4,
						data : [
							'.substr($barData,0,-1).'
						],
						barColors: ["#00a65a"],
						xkey: "y",
						ykeys: ["a"],
						labels: ["Total"],
						hideHover: "auto",
						padding: 50,
						xLabelAngle: 60
						});
					
					});
					
					</script>
					
				
				
					<div class="chart" id="bar-chart-customer"></div>';
			
			}else{
			
				return "<div class=\"alert alert-danger\">No Customer yet</div>";
			}
	}
	
	function CustomerLevelCharts() {
		$this->connect_db(); 
		
			
			$sql = "select count(id) as totalcustomer, customer_id,state from site_tenants group by state order by customer_id";
			$res = mysql_query($sql)or die(mysql_error());
			$countRow = mysql_num_rows($res);	
				
			if($countRow>0){
				$barData = "";
				$donutData = "";
									
				while($data = mysql_fetch_object($res)) {
					$custid = $data->customer_id;
					$totatlCust = $data->totalcustomer;
					$CustState = $data->state;
													
					$barData .= '{y:"'.$CustState.'",a:'.$totatlCust.'},';
				}			
								
				return '<script type="text/javascript">
				$(function() {

						//BAR CHART
						var bar = new Morris.Bar({
						element: "bar-chart-customer-level",
						barSizeRatio:0.2,
						data : [
							'.substr($barData,0,-1).'
						],
						barColors: function (row, series, type) {
						console.log("--> "+row.label, series, type);
						if(row.label == "ITP") return "#2196F3";
						else if(row.label == "Site Provision") return "#5CB85C";
						else if(row.label == "Live") return "#D9534F";
						else if(row.label == "Decommissioned") return "#F0AD4E";
						},
						xkey: "y",
						ykeys: ["a"],
						labels: ["Total"],
						hideHover: "auto",
						padding: 50,
						xLabelAngle: 60
						});
					
					});
					
					</script>
					
				
				
					<div class="chart" id="bar-chart-customer-level"></div>';
			
			}else{
			
				return "<div class=\"alert alert-danger\">No Customer yet</div>";
			}
	}
	
	function TicketsCharts() {
		$this->connect_db(); 		
			
			$sql = "select count(ticket_id) as totalTickets, severity from tickets group by severity order by ticket_id";
			$res = mysql_query($sql)or die(mysql_error());
			$countRow = mysql_num_rows($res);	
				
			if($countRow>0){
				$barData = "";
				$donutData = "";
									
				while($data = mysql_fetch_object($res)) {
					$totalTickets = $data->totalTickets;
					$TicketSeverity = $data->severity;
													
					$barData .= '{y:"'.$TicketSeverity.'",a:'.$totalTickets.'},';
				}			
								
				return '<script type="text/javascript">
				$(function() {

						//BAR CHART
						var bar = new Morris.Bar({
						element: "bar-chart-ticket",
						barSizeRatio:0.2,
						data : [
							'.substr($barData,0,-1).'
						],
						barColors: function (row) {
						console.log("--> "+row.label);
						if(row.label == "Low Level") return "#2196F3";
						else if(row.label == "Normal Level") return "#5CB85C";
						else if(row.label == "High Level") return "#D9534F";
						},
						xkey: "y",
						ykeys: ["a"],
						labels: ["Total"],
						hideHover: "auto",
						padding: 50,
						xLabelAngle: 60
						});
					
					});
					
					</script>
					
				
				
					<div class="chart" id="bar-chart-ticket"></div>';
			
			}else{
			
				return "<div class=\"alert alert-danger\">No Tickets yet</div>";
			}
	}	
	
	function InvoiceChart() {
		$this->connect_db(); 		
			
		$sql = "select count(id) as totalInvoice, payment_status from invoice_customer group by payment_status order by id";
		$res = mysql_query($sql)or die(mysql_error());
		$countRow = mysql_num_rows($res);	
			
		if($countRow>0){
			$barData = "";
			$donutData = "";
								
			while($data = mysql_fetch_object($res)) {
				$totalInvoice = $data->totalInvoice;
				$payment_status = $data->payment_status;
							
				$barData .= '{y:"'.$payment_status.'",a:'.$totalInvoice.'},';
				
				//$donutData .= '{label:"'.$month.'",value:'.$consumption.'},';
			}
		
		
							
			return '<script type="text/javascript">
			$(function() {

					//BAR CHART
					var bar = new Morris.Bar({
					element: "bar-chart-invoice",
					barSizeRatio:0.2,
					data : [
						'.substr($barData,0,-1).'
					],
					barColors: function (row) {
					console.log("--> "+row.label);
					if(row.label == "Paid") return "#5CB85C";
					else if(row.label == "Not Paid") return "#D9534F";
					},
					xkey: "y",
					ykeys: ["a"],
					labels: ["Total"],
					hideHover: "auto",
					xLabelAngle: 0
					});
				
				});
				
				</script>
				
			
			
				<div class="chart" id="bar-chart-invoice"></div>';
		
		}else{
		
			return "<div class=\"alert alert-danger\">No Invoice Issued yet</div>";
		}
	}	
	
	function SupplyLevelChart() {
		$this->connect_db(); 		
			
		$sql = "select count(id) as total, diesel_level_status from supplies group by diesel_level_status,status having status = '0' order by diesel_level_status";
		$res = mysql_query($sql)or die(mysql_error());
		$countRow = mysql_num_rows($res);	
			
		if($countRow>0){
			$barData = "";
			$donutData = "";
								
			while($data = mysql_fetch_object($res)) {
				$total = $data->total;
				$diesel_level_status = $data->diesel_level_status;
							
				$barData .= '{y:"'.$diesel_level_status.'",a:'.$total.'},';
				
				//$donutData .= '{label:"'.$month.'",value:'.$consumption.'},';
			}
		
		
							
			return '<script type="text/javascript">
			$(function() {

					//BAR CHART
					var bar = new Morris.Bar({
					element: "bar-chart-sLevel",
					barSizeRatio:0.2,
					data : [
						'.substr($barData,0,-1).'
					],
					barColors: function (row) {
					console.log("--> "+row.label);
					if(row.label == "High") return "#5CB85C";
					else if(row.label == "Normal") return "#F0AD4E";
					else if(row.label == "Low") return "#D9534F";
					},
					xkey: "y",
					ykeys: ["a"],
					labels: ["Total"],
					hideHover: "auto",
					xLabelAngle: 60
					});
				
				});
				
				</script>
				
			
			
				<div class="chart" id="bar-chart-sLevel"></div>';
		
		}else{
		
			return "<div class=\"alert alert-danger\">No Supplies yet</div>";
		}
	}
	
	
	function displaySiteSupplyMode($siteID) {
		$this->connect_db();
		//retrive current supply details
		$SiteSupply = "select id,supply_date,DATEDIFF(CURDATE(),supply_date) as days_past,cpd,next_supply_date,time_created 
						from supplies where site_id = '$siteID' and status = '0' order by time_created desc limit 0,1";
		$SiteSupplyResult = mysql_query($SiteSupply)or die(mysql_error());
		$countRow = mysql_num_rows($SiteSupplyResult);
		
		if($countRow>0) {
			$SiteSupplyData = mysql_fetch_object($SiteSupplyResult)or die(mysql_error());
			$supplyID = $SiteSupplyData->id;
			$supplyDate = $SiteSupplyData->supply_date;
			$nextSupplyDate = $SiteSupplyData->next_supply_date;
			$daysPast =  $SiteSupplyData->days_past;
			$currCPD =  $SiteSupplyData->cpd; 
			
			$cpdPerGen = $currCPD/2;
			
			$estConsumption = $daysPast * $cpdPerGen;
			
			//get number of diesel tanks supplied to on site
			$siteData = $this->getSiteInfo($siteID);
			$siteTanks = $siteData->tank_mode;
			
			echo"<div class=\"col-md-12\">
				<!-- panel -->
				<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							<table width=\"100%\">
								<tr>
									<td width=\"90%\">
										Site Supply Status ($siteTanks active tanks on Site.)
									</td>
									<td align=\"right\">
										<a href=\"site_supply_history.php?siteID=$siteID\" class=\"btn btn-primary\">Site Supply History</a>
									</td>
								</tr>
							</table>
						</h3>
					</div>
					<div class=\"panel-body\">
					<div class=\"panel-group piluku-accordion\" id=\"accordion\" role=\"tablist\" aria-multiselectable=\"true\">";
					$tabID = 1;
					$tankCounter = 1;
			//get supply details for each supplied tank
			//retrive current supply details
			$TankSupply = "select id,tank,initial_stock,supplied_qty,new_stock,time_created from supplies_details where supply_id = '$supplyID'";
			$TankSupplyResult = mysql_query($TankSupply)or die(mysql_error());
			while($TankSupplyData = mysql_fetch_object($TankSupplyResult)) {
			
				$tank = $TankSupplyData->tank;
				$initialStock = $TankSupplyData->initial_stock;
				$qtySupplied = $TankSupplyData->supplied_qty;
				$totalStockAfterSupply = $TankSupplyData->new_stock; 
				
				$estStock = $totalStockAfterSupply  - $estConsumption;
				
				echo"<div class=\"panel panel-default\">
								<div class=\"panel-heading\" role=\"tab\" id=\"heading$tabID\">
								  <h3 class=\"panel-title\">
								  <table width=\"100%\">
								  <tr>
									<td width=\"90%\">
										<a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse$tabID\" aria-expanded=\"true\" aria-controls=\"collapse$tabID\">
										$tank
										</a>
									</td>
									<td align=\"right\">
										<a href=\"tank_history.php?siteID=$siteID&tn=$tankCounter\" class=\"btn btn-danger\" style=\"color:#fff;\">Tank Supply History</a>
									</td>
									</tr>
									</table>
								  </h3>
								</div>
								<div id=\"collapse$tabID\" class=\"panel-collapse collapse in\" role=\"tabpanel\" aria-labelledby=\"heading$tabID\">
								<div class=\"panel-body\">
									<div class=\"small-size\">
									<table id=\"example1\" class=\"table table-bordered table-hover\">
										<tbody> 
											<tr>
												<td><strong>Last Supply Date</strong></td>
												<td>$supplyDate</td>
												<td></td>
												<td><strong>Initial Stock</strong></td>
												<td>$initialStock Litres</td>
											</tr>
											<tr>
												<td><strong>Quantity Supplied</strong></td>
												<td>$qtySupplied Litres</td>
												<td></td>
												 <td><strong>Stock after Supplied</strong></td>
												<td>$totalStockAfterSupply Litres</td>
											</tr>
											<tr>
												<td><strong>Days from last Supply</strong></td>
												<td>";
												if($daysPast=="") { echo"No Supply Yet"; }else{ echo"$daysPast day(s)"; }
												echo"</td>
												<td></td>
												<td><strong>Est. Consumption (calculated)</strong></td>
												<td>$estConsumption Litres</td>
											</tr>
											<tr>
												<td><strong>Est. Stock Level (calculated)</strong></td>
												<td>$estStock Litres</td>
												<td></td>
												<td><strong>Next Supply Date</strong></td>
												<td>$nextSupplyDate</td>
											</tr>
											<tr>
												<td colspan=\"5\">Estimated Diesel Level<br />";
												$this->getdieselReading($siteID,$tank);
												echo"</td>
											</tr>
										</tbody>
									</table>
								</div>
								</div>
							 </div>
							</div>";
							
				$tabID++;
				$tankCounter++;			
			}
			
			echo"</div>
					</div>
						</div>
						<!-- /panel -->
					</div>";
		}else {
			echo"<div class=\"col-md-12\">
				<!-- panel -->
				<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							Site Supply Status
						</h3>
					</div>
					<div class=\"panel-body\">
					<div class=\"panel-group piluku-accordion\" id=\"accordion\" role=\"tablist\" aria-multiselectable=\"true\">
						<div class=\"alert alert-danger\">No Supply Made on Site Yet.</div>
					</div>
					</div>
						</div>
						<!-- /panel -->
					</div>";
		}
	}	
		
	function displaySiteSupplyMode2($siteID) {
		$this->connect_db();
		//retrive current supply details
		$SiteSupply = "select last_supply_date,DATEDIFF(CURDATE(),last_supply_date) as days_past,tank,initial_stock,qty,cpd,nxt_supply_date 
						from supply_curr_stats where site_id = '$siteID'";
		$SiteSupplyResult = mysql_query($SiteSupply)or die(mysql_error());
		
		//get number of diesel tanks supplied to on site
		$siteData = $this->getSiteInfo($siteID);
		$siteTanks = $siteData->tank_mode;
		
		echo"<div class=\"col-md-12\">
			<!-- panel -->
			<div class=\"panel panel-piluku\">
				<div class=\"panel-heading\">
					<h3 class=\"panel-title\">
						<table width=\"100%\">
							<tr>
								<td width=\"90%\">
									Site Supply Status ($siteTanks active tanks on Site.)
								</td>
								<td align=\"right\">
									<a href=\"site_supply_history.php?siteID=$siteID\" class=\"btn btn-primary\">Site Supply History</a>
								</td>
							</tr>
						</table>
					</h3>
				</div>
				<div class=\"panel-body\">
				<div class=\"panel-group piluku-accordion\" id=\"accordion\" role=\"tablist\" aria-multiselectable=\"true\">
						";
				$tabID = 1;
				$tankCounter = 1;
		while($SiteSupplyData = mysql_fetch_object($SiteSupplyResult)) {
		
			$tank = $SiteSupplyData->tank;
			$supplyDate = $SiteSupplyData->last_supply_date;
			$initialStock = $SiteSupplyData->initial_stock;
			$qtySupplied = $SiteSupplyData->qty;
			$totalStockAfterSupply = $qtySupplied + $initialStock;
			$daysPast =  $SiteSupplyData->days_past; 
			$currCPD =  $SiteSupplyData->cpd; 
			$nextSupplyDate = $SiteSupplyData->nxt_supply_date;
			
			$estConsumption = $daysPast * $currCPD;
			$estStock = $totalStockAfterSupply  - $estConsumption;
			
			echo"<div class=\"panel panel-default\">
							<div class=\"panel-heading\" role=\"tab\" id=\"heading$tabID\">
							  <h3 class=\"panel-title\">
							  <table width=\"100%\">
							  <tr>
								<td width=\"90%\">
									<a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse$tabID\" aria-expanded=\"true\" aria-controls=\"collapse$tabID\">
									$tank
									</a>
								</td>
								<td align=\"right\">
									<a href=\"tank_history.php?siteID=$siteID&tn=$tankCounter\" class=\"btn btn-danger\" style=\"color:#fff;\">Tank Supply History</a>
								</td>
								</tr>
								</table>
							  </h3>
							</div>
							<div id=\"collapse$tabID\" class=\"panel-collapse collapse in\" role=\"tabpanel\" aria-labelledby=\"heading$tabID\">
							<div class=\"panel-body\">
								<div class=\"small-size\">
								<table id=\"example1\" class=\"table table-bordered table-hover\">
									<tbody> 
										<tr>
											<td><strong>Last Supply Date</strong></td>
											<td>$supplyDate</td>
											<td></td>
											<td><strong>Initial Stock</strong></td>
											<td>$initialStock Litres</td>
										</tr>
										<tr>
											<td><strong>Quantity Supplied</strong></td>
											<td>$qtySupplied Litres</td>
											<td></td>
											 <td><strong>Stock after Supplied</strong></td>
											<td>$totalStockAfterSupply Litres</td>
										</tr>
										<tr>
											<td><strong>Days from last Supply</strong></td>
											<td>";
											if($daysPast=="") { echo"No Supply Yet"; }else{ echo"$daysPast day(s)"; }
											echo"</td>
											<td></td>
											<td><strong>Est. Consumption (calculated)</strong></td>
											<td>$estConsumption Litres</td>
										</tr>
										<tr>
											<td><strong>Est. Stock Level (calculated)</strong></td>
											<td>$estStock Litres</td>
											<td></td>
											<td><strong>Next Supply Date</strong></td>
											<td>$nextSupplyDate</td>
										</tr>
										<tr>
											<td colspan=\"5\">Estimated Diesel Level<br />";
											$this->getdieselReading($siteID,$tank);
											echo"</td>
										</tr>
									</tbody>
								</table>
							</div>
							</div>
						 </div>
						</div>";
						
			$tabID++;
			$tankCounter++;			
		}
		
		echo"</div>
				</div>
					</div>
					<!-- /panel -->
				</div>";
	}
	
	function siteGenerators($siteID) {
		$this->connect_db();
		//retrive site generators
		$genQuery = "SELECT * FROM power_source where site_id = '$siteID' and source_type = 'Gen' order by source_name";
		$genQueryResult = mysql_query($genQuery)or die(mysql_error());
		
		//get number of diesel tanks supplied to on site
		$siteData = $this->getSiteInfo($siteID);
		
		echo"<div class=\"col-md-12\">
			<!-- panel -->
			<div class=\"panel panel-piluku\">
				<div class=\"panel-heading\">
					<h3 class=\"panel-title\">
						<table width=\"100%\">
							<tr>
								<td width=\"90%\">
									Site Service Status
								</td>
								<td align=\"right\">
									<div class=\"btn-group\">
										<button class=\"btn btn-primary\" data-toggle=\"dropdown\">
											<span class=\"caret\"></span> Actions
										</button>
										<ul class=\"dropdown-menu dropdown-button-menu btn-drop\" role=\"menu\">
											<li><a href=\"site_service_history.php?siteID=$siteID\">Service History</a>
											</li>
										</ul>
									</div>
								</td>
							</tr>
						</table>
					</h3>
				</div>
				<div class=\"panel-body\">
				<div class=\"panel-group piluku-accordion\" id=\"accordion\" role=\"tablist\" aria-multiselectable=\"true\">
						";
				$tabID = 1;
		while($genQueryData = mysql_fetch_object($genQueryResult)) {
		
			$powerid = $genQueryData->power_id;
			$assetid = $genQueryData->gen_asset_id;
			$genName = $genQueryData->source_name;
			$hrInter = $genQueryData->service_hours_interval;
			
			//get asset serial for gen
			$assetData = $this->getAssetInfo($assetid);
			$serial = $assetData->asset_serial;
			
			//get gen current service info
			$serviceInfo = $this->getCurrServiceInfo($siteID,$powerid);
			$last_service_date = $serviceInfo->last_service_date;
			$serviceRunHr = $serviceInfo->curr_running_hrs;
			$nxtServiceRunHr = $serviceInfo->nxt_running_hrs;
			$nxt_service_date = $serviceInfo->nxt_service_date;
			$service_count = $serviceInfo->service_count;
			
			//get total hours ran
			$HoursRan = $this->getSourceRanHours($powerid);
			
			echo"<div class=\"panel panel-default\">
							<div class=\"panel-heading\" role=\"tab\" id=\"heading2$tabID\">
							  <h3 class=\"panel-title\">
									<a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse2$tabID\" aria-expanded=\"true\" aria-controls=\"collapse2$tabID\">
									$genName ($serial)
									</a>
							  </h3>
							</div>
							<div id=\"collapse2$tabID\" class=\"panel-collapse collapse in\" role=\"tabpanel\" aria-labelledby=\"heading2$tabID\">
							<div class=\"panel-body\">
								<div class=\"small-size\">
								<table id=\"example1\" class=\"table table-bordered table-hover\">
									<tbody> 
										<tr>
											<td><strong>Last Service Date</strong></td>
											<td>$last_service_date</td>
											<td></td>
											<td><strong>Next Service Date</strong></td>
											<td>$nxt_service_date</td>
										</tr>
										<tr>
											 <td><strong>Service Running Hour</strong></td>
											<td>$serviceRunHr Hours</td>
											<td></td>
											<td><strong>Next Service Running Hour</strong></td>
											<td>$nxtServiceRunHr Hours</td>
										</tr>
										<tr>
											<td><strong>Service Hour Interval</strong></td>
											<td>$hrInter Hours</td>
											<td></td>
											 <td><strong>Total Hours Ran</strong></td>
											<td>$HoursRan Hours</td>
										</tr>
										<tr>
											<td><strong>Service Count</strong></td>
											<td>$service_count</td>
											<td></td>
											 <td></td>
											<td></td>
										</tr>
									</tbody>
								</table>
							</div>
							</div>
						 </div>
						</div>";
						
			$tabID++;		
		}
		
		echo"</div>
				</div>
					</div>
					<!-- /panel -->
				</div>";
	}
	
	function getSourceRanHours($powerID) {
	
		$this->connect_db();
		$query = "select * from site_running_hours where power_id = '$powerID' order by time_created desc";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow>0) {
			$ranData = mysql_fetch_object($result)or die(mysql_error());
			$totalRan = $ranData->running_hrs;
			if($totalRan=="") { return 0; }else{ return $totalRan; }
		}
	}
	
	function sitePowerSources($siteID) {
		$this->connect_db();
		//retrive current supply details
		$SitePower = "select * from power_source where site_id='$siteID'";
		$SitePowerResult = mysql_query($SitePower)or die(mysql_error());
		
		echo"<div class=\"small-size\">
				<table id=\"example1\" class=\"table table-bordered table-hover\">
					<thead>
						<tr>
							<th><strong>SN</strong></th>
							<th><strong>Source Name</strong></th>
							<th><strong>Service Interval</strong></th>
							<th><strong>Total Ran Hour(s)</strong></th>
						</tr>
					</thead>
					<tbody>";
		$sn = 0;
		while($SitePowerData = mysql_fetch_object($SitePowerResult)) {
		
			$sn +=1;
			$powerid  = $SitePowerData->power_id;
			$sourceType = $SitePowerData->source_type;
			$sourceName = $SitePowerData->source_name;
			$sourceHoursint = $SitePowerData->service_hours_interval;
			$ranHours = $this->getSourceRanHours($powerid);
			
			echo"<tr>
					<td>$sn</td>
					<td>$sourceName</td>
					<td>";
					if($sourceType!="Gen"){echo"N/A";}else{echo $sourceHoursint." Hours";} 
					echo"</td>
					<td>";
					if($sourceType!="Gen"){echo"N/A";}else{echo $ranHours." Hours";} 
					echo"</td>
				</tr>";		
		}
		echo"</tbody>
			</table>
			</div>";
	}
	
	function EngrsAttachedSite($siteID) {
		$this->connect_db();
		//retrive current supply details
		$SitePower = "select * from site_users where site_id='$siteID'";
		$SitePowerResult = mysql_query($SitePower)or die(mysql_error());
		
		echo"<div class=\"small-size\">
				<table id=\"example1\" class=\"table table-bordered table-hover\">
					<thead>
						<tr>
							<th><strong>SN</strong></th>
							<th>#</th>
							<th><strong>Engr Name</strong></th>
							<th><strong>Action</strong></th>
						</tr>
					</thead>
					<tbody>";
		$sn = 0;
		while($data = mysql_fetch_object($SitePowerResult)) {
			$rand = rand();
			$sn +=1;
			$id  = $data->id;
			$engrid  = $data->user_id;
		
			
			//get userData
			$userData = $this->getUserInfo($engrid);
			$EngrID = $userData->id;
			$EngrName = $userData->name;
			
			echo"<tr>
					<td>$sn</td>
					<td><img src=\"acct-images.php?id=$EngrID\" width=\"50\"/></td>
					<td>$EngrName</td>
					<td>";
					if($_SESSION['level']=='Supervisor') {
						echo"<a href=\"".$_SERVER['PHP_SELF']."?siteID=$siteID&esid=$id&del=$rand\">remove</a>";
					}else {
						echo "NA";
					}
					echo"</td>
				</tr>";		
		}
		echo"</tbody>
			</table>
			</div>";
	}
	
	function getsiteAssets($siteID) {
		$this->connect_db();
		$SiteAsset = "select * from site_asset where site_id!='siteID'";
		$SiteAssetResult = mysql_query($SiteAsset)or die(mysql_error());
		
		echo"<div class=\"small-size\">
				<table id=\"example1\" class=\"table table-bordered table-hover\">
					<thead>
						<tr>
							<th><strong>SN</strong></th>
							<th><strong>Serial #</strong></th>
							<th><strong>Asset Name</strong></th>
							<th><strong>Lifespan (in months)</strong></th>
						</tr>
					</thead>
					<tbody>";
		$sn = 0;
		while($SiteAssetData = mysql_fetch_object($SiteAssetResult)) {
		
			$sn +=1;
			$assetid  = $SiteAssetData->asset_id;
			//get asset info
			$assetData = $this->getAssetInfo($assetid);
			$serial = $assetData->asset_serial;
			$assetName = $assetData->asset_name;
			$lifeSpan = $assetData->life_span;
			
			echo"<tr>
					<td>$sn</td>
					<td>$serial</td>
					<td>$assetName</td>
					<td>$lifeSpan</td>
				</tr>";		
		}
		echo"</tbody>
			</table>
			</div>";
	}
	
	function siteUserfiles($fileType) {
		$this->connect_db();
		$Userfiles = "select * from user_files where userid = '".$_SESSION['userid']."' and file_type='$fileType'";
		$UserfilesResult = mysql_query($Userfiles)or die(mysql_error());
		$countRow = mysql_num_rows($UserfilesResult);

		if($countRow>0) {
			echo "<div id=\"freewall\" class=\"free-wall\">";
			while($UserfilesrData = mysql_fetch_object($UserfilesResult)) {
			
				$sn +=1;
				$fileid  	= $UserfilesrData->file_id;
				$file_title = $UserfilesrData->file_title;
				$file_type	= $UserfilesrData->file_type;
				$file_url 	= $UserfilesrData->file_url;
				
				if($file_type=="img") {
					echo"<div class=\"brick\">
							<img src=\"$file_url\" title=\"this is the caption\" alt=\"post6\">
							<div class=\"info\">
								<h3>$file_title</h3>
								<h5>Location:<br />http://localhost:8080/bctek_new/$file_url</h5>
							</div>
						</div>";
				}elseif($file_type=="vid") {
					echo "<div class=\"brick\">
							<video controls=\"controls\" width=\"100%\">
								<source src=\"$file_url\" type=\"video/mp4\" />
							</video>
							<div class=\"info\">
								<h3>$file_title</h3>
								<h5>Location:<br />http://localhost:8080/bctek_new/$file_url</h5>
							</div>
						</div>";
				}
			}
			echo"</div>";
		}else{
			echo "<div class=\"alert alert-danger\"><i class=\"fa fa-times\"></i> No File Yet.</div>";
		}
	}
	
	function CountActiveSupplyNotification() {
		$this->connect_db();
		
		$Query = "select * from supply_notification where to_user='".$_SESSION['userid']."' and seen = 'no'";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		
		return $countRows;
	}
	
	function CountActiveDieselevelNotification() {
		$this->connect_db();
		
		$Query = "select * from dieselevel_notification where to_user='".$_SESSION['userid']."' and seen = 'no'";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		
		return $countRows;
	}
	
	function CountActiveServiceNotification() {
		$this->connect_db();
		
		$Query = "select * from service_notification where to_user='".$_SESSION['userid']."' and seen = 'no'";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		
		return $countRows;
	}
	
	function CountActiveTicketNotification() {
		$this->connect_db();
		
		$Query = "select * from ticket_notification where to_user='".$_SESSION['userid']."' and seen = 'no'";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		
		return $countRows;
	}
	
	function CountActiveNotification() {
		$this->connect_db();
		
		$Query = "select * from notifications where to_user = '".$_SESSION['userid']."' and seen = 'no'";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		
		return $countRows;
	}
	
	function notifyAlert($page) {
		$this->connect_db();
		
		$Query = "select * from notifications where to_user = '".$_SESSION['userid']."' order by time_created desc limit 0,4";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
		echo'<li>
				<a href="notifications.php" class="last_info">App Notifications</a>
			</li>';
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->notif_id;
				$notifType = $notify->notif_type;
				$typeID = $notify->ntype_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notif_desc;
				$seenStatus = $notify->seen;
				$date = date("M d, Y - h:ma", $notify->time_created);
					
					echo'<li';
					if($seenStatus=="no") {echo' style="background-color:#DDE1E6;" class="notify_class"';}
							echo'>
							<a href="notifications.php?notif_id='.$notif_id.'&tid='.$typeID.'&notif_t='.$notifType.'&sid='.$siteID.'">
								<span class="text_info"> '.$notifDesc.'</span> 
								<span class="time_info">'.$date.'</span> 
							</a>
						</li>';
			}
					
		echo'<li>
				<a href="#" onclick="ClearNotifications(\'notify_badge\',\'notify_class\',\'notifications\','.$_SESSION['userid'].')" class="last_info">Clear all</a>
			</li>';
			
		}else{
			
			echo'<li>
					<a href="#">
						<span class="text_info">No Notifications!</span>
					</a>
				</li>
				<li>
				<a href="notifications.php" class="last_info">See all work orders</a>
			</li>';
		}
		
	}	
	
	function DieselReordernotification($page) {
		$this->connect_db();
		
		$Query = "select * from dieselevel_notification where to_user = '".$_SESSION['userid']."' order by time_created desc limit 0,3";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
		echo'<li>
				<a href="site_reorder.php" class="last_info">Diesel Reorder Work Order</a>
			</li>';
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$workOrder = $notify->work_order;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
				$dieselPercent = $this->getSiteDieselPercent($siteID);
					
					echo'<li';
					if($seenStatus=="no") {echo' style="background-color:#DDE1E6;" class="dwo_class"';}
							echo'>
							<a href="view_supply.php?siteID='.$siteID.'&nid='.$notif_id.'"> 
								<span class="text_info"> '.$notifDesc.'<br/>
								<span class="label ';
								switch($workOrder) {
										case "Not Done":
										echo"label-danger";
										break;
										case "Done":
										echo"label-success";
										break;
									}
								echo'">'.$workOrder.'</span>
								</span> 
								<span class="text_info">
								<span style="text-align:right;font-size:10px;">'.$dieselPercent.'%</span>';								
								$this->getSiteDieselReading_notfy($siteID);
								echo'</span>
								<span class="time_info">'.$date.'</span> 
							</a>
						</li>';
			}
					
		echo'<li>
				<a href="#" onclick="ClearNotifications(\'dwo_badge\',\'dwo_class\',\'dieselevel_notification\','.$_SESSION['userid'].')" class="last_info">Clear all</a>
			</li>';
			
		}else{
			
			echo'<li>
					<a href="#">
						<span class="text_info">No Work Order!</span>
					</a>
				</li>
				<li>
				<a href="site_reorder.php" class="last_info">See all</a>
			</li>';
		}
		
	}		
	
	function DieselReorderWorkOrder() {
		$this->connect_db();
		
		$Query = "select * from dieselevel_notification where to_user = '".$_SESSION['userid']."' and work_order = 'Not Done' order by time_created desc limit 0,7";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$workOrder = $notify->work_order;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
				$dieselPercent = $this->getSiteDieselPercent($siteID);
				
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				echo"<li class=\"list-group-item\">
					<div class=\"ms-hover\">
						<label for=\"todo1\" style=\"display: block;\"><span></span><a href=\"view_supply.php?siteID=$siteID&nid=$notif_id\">Site $site_id ($dieselPercent%)<br />";
						$this->getSiteDieselReading_notfy($siteID);
						echo"</a></label>
					</div>
				</li>";
			}
					
			echo'<li class="list-group-item add-to-input">
                <a href="site_reorder.php" class="last_info">See all</a>
            </li>';
			
		}else{
			
			echo"<li class=\"list-group-item\">No Work Order!</li>";
		}
		
	}	
	
	function Supplynotification($page) {
		$this->connect_db();
		
		$Query = "select * from supply_notification where to_user = '".$_SESSION['userid']."' order by time_created desc limit 0,4";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
		echo'<li>
				<a href="supply_view.php" class="last_info">Supply Work Order</a>
			</li>';
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->id;
				$sid = $notify->supply_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$approved = $notify->approved_status;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
					
					echo'<li';
					if($seenStatus=="no") {echo' style="background-color:#DDE1E6;" class="swo_class"';}
							echo'>
							<a href="supply_workorder.php?sid='.$sid.'&nid='.$notif_id.'">
								<span class="text_info"> '.$notifDesc.'<br/>
								<span class="label ';
								switch($approved) {
										case "Pending":
										echo"label-info";
										break;
										case "Disapproved":
										echo"label-danger";
										break;
										case "Approved":
										echo"label-success";
										break;
									}
								echo'">'.$approved.'</span>
								</span> 
								<span class="time_info">'.$date.'</span> 
							</a>
						</li>';
			}
					
		echo'<li>
				<a href="#" onclick="ClearNotifications(\'swo_badge\',\'swo_class\',\'supply_notification\','.$_SESSION['userid'].')" class="last_info">Clear all</a>
			</li>';
			
		}else{
			
			echo'<li>
					<a href="#">
						<span class="text_info">No Supply Work Order!</span>
					</a>
				</li>
				<li>
				<a href="supply_view.php" class="last_info">See all</a>
			</li>';
		}
		
	}			
	
	function SupplyWorkOrder() {
		$this->connect_db();
		
		$Query = "select * from supply_notification where to_user = '".$_SESSION['userid']."' and work_order = 'Not Done' order by time_created desc limit 0,8";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->id;
				$sid = $notify->supply_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$workOrder = $notify->work_order;
				$date = date("D M d, Y - g:ia", $notify->time_created);
						
				echo"<li class=\"list-group-item\">
						<div class=\"ms-hover\">
							<label for=\"todo1\" style=\"display: block;\"><span></span><a href=\"supply_workorder.php?sid=$sid&nid=$notif_id\">$notifDesc</a></label>
						</div>
					</li>";
			}
			
			echo'<li class="list-group-item add-to-input">
                <a href="supply_view.php" class="last_info">See all</a>
            </li>';
			
		}else{
			
			echo"<li class=\"list-group-item\">No Supply Work Order!</li>";
		}
		
	}		
	
	function Servicenotification($page) {
		$this->connect_db();
		
		$Query = "select * from service_notification where to_user = '".$_SESSION['userid']."' order by time_created desc limit 0,4";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
		echo'<li>
				<a href="service_view.php" class="last_info">Service Work Order</a>
			</li>';
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->id;
				$sid = $notify->service_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$approved = $notify->approved_status;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
					
					echo'<li';
					if($seenStatus=="no") {echo' style="background-color:#DDE1E6;" class="swo2_class"';}
							echo'>
							<a href="service_workorder.php?sid='.$sid.'&nid='.$notif_id.'">
								<span class="text_info"> '.$notifDesc.'</span>
								<span class="label ';
								switch($approved) {
										case "Pending":
										echo"label-info";
										break;
										case "Disapproved":
										echo"label-danger";
										break;
										case "Approved":
										echo"label-success";
										break;
									}
								echo'">'.$approved.'</span> <br />
								<span class="time_info">'.$date.'</span> 
							</a>
						</li>';
			}
					
		echo'<li>
				<a href="#" onclick="ClearNotifications(\'swo2_badge\',\'swo2_class\',\'service_notification\','.$_SESSION['userid'].')" class="last_info">Clear all</a>
			</li>';
			
		}else{
			
			echo'<li>
					<a href="#">
						<span class="text_info">No Service!</span>
					</a>
				</li>
				<li>
				<a href="service_view.php" class="last_info">See all</a>
			</li>';
		}
		
	}			
	
	function ServiceWorkOrder() {
		$this->connect_db();
		
		$Query = "select * from service_notification where to_user = '".$_SESSION['userid']."' order by time_created desc limit 0,8";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->id;
				$sid = $notify->service_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
					echo"<li class=\"list-group-item\">
						<div class=\"ms-hover\">
							<label for=\"todo1\" style=\"display: block;\"><span></span><a href=\"service_workorder.php?sid=$sid&nid=$notif_id\">$notifDesc</a></label>
						</div>
					</li>";
			}
			
			echo'<li class="list-group-item add-to-input">
                <a href="service_view.php" class="last_info">See all</a>
            </li>';
			
		}else{
			
			echo'<li class="list-group-item add-to-input">No Service!</li>';
		}
		
	}	
	
	function Ticketnotification($page) {
		$this->connect_db();
		
		$Query = "select * from ticket_notification where to_user = '".$_SESSION['userid']."' order by time_created desc limit 0,6";
		$Result = mysql_query($Query)or die(mysql_error());
		$countRows = mysql_num_rows($Result);
		if($countRows>0) {
		echo'<li>
				<a href="mng_tickets.php" class="last_info">Tickets Notifications</a>
			</li>';
			
			while($notify = mysql_fetch_object($Result)) {
				
				$notif_id = $notify->id;
				$tid = $notify->ticket_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$ntype = $notify->notif_type;
				$seenStatus = $notify->seen;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
				//get Ticket Info
				$ticketData = $this->getTicketInfo($tid);
				$ref = $ticketData->ticket_ref;
				$tSubject = $this->limit_words($ticketData->ticket_subject,7);
				$severity = $ticketData->severity;
					
					echo'<li';
					if($seenStatus=="no") {echo' style="background-color:#DDE1E6;" class="t_class"';}
							echo'>
							<a href="open_ticket.php?tid='.$tid.'">
								<span class="text_info"> '.$notifDesc.' (#'.$ref.')<br/>';
								if($ntype=="ticket topic") {
									echo $tSubject.'...<br /><span class="label ';
									switch($severity) {
											case "Low Level":
											echo"label-info";
											break;
											case "Normal Level":
											echo"label-primary";
											break;
											case "High Level":
											echo"label-danger";
											break;
										}
									echo'">'.$severity.'</span>';
								}
								echo'</span> 
								<span class="time_info">'.$date.'</span> 
							</a>
						</li>';
			}
					
		echo'<li>
				<a href="#" onclick="ClearNotifications(\'t_badge\',\'t_class\',\'ticket_notification\','.$_SESSION['userid'].')" class="last_info">Clear all</a>
			</li>';
			
		}else{
			
			echo'<li>
					<a href="#">
						<span class="text_info">No Tickets!</span>
					</a>
				</li>
				<li>
				<a href="mng_tickets.php" class="last_info">See all</a>
			</li>';
		}
		
	}	
	
	function getSupplynotification() {	
		$this->connect_db();				
		$Query = "select * from supply_notification where to_user = '".$_SESSION['userid']."' order by time_created desc";
		$Result = mysql_query($Query)or die(mysql_error());
		$num_rows = mysql_num_rows($Result);
		   
	   if($num_rows > 0){
	   
			echo"<table class=\"table table-hover display\">
				<tbody>";
				
			 while($notify = mysql_fetch_object($Result)) {
			 
				$notif_id = $notify->id;
				$sid = $notify->supply_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$workOrder = $notify->work_order;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
				
				echo"<tr>
                        <td style=\"color:#000\">
							<a href=\"supply_workorder.php?sid=$sid&nid=$notif_id.\" class=\"";
						if($seenStatus=="Not Seen") {echo"info"; }
						echo"\">$notifDesc</a><br />
							<span class=\"label ";
								switch($workOrder) {
										case "Not Done":
										echo"label-danger";
										break;
										case "Done":
										echo"label-success";
										break;
									}
								echo"\">$workOrder</span>";
							echo"<span style=\"color:#ccc;\">$date</span>
						</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Supply Work Order!</div>';   
	   }
	}				
	
	function getServicenotification() {	
		$this->connect_db();				
		$Query = "select * from service_notification where to_user = '".$_SESSION['userid']."' order by time_created desc";
		$Result = mysql_query($Query)or die(mysql_error());
		$num_rows = mysql_num_rows($Result);
		   
	   if($num_rows > 0){
	   
			echo"<table class=\"table table-hover display\">
				<tbody>";
				
			 while($notify = mysql_fetch_object($Result)) {
			 
				$notif_id = $notify->id;
				$sid = $notify->service_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
				
				echo"<tr>
                        <td style=\"color:#000\">
							<a href=\"service_workorder.php?sid=$sid&nid=$notif_id\" class=\"";
						if($seenStatus=="Not Seen") {echo"info"; }
						echo"\">$notifDesc</a><br />
							<span style=\"color:#ccc;\">$date</span>
						</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Service Notifications!</div>';   
	   }
	}			
	
	function getDieselReordernotification() {	
		$this->connect_db();				
		$Query = "select * from dieselevel_notification where to_user = '".$_SESSION['userid']."' order by time_created desc";
		$Result = mysql_query($Query)or die(mysql_error());
		$num_rows = mysql_num_rows($Result);
		   
	   if($num_rows > 0){
	   
			echo"<table class=\"table table-hover display\">
				<tbody>";
				
			 while($notify = mysql_fetch_object($Result)) {
			 
				$notif_id = $notify->id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notification;
				$seenStatus = $notify->seen;
				$workOrder = $notify->work_order;
				$date = date("D M d, Y - g:ia", $notify->time_created);
				
				
				echo"<tr>
                        <td style=\"color:#000\">
							<a href=\"view_supply.php?siteID=$siteID\" class=\"";
						if($seenStatus=="Not Seen") {echo"info"; }
						echo"\">$notifDesc</a><br />
							<span class=\"label ";
								switch($workOrder) {
										case "Not Done":
										echo"label-danger";
										break;
										case "Done":
										echo"label-success";
										break;
									}
								echo"\">$workOrder</span>";
							$this->getOverallDieselReading($siteID);
							echo"<br /><span style=\"color:#ccc;\">$date</span>
						</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Work Orders!</div>';   
	   }
	}		
	
	function getAllNotifications() {	
		$this->connect_db();		
		$sql = "SELECT * FROM notifications where to_user = '".$_SESSION['userid']."' ORDER BY time_created desc";	
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
	   
			echo"<table class=\"table table-hover display\">
				<tbody>";
				
			 while($notify = mysql_fetch_object($result)) {
			 
				$notif_id = $notify->notif_id;
				$notifType = $notify->notif_type;
				$typeID = $notify->ntype_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notif_desc;
				$seenStatus = $notify->seen;
				$date = date("M d, Y, g:ia", $notify->time_created);
				
				
				echo"<tr class=\"";
						if($seenStatus=="no") {echo"info"; }
						echo"\">
                        <td style=\"color:#000\">
							<a href=\"notifications.php?notif_id=$notif_id&tid=$typeID&notif_t=$notifType&sid=$siteID\">$notifDesc</a><br /><span style=\"color:#ccc;\">$date</span>
						</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Notifications!</div>';   
	   }
	}	
	
	function dashNotifications() {	
		$this->connect_db();		
		$sql = "SELECT * FROM notifications ORDER BY time_created desc";	
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
	   
			echo"<table class=\"table table-hover display\">
				<tbody>";
				
			 while($notify = mysql_fetch_object($result)) {
			 
				$notif_id = $notify->notif_id;
				$notifType = $notify->notif_type;
				$typeID = $notify->ntype_id;
				$siteID = $notify->site_id;
				$notifDesc = $notify->notif_desc;
				$seenStatus = $notify->seen;
				$date = date("M d, Y, g:ia", $notify->time_created);
				
				
				echo"<tr class=\"";
						if($seenStatus=="no") {echo"info"; }
						echo"\">
                        <td style=\"color:#000\">
							<a href=\"notifications.php?notif_id=$notif_id&tid=$typeID&notif_t=$notifType&sid=$siteID\">$notifDesc</a><br /><span style=\"color:#ccc;\">$date</span>
						</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">All work Orders Cleared!</div>';   
	   }
	}
	
	function getdieselReading($siteid,$tank) {
		//get disel level for this site gen 
		$Sitedisel = "select s.id,s.site_id,s.cpd,sd.initial_stock,sd.supplied_qty,sd.new_stock,s.status,sd.tank,
				 DATEDIFF(s.next_supply_date,s.supply_date) as total_days,
				 DATEDIFF(s.next_supply_date,CURDATE()) as remaining_days,
				 DATEDIFF(CURDATE(),s.supply_date) as daysPast
				 from  supplies s join supplies_details sd on s.id = sd.supply_id where s.site_id = '$siteid' and sd.tank='$tank' and s.status='0'";
		$SitediselResult = mysql_query($Sitedisel)or die(mysql_error());
		$countRowGen1 = mysql_num_rows($SitediselResult);
		if($countRowGen1 >0) {
			$SitediselData = mysql_fetch_object($SitediselResult)or die(mysql_error());

			$new_stock 			= $SitediselData->new_stock;
			$cpd			 	=  $SitediselData->cpd;
			$Gen1totalDays	 	=  $SitediselData->total_days;
			$Gen1daysPast	 	=  $SitediselData->daysPast;
			$Gen1RemainingDays 	=  $SitediselData->remaining_days;
						
			$cpdPerGen = $cpd/2;			
			$estConsumption = $Gen1daysPast * $cpdPerGen;

			//calculate percent of disel remaining
			$Gen1percentage = (100*$estConsumption)/$new_stock;
			$remainingPercent = 100-$Gen1percentage;
			$Gen1percentRound = round($remainingPercent, 2);
		}else {
			$Gen1percentRound = 0;
		}
		
		echo"<div class=\"progress progress-striped active\">
		<div class=\"progress-bar ";
		if($Gen1percentRound<39){echo"progress-bar-danger";}elseif($Gen1percentRound>=39 && $Gen1percentRound<=60){echo "progress-bar-warning";}else{echo "progress-bar-success";}
		echo"\" role=\"progressbar\" aria-valuenow=\"100\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: ";
		if($Gen1percentRound<=0){echo"5";}else{ echo $Gen1percentRound;}
		echo"%\"><span>";
		echo $Gen1percentRound."%,";
		if($Gen1percentRound<=0){echo"0";}else{ echo $Gen1RemainingDays;}
		echo"Days</span>
			</div>
		</div>";
	}
	
	function getOverallDieselReading($siteid) {
		//get disel level for this site gen 
		$Sitedisel = "select s.id,s.site_id,s.status,s.cpd,sum(sd.new_stock) as total_stock,
				 DATEDIFF(s.next_supply_date,s.supply_date) as total_days,
				 DATEDIFF(s.next_supply_date,CURDATE()) as remaining_days,
				 DATEDIFF(CURDATE(),s.supply_date) as daysPast
				 from  supplies s join supplies_details sd on s.id = sd.supply_id where s.site_id = '$siteid' and s.status='0'";
		$SitediselResult = mysql_query($Sitedisel)or die(mysql_error());
		$countRowGen1 = mysql_num_rows($SitediselResult);
		if($countRowGen1>0) {
			$SitediselData = mysql_fetch_object($SitediselResult)or die(mysql_error());

			$supplyID			= $SitediselData->id;
			$total_stock		= $SitediselData->total_stock;
			$cpd			 	=  $SitediselData->cpd;
			$Gen1totalDays 		= $SitediselData->total_days;
			$Gen1daysPast	 	=  $SitediselData->daysPast;
			$Gen1RemainingDays 	=  $SitediselData->remaining_days;
			
			if($supplyID==""){
				$Gen1percentRound = 0;
			}else{
				$estConsumption = $Gen1daysPast * $cpd;

				//calculate percent of disel remaining
				$Gen1percentage = (100*$estConsumption)/$total_stock;
				$remainingPercent = 100-$Gen1percentage;
				$Gen1percentRound = round($remainingPercent, 2);
			}
			
		}else {
			$Gen1percentRound = 0;
		}
		
		$dieselLeft = ($Gen1percentRound/100) * $total_stock;
		
		echo"<div class=\"progress progress-striped active\" style=\"margin-bottom:0px;\">
		<div class=\"progress-bar ";
		if($Gen1percentRound<=39){echo"progress-bar-danger";}elseif($Gen1percentRound>=40 && $Gen1percentRound<=60){echo "progress-bar-warning";}else{echo "progress-bar-success";}
		echo"\" role=\"progressbar\" aria-valuenow=\"100\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: ";
		if($Gen1percentRound<=0){echo"5";}else{ echo $Gen1percentRound;}
		echo"%\"><span>";
		echo $Gen1percentRound."%</span>
			</div>
		</div>".round($dieselLeft, 2) ."ltr.";
	}
	
	function getSiteDieselReading_notfy($siteid) {
		//get disel level for this site gen 
		$Sitedisel = "select s.id,s.site_id,s.status,s.cpd,sum(sd.new_stock) as total_stock,
				 DATEDIFF(s.next_supply_date,s.supply_date) as total_days,
				 DATEDIFF(s.next_supply_date,CURDATE()) as remaining_days,
				 DATEDIFF(CURDATE(),s.supply_date) as daysPast
				 from  supplies s join supplies_details sd on s.id = sd.supply_id where s.site_id = '$siteid' and s.status='0'";
		$SitediselResult = mysql_query($Sitedisel)or die(mysql_error());
		$countRowGen1 = mysql_num_rows($SitediselResult);
		if($countRowGen1>0) {
			$SitediselData = mysql_fetch_object($SitediselResult)or die(mysql_error());

			$supplyID			= $SitediselData->id;
			$total_stock		= $SitediselData->total_stock;
			$cpd			 	=  $SitediselData->cpd;
			$Gen1totalDays 		= $SitediselData->total_days;
			$Gen1daysPast	 	=  $SitediselData->daysPast;
			$Gen1RemainingDays 	=  $SitediselData->remaining_days;
			
			if($supplyID==""){
				$Gen1percentRound = 0;
			}else{
				$estConsumption = $Gen1daysPast * $cpd;

				//calculate percent of disel remaining
				$Gen1percentage = (100*$estConsumption)/$total_stock;
				$remainingPercent = 100-$Gen1percentage;
				$Gen1percentRound = round($remainingPercent, 2);
			}
			
		}else {
			$Gen1percentRound = 0;
		}
		
		echo"<div class=\"progress progress-striped active\" style=\"margin-bottom:0px;height: 7px;\">
		<div class=\"progress-bar ";
		if($Gen1percentRound<39){echo"progress-bar-danger";}elseif($Gen1percentRound>=39 && $Gen1percentRound<=60){echo "progress-bar-warning";}else{echo "progress-bar-success";}
		echo"\" role=\"progressbar\" aria-valuenow=\"100\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: ";
		if($Gen1percentRound<=0){echo"5";}else{ echo $Gen1percentRound;}
		echo"%\"><span>
			</span>
			</div>
		</div>";
	}
	
	function getSiteDieselPercent($siteid) {
		//get disel level for this site gen 
		$Sitedisel = "select s.id,s.site_id,s.status,s.cpd,sum(sd.new_stock) as total_stock,
				 DATEDIFF(s.next_supply_date,s.supply_date) as total_days,
				 DATEDIFF(s.next_supply_date,CURDATE()) as remaining_days,
				 DATEDIFF(CURDATE(),s.supply_date) as daysPast
				 from  supplies s join supplies_details sd on s.id = sd.supply_id where s.site_id = '$siteid' and s.status='0'";
		$SitediselResult = mysql_query($Sitedisel)or die(mysql_error());
		$countRowGen1 = mysql_num_rows($SitediselResult);
		if($countRowGen1>0) {
			$SitediselData = mysql_fetch_object($SitediselResult)or die(mysql_error());

			$supplyID			= $SitediselData->id;
			$total_stock		= $SitediselData->total_stock;
			$cpd			 	=  $SitediselData->cpd;
			$Gen1totalDays 		= $SitediselData->total_days;
			$Gen1daysPast	 	=  $SitediselData->daysPast;
			$Gen1RemainingDays 	=  $SitediselData->remaining_days;
			
			$estConsumption = $Gen1daysPast * $cpd;

				//calculate percent of disel remaining
				$Gen1percentage = (100*$estConsumption)/$total_stock;
				$remainingPercent = 100-$Gen1percentage;
				$Gen1percentRound = round($remainingPercent, 2);
				return $Gen1percentRound;
		}else {
			$Gen1percentRound = 0;
			return $Gen1percentRound;
		}
		
	}
	
	function CurrentSupplyDate($siteid) {
		
		$query = "select site_id,supply_date from  supplies where site_id = '$siteid' and status='0'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow >0) {
			$data = mysql_fetch_object($result)or die(mysql_error());
			$SupplyDate = $data->supply_date;
			echo $SupplyDate;
		}else {
			echo"-";
		}
	}
	
	function NextSupplyDate($siteid) {
		
		$query = "select site_id,next_supply_date from  supplies where site_id = '$siteid' and status='0'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow >0) {
			$data = mysql_fetch_object($result)or die(mysql_error());
			$nextSupplyDate = $data->next_supply_date;
			echo $nextSupplyDate;
		}else {
			echo"-";
		}
	}
	
	function checkTicketIndicator($siteid) {
		
		$query = "select * from  ticket_notification where site_id = '$siteid' and to_user='".$_SESSION['userid']."' and seen='no'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow >0) {
			return $countRow;
		}else {
			return 0;
		}
	}
	
	function checkSupplyIndicator($siteid) {
		
		$query = "select * from supply_notification where site_id = '$siteid' and to_user='".$_SESSION['userid']."' and seen='no'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow >0) {
			return $countRow;
		}else {
			return 0;
		}
	}
	
	function checkServiceIndicator($siteid) {
	
		$query = "select * from  service_notification where site_id = '$siteid' and to_user='".$_SESSION['userid']."' and seen='no'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow >0) {
			return $countRow;
		}else {
			return 0;
		}
	}
	
	function checkWeekReportIndicator($siteid) {
		
		$query = "select * from notifications where site_id = '$siteid' and to_user='".$_SESSION['userid']."' and notif_type='week_report' and seen='no'";
		$result = mysql_query($query)or die(mysql_error());
		$countRow = mysql_num_rows($result);
		if($countRow >0) {
			return 1;
		}else {
			return 0;
		}
	}	
	
	function activeSites() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM site where status = 'Live' ORDER BY site_id asc";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
		if($num_rows > 0){
			echo"<table class=\"table table-bordered table-hover display\">
               <thead>
                    <tr>
                    <th>sn</th>
                    <th>Site ID</th>
                    <th>Site No</th>
                    <th>Tenant Count</th>
                    <th>Supply Date</th>
                    <th>Current Est. Level</th>
                    <th>Next Supply</th>
                    <th>Tickets</th>
                    <th>Diesel Report</th>
                    <th>Service Report</th>
                    <th>Weekly Report</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$state 			= $site->state;
				$site_no 		= $site->site_no;
				
				//tenants
				$tenantCount = $this->countSiteTenants($id);
				
				//check for new ticket
				$checkTicket = $this->checkTicketIndicator($id);
				
				//check for new supply
				$checkSupply = $this->checkSupplyIndicator($id);
				
				//check for new service
				$checkService = $this->checkServiceIndicator($id);
				
				//check for new weekly report
				$checkWeek= $this->checkWeekReportIndicator($id);
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$site_no</td>
                        <td>$tenantCount Tenant(s)</td>
                        <td>";
							$this->CurrentSupplyDate($id);
						echo"</td>
                        <td>";
						$this->getOverallDieselReading($id);
						echo"</td>
                        <td>";
						$this->NextSupplyDate($id);
						echo"</td>
                        <td>";
						if($checkTicket !=0) {
							echo"<span class=\"indicator\"><a href=\"site_tickets.php?sid=$id\" class=\"blink\" style=\"color:#c60000\"><img src=\"assets/images/new-ticket.png\"> New Ticket <span class=\"badge bg-danger\">$checkTicket</span></a></span></td>";
						}else {
							echo"<img src=\"assets/images/ok.png\"> No New Ticket.";
						}
                        echo"<td>";
						if($checkSupply !=0) {
							echo"<span class=\"indicator\"><a href=\"view_supply.php?siteID=$id\" class=\"blink\" style=\"color:#c60000\"><img src=\"assets/images/new-ticket.png\"> New Report <span class=\"badge bg-danger\">$checkSupply</span></a></span></td>";
						}else {
							echo"<img src=\"assets/images/ok.png\"> No New Report.";
						}
						echo"</td>
                        <td>";
						if($checkService != 0) {
							echo"<span class=\"indicator\"><a href=\"view_service.php?siteID=$id\" class=\"blink\" style=\"color:#c60000\"><img src=\"assets/images/new-ticket.png\"> New Report <span class=\"badge bg-danger\">$checkService</span></a></span></td>";
						}else {
							echo"<img src=\"assets/images/ok.png\"> No New Report.";
						}
						echo"</td>
                        <td>";
						if($checkWeek == 1) {
							echo"<span class=\"indicator\"><a href=\"view_week.php?siteID=$id\" class=\"blink\" style=\"color:#c60000\"><img src=\"assets/images/week.png\"> New Report</a></span></td>";
						}else {
							echo"<img src=\"assets/images/ok.png\"> No New Report.";
						}
						echo"</td>
                     </tr>";
			 }
			 
			// print the navigation link
			echo"</tbody>
			</table>";
	   }else{
			echo'<div class="alert alert-danger">No Site Yet</div>';   
	   }
	}
	
	//delete site
	function deleteWeeklyReport($wid) {
		$this->connect_db(); 
		
		//delete supply stats for site
		$del1 = "delete from weekly_diesel_level where week_id = '$wid'";
		$del1_result = mysql_query($del1)or die(mysql_error());
		
		//delete supply for site
		$del2 = "delete from weekly_running_hours where week_id = '$wid'";
		$del2_result = mysql_query($del2)or die(mysql_error());
		
		//delete gens for site
		$del3 = "delete from weekly_report where id = '$wid'";
		$del3_result = mysql_query($del3)or die(mysql_error());
		
		//delete from running hours
		$del4 = "delete from site_running_hours where reported_from = 'week_report' and report_id = '$wid'";
		$del4_result = mysql_query($del4)or die(mysql_error());
		
		
		if($del1_result && $del2_result && $del3_result && $del4_result) {
			return 1;
		}else {
			return 0;
		}
	} 

	function clearNotifications($page,$notifType) {
		$this->connect_db();
		
			if($notifType=="supply") {
				$updateNotify = mysql_query("update supply_notification set seen = 'yes' where to_user='".$_SESSION['userid']."'")or die(mysql_error());
			}elseif($notifType=="service") {
				$updateNotify = mysql_query("update service_notification set seen = 'yes' where to_user='".$_SESSION['userid']."'")or die(mysql_error());
			}elseif($notifType=="ticket") {
				$updateNotify = mysql_query("update ticket_notification set seen = 'yes' where to_user='".$_SESSION['userid']."'")or die(mysql_error());
			}
			
		if ($_SERVER['HTTPS']){
			$domainName = 'https://' . $_SERVER['SERVER_NAME'];
		}else{
			$domainName = 'http://' . $_SERVER['SERVER_NAME'];
		}
		header("location:$domainName$page");
	}
	
	function edit_stock_supplied_Input($reportID) {
		$this->connect_db();		
		
		$sql = "SELECT * FROM supplies_details where supply_id = '$reportID'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		//get number of tanks on site
		$siteData = $this->getSiteInfo($siteid);
		$siteTanks = $siteData->tank_mode;
			
		while($supply = mysql_fetch_object($result)) {
			$sn += 1;
			$id 		= $supply->id;
			$sid 		= $supply->supply_id;
			$tank 		= $supply->tank;
			$initstock 	= $supply->initial_stock;
			$supplied 	= $supply->supplied_qty;
			$newstock 	= $supply->new_stock;
				
			echo"<div class=\"form-group col-sm-6\">
				<label class=\"control-label\">Stock ($tank)</label>
				<div class=\"input-group\">
					<span class=\"input-group-addon bg\">
						<i class=\"fa fa-asterisk\"></i>
					</span>
					  <input type=\"text\" class=\"form-control\" placeholder=\"Initial Stock\" value=\"$initstock\" name=\"init_stock[]\" required />
				</div>
			</div>
			
			<div class=\"form-group col-sm-6\">
				<label class=\"control-label\">Supplied ($tank)</label>
				<div class=\"input-group\">
					<span class=\"input-group-addon bg\">
						<i class=\"fa fa-asterisk\"></i>
					</span>
					<input type=\"text\" class=\"form-control\" placeholder=\"Quantity Supplied\" value=\"$supplied\" name=\"supplied_qty[]\" required />
				</div>
			</div>";
		}
	}
	
	function EditRunningHoursInput($siteid) {
		$this->connect_db();
		$query = mysql_query("select * from power_source where site_id = '$siteid' and source_type='Gen'");
		while($powerSource = mysql_fetch_object($query)) {
			$powerID = $powerSource->power_id;
			$sourceName = $powerSource->source_name;
			
			$sql = mysql_query("select * from site_running_hours where power_id = '$powerID'");
			$hoursData = mysql_fetch_object($sql);
			$runningHours = $hoursData->running_hrs;
			
			
			echo"<!-- xinput group-->
					<div class=\"form-group col-sm-6\">
						<label class=\"control-label\">Running Hours for $sourceName</label>
						<div class=\"input-group\">
							<span class=\"input-group-addon bg\">
								<i class=\"fa fa-asterisk\"></i>
							</span>
							<input type=\"text\" class=\"form-control\" placeholder=\"00.00\" name=\"runnhrs[]\" value=\"$runningHours\" required />
							<input type=\"hidden\" value=\"$powerID\" name=\"sourceid[]\"  />
						</div>
					</div>
				  <!-- /input-group -->";
		}
	}	
	
	function addDownTime($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {		
			$time = time();

			$site   		= $this->mysql_prepare_value(trim($post['site']));
			$timedown		= $this->mysql_prepare_value(trim($post['timedown']));
			$timeIn			= $this->mysql_prepare_value(trim($post['time_received']));
			$timeOut		= $this->mysql_prepare_value(trim($post['timedespatched']));
			$tenant			= $this->mysql_prepare_value(trim($post['tenant']));

			//arrange date befor inserrting

			$query = "insert into downtime values('','$site','$timedown','$timeIn','$timeOut','$tenant','','','','','".$_SESSION['userid']."','','$time','','Open')";
			$result = mysql_query($query)or die(mysql_error());
			$downtime_id = mysql_insert_id();
			
			//insert escalation tenant.
			$query2 = "insert into downtime_tenant values('','$downtime_id','$tenant','$timedown','$timeIn','".$_SESSION['userid']."','$time')";
			$result2 = mysql_query($query2)or die(mysql_error());
			
			if($result && $result2) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Down Time saved</div>';
			}
		}
	}		
	
	function addEscTenant($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {		
			$time = time();

			$downtime_id  	= $this->mysql_prepare_value(trim($post['eid']));
			$tenant			= $this->mysql_prepare_value(trim($post['tenant']));
			$timedown		= $this->mysql_prepare_value(trim($post['timedown']));
			$timeout		= $this->mysql_prepare_value(trim($post['timeout']));
			
			//insert escalation tenant.
			$query = "insert into downtime_tenant values('','$downtime_id','$tenant','$timedown','$timeout','".$_SESSION['userid']."','$time')";
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Tenant Added</div>';
			}
		}
	}		
	
	function RespondDownTime($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {		
			$time = time();
			
			$id				= $this->mysql_prepare_value($post['eid']);			
			$status			= $this->mysql_prepare_value(trim($post['status']));			
			$timeup			= $this->mysql_prepare_value(trim($post['timeup']));	
			$reason			= $this->mysql_prepare_value(trim($post['reason']));	
			$reason_cause		= $this->mysql_prepare_value(trim($post['cause_status']));	

			//arrange date befor inserrting

			$query = "update downtime set escalation_valid = '$status',downtime_cause = '$reason',time_up = '$timeup',
			 closed_by = '".$_SESSION['userid']."',time_closed = '$time', escalation_status = 'Closed', esc_cause_status = '$reason_cause'
			where id = '$id'";
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Escalation Closed Successfully</div>';
			}
		}
	}	
	
	function updateDownTime($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {		

			$eid	   		= $this->mysql_prepare_value(trim($post['eid']));
			$site   		= $this->mysql_prepare_value(trim($post['site']));
			$timedown		= $this->mysql_prepare_value(trim($post['timedown']));
			$receivetime	= $this->mysql_prepare_value(trim($post['time_received']));
			$despatchtime	= $this->mysql_prepare_value(trim($post['timedespatched']));
			$tenant			= $this->mysql_prepare_value(trim($post['tenant']));

			//arrange date befor inserrting

			$query = "update downtime set site_id ='$site',
			time_down = '$timedown',
			esc_receive_time ='$receivetime',
			esc_despatch_time = '$despatchtime',
			tenant_id = '$tenant'
			where id = '$eid'";
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Down Time Saved</div>';
			}
		}
	}	
	
	function SendTransferRequest($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {
		
			$time = time();

			$ref	   	= $this->mysql_prepare_value(trim($post['tranref']));
			$item		= $this->mysql_prepare_value(trim($post['item']));
			$item_desc	= $this->mysql_prepare_value(trim($post['item_desc']));
			$from_site	= $this->mysql_prepare_value(trim($post['from_site']));
			$to_site	= $this->mysql_prepare_value(trim($post['to_site']));
			$comment	= $this->mysql_prepare_value(trim($post['comment']));

			//arrange date befor inserrting

			$query = "insert into transfer_request values('','$ref','".$_SESSION['userid']."','$item','$item_desc','$from_site','$to_site','$comment','$time','Pending','','','Not Done','','$time')";
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {
				
				//send email notification for this request
				
				//get sender
				$userData = $this->getUserInfo($_SESSION['userid']);
				$request_by = $userData->name;
				
				//get sites involved
				$siteData1 = $this->getSiteInfo($from_site);
				$fromSite = $siteData1->site_id;
				
				$siteData2 = $this->getSiteInfo($to_site);
				$toSite = $siteData2->site_id; 
				
				$globalConfigData = $this->getConfigInfo();
				$to = $globalConfigData->trans_req_email;

				$headers = "From: " . strip_tags("Bctek App") . "\r\n";
				$headers .= "MIME-Version: 1.0\r\n";
				$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
				
				$message = '<html>
				<body bgcolor="#f7f7f7">';
				$message .= '<table width="700px" border="0" align="center" cellpadding="20" style="border:solid 1px #CCC;">';
				$message .= '<tr><td valign="top"><span style="color:#000; font-size:25px">Transfer Request from '.$request_by.'</span></td></tr>';
				$message .= '<tr><td valign="top">Transfer Item: <h3>'.$item.'</h3></td></tr>';
				$message .= '<tr><td valign="top">Item Description: <h3>'.$item.'</h3></td></tr>';
				$message .= "<tr><td valign=\"top\">From Site: <h3>".$fromSite."</h3></td></tr>";
				$message .= "<tr><td valign=\"top\">To Site: <h3>".$toSite."</h3></td></tr>";
				$message .= "<tr><td valign=\"top\">Reason: <h3>".$comment."</h3></td></tr>";
				$message .= "<tr><td valign=\"top\">Request Time: <h3>".date("d M, Y; H:m",$time)."</h3></td></tr>";
				$message .= "</table>";
				$message .= "</body></html>";
				 
				$sendmail = mail($to, "[bcteksmtool.com] Transfer Request from ".$request_by, $message, $headers);
				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Request Sent
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">�</button></div>';
			}
		}
	}
	
	function RespondToRequest($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {		

			$id	   			= $this->mysql_prepare_value(trim($post['trqid']));
			$reponse   		= $this->mysql_prepare_value(trim($post['reponse']));
			$no_reason 		= $this->mysql_prepare_value(trim($post['no_reason']));
			
			$time = time();

			//arrange date befor inserrting

			$query = "update transfer_request set request_reponse ='$reponse', response_date = '$time', disapprove_reason = '$no_reason'
			where id = '$id'";
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {
			
				$requestData = $this->getTransferRequestInfo($id);
				$requested_by = $requestData->requested_by;
				$transfer_item = $requestData->transfer_item;
				$from_site = $requestData->from_site;
				$to_site = $requestData->to_site;
				
				//get sender
				$userData = $this->getUserInfo($requested_by);
				$to = $userData->email;
				
				//get site ID
				$siteData1 = $this->getSiteInfo($from_site);
				$fromSite = $siteData1->site_id;

				$siteData2 = $this->getSiteInfo($to_site);
				$toSite = $siteData2->site_id;
				
				$headers = "From: " . strip_tags("Bctek App") . "\r\n";
				$headers .= "MIME-Version: 1.0\r\n";
				$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
				
				$message = '<html>
				<body bgcolor="#f7f7f7">';
				$message .= '<table width="700px" border="0" align="center" cellpadding="20" style="border:solid 1px #CCC;">';
				$message .= '<tr><td valign="top">Transfer Item: <h3>'.$transfer_item.'</h3></td></tr>';
				$message .= "<tr><td valign=\"top\">From Site: <h3>".$fromSite."</h3></td></tr>";
				$message .= "<tr><td valign=\"top\">To Site: <h3>".$toSite."</h3></td></tr>";
				$message .= "<tr><td valign=\"top\">Response: <h3>".$reponse."</h3></td></tr>";
				if($reponse=="Not Approved") {
					$message .= "<tr><td valign=\"top\">Reason: <h3>".$no_reason."</h3></td></tr>";
				}
				$message .= "<tr><td valign=\"top\">Time of Response: <h3>".date("d M, Y; H:m",$time)."</h3></td></tr>";
				$message .= "</table>";
				$message .= "</body></html>";
				 
				$sendmail = mail($to, "[Reply] Transfer Request from", $message, $headers);
				
				
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Transfer Request Response sent </div>';
			}
		}
	}	
	
	
	function TransferStatus($post, $process) {
		$this->connect_db(); 
		
		if(isset($process)) {		

			$id	   			= $this->mysql_prepare_value(trim($post['trqid']));
			$status   		= $this->mysql_prepare_value(trim($post['status']));
			$dtime	 		= $this->mysql_prepare_value(trim($post['dtime']));
			
			$time = time();

			if($status=="done") {
				$query = "update transfer_request set request_status ='Done', status_date = '$dtime' where id = '$id'";
			}else{
				$query = "update transfer_request set request_status ='Not Done', status_date = ' ' where id = '$id'";
			}
			$result = mysql_query($query)or die(mysql_error());
			
			if($result) {
				return '<div class="alert alert-success"><i class="fa fa-check"></i> Transfer Status Changed </div>';
			}
		}
	}	
	
	function getDownTime() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM downtime where escalation_status = 'Open' ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-striped\"  id=\"example\">
               <thead>
                    <tr>
                    <th>SN</th>
                    <th>Site ID</th>
                    <th>First Tenant</th>
                    <th>Down Time</th>
                    <th class=\"hidden-phone\">Time In</th>
                    <th>Time Out</th>
                    <th>Validity</th>
                    <th>Time Up</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($downtime = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 			= $downtime->id;
				$siteID 		= $downtime->site_id;
				$tenantID 		= $downtime->tenant_id;
				$timeDown	 	= $downtime->time_down;
				$timeIn		 	= $downtime->esc_receive_time;
				$timeOut		= $downtime->esc_despatch_time;
				$esc_valid		= $downtime->escalation_valid;
				$time_up		= $downtime->time_up;
				$comment		= $downtime->comment;
				$esc_status		= $downtime->escalation_status;
				
				//get site ID
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				//get Tenant
				$tenantData = $this->getCustomerInfo($tenantID);
				$tenant = $tenantData->short_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"site_downLog.php?sid=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\">$site_id</a></td>
                        <td>$tenant</td>
                        <td>$timeDown</td>
                        <td>$timeIn </td>
                        <td>$timeOut </td>
                        <td>$esc_valid</td>
                        <td>$time_up</td>
                        <td><span class=\"label label-";
						if($esc_status=="Closed"){echo"success";}else{echo"danger";}
						echo"\">$esc_status</span></td>
						<td>";
						if($_SESSION['level']=="Supervisor") {
							echo"<a href=\"esc_details.php?eid=$id\"><i class=\"fa fa-folder\"></i></a>";
						}else{
							echo"<a href=\"edit_esc.php?eid=$id\" data-toggle=\"modal\" data-target=\"#siteModal\"><i class=\"fa fa-edit \"></i></a> | 							
								<a href=\"esc_details.php?eid=$id\"><i class=\"fa fa-folder\"></i></a> |
								<a href=\"".$_SERVER['PHP_SELF']."?eid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash\"></i></a>";
						}
						echo"</td>
                     </tr>";
			 }
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Down Time Logged</div>';   
	   }
	}
	
	function searchDownTime($site,$start,$end,$tenant) {	
		$this->connect_db();
		
		$sql = "SELECT d.id,d.site_id,d.time_down,d.esc_receive_time,d.esc_despatch_time,d.tenant_id,
		        d.escalation_valid,d.downtime_cause,d.esc_cause_status,d.time_up,d.escalation_status,d.time_created FROM downtime d";
		if($tenant!="all") {
			$sql .= " join downtime_tenant dt on dt.downtime_id = d.id";
		}
		$sql .= " where d.time_down between '$start' and '$end'";		
		if($site!="all") {
			$sql .= " and d.site_id = '$site'";
		}if($tenant!="all") {
			$sql .= " and d.tenant_id = '$tenant'";
		}
		$sql .= " ORDER BY d.time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		//generate excel
		$getExcel = $this->DowntimeLogSearch2Excel($sql);
		   
	   if($num_rows > 0){
			echo"<div class=\"alert alert-info\">Down Time Between $start and $end";
			if($tenant!="all") {
				//get Tenant
				$tenantDataX = $this->getCustomerInfo($tenant);
				$tenantX = $tenantDataX->short_name;
				echo" for $tenantX";
			}
			if($site!="all") {
				//get site ID
				$siteDataX = $this->getSiteInfo($site);
				$sid = $siteDataX->site_id;
				echo" on site $sid";
			}			
			echo"<a href=\"exports/$getExcel\" class=\"btn btn-xs btn-warning pull-right\">Export to Excel</a>
			<a href=\"downtime_log.php\" class=\"btn btn-xs btn-success pull-right\">Back to Log</a></div>			
			<table class=\"table table-bordered table-striped\"  id=\"example\">
               <thead>
                    <tr>
                    <th>SN</th>
                    <th>Site ID</th>
                    <th>First Tenant</th>
                    <th>Down Time</th>
                    <th class=\"hidden-phone\">Time In</th>
                    <th>Time Out</th>
                    <th>Validity</th>
                    <th>Time Up</th>
                    <th>Status</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($downtime = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 			= $downtime->id;
				$siteID 		= $downtime->site_id;
				$tenantID 		= $downtime->tenant_id;
				$timeDown	 	= $downtime->time_down;
				$timeIn		 	= $downtime->esc_receive_time;
				$timeOut		= $downtime->esc_despatch_time;
				$esc_valid		= $downtime->escalation_valid;
				$time_up		= $downtime->time_up;
				$comment		= $downtime->comment;
				$esc_status		= $downtime->escalation_status;
				
				//get site ID
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				//get Tenant
				$tenantData = $this->getCustomerInfo($tenantID);
				$tenant = $tenantData->short_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"site_downLog.php?sid=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\">$site_id</a></td>
                        <td>$tenant</td>
                        <td>$timeDown</td>
                        <td>$timeIn </td>
                        <td>$timeOut </td>
                        <td>$esc_valid</td>
                        <td>$time_up</td>
                        <td><span class=\"label label-";
						if($esc_status=="Closed"){echo"success";}else{echo"danger";}
						echo"\">$esc_status</span></td>
						<td>";
						if($_SESSION['level']=="Supervisor") {
							echo"<a href=\"esc_details.php?eid=$id\"><i class=\"fa fa-folder\"></i></a>";
						}else{
							echo"<a href=\"edit_esc.php?eid=$id\" data-toggle=\"modal\" data-target=\"#siteModal\"><i class=\"fa fa-edit \"></i></a> | 							
								<a href=\"esc_details.php?eid=$id\"><i class=\"fa fa-folder\"></i></a> |
								<a href=\"".$_SERVER['PHP_SELF']."?eid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash\"></i></a>";
						}
						echo"</td>
                     </tr>";
			 }
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Down Time Between this period <a href=\"downtime_log.php\" class=\"btn btn-xs btn-success pull-right\">Back to Log</a></div>';   
	   }
	}
	
	function getDownTimeTenants($downTime_id) {	
		$this->connect_db();
		
		//get Downtime info
		$downTimeData = $this->getDownTimeInfo($downTime_id);
		$status = $downTimeData->escalation_status;
		
		$sql = "SELECT * FROM downtime_tenant where downtime_id = '$downTime_id' ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-striped\">
               <thead>
                    <tr>
                    <th>Tenant</th>
                    <th>Downtime</th>
                    <th>Time In</th>";
					if(($_SESSION['level']=="NOC Admin" || $_SESSION['level']=="NOC Team") && $status=="Open") {
						echo"<th>Action</th>";
					}
                    echo"</tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($downtimet = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 			= $downtimet->id;
				$tenantID 		= $downtimet->tenant_id;
				$timeDown	 	= $downtimet->time_down;
				$timeIn		 	= $downtimet->esc_receive_time;
				
				//get Tenant
				$tenantData = $this->getCustomerInfo($tenantID);
				$tenant = $tenantData->short_name;
				
				echo"<tr>
                        <td>$tenant</td>
                        <td>$timeDown</td>
                        <td>$timeIn</td>";
							if(($_SESSION['level']=="NOC Admin" || $_SESSION['level']=="NOC Team") && $status=="Open") {
								echo"<td><a href=\"".$_SERVER['PHP_SELF']."?eid=$downTime_id&tid=$id&del_t=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\">remove</a></td>";
							}
						echo"</tr>";
			}
			echo "</tbody>
				 </table>";
		}else{
				echo'<div class="alert alert-danger">No Tenant captured</div>';   
		}
	}
	
	function getEngrDownTimeView() {	
		$this->connect_db();
		
		$sql = "SELECT * FROM downtime ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-striped\"  id=\"example\">
               <thead>
                    <tr>
                    <th>SN</th>
                    <th>Site ID</th>
                    <th>Tenant</th>
                    <th>Notice Time</th>
                    <th>Status</th>
                    <th>Cause</th>
                    <th>Time Up</th>
                    <th>Comments</th>
                    <th>Responded</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($downtime = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 			= $downtime->id;
				$siteID 		= $downtime->site_id;
				$tenantID 		= $downtime->tenant_id;
				$notice		 	= $downtime->esc_receive_time;
				$status 		= $downtime->status;
				$cause			= $downtime->downtime_cause;
				$time_up		= $downtime->time_up;
				$comment		= $downtime->comment;
				$response		= $downtime->response;
				
				//get site ID
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				//get Tenant
				$tenantData = $this->getCustomerInfo($tenantID);
				$tenant = $tenantData->short_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"site_downLog.php?sid=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\">$site_id</a></td>
                        <td>$tenant</td>
                        <td>$notice </td>
                        <td>$status</td>
                        <td>$cause</td>
                        <td>$time_up</td>
                        <td>$comment</td>
                        <td>$response</td>
						<td><a href=\"respond_esc.php?eid=$id\" data-toggle=\"modal\" data-target=\"#siteModal\">Respond</a></td>
                     </tr>";
			 }
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Down Time Logged</div>';   
	   }
	}
	
	function getSiteDownTime($site) {	
		$this->connect_db();
		
		$sql = "SELECT * FROM downtime where site_id = '$site' ORDER BY time_created desc";
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-striped\"  id=\"example\">
               <thead>
                    <tr>
                    <th>SN</th>
                    <th>Site ID</th>
                    <th>Tenant</th>
                    <th>Notice Time</th>
                    <th>Status</th>
                    <th>Cause</th>
                    <th>Time Up</th>
                    <th>Comments</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($downtime = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 			= $downtime->id;
				$siteID 		= $downtime->site_id;
				$tenantID 		= $downtime->tenant_id;
				$notice		 	= $downtime->esc_receive_time;
				$status 		= $downtime->status;
				$cause			= $downtime->downtime_cause;
				$time_up		= $downtime->time_up;
				$comment		= $downtime->comment;
				
				//get site ID
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
				
				//get Tenant
				$tenantData = $this->getCustomerInfo($tenantID);
				$tenant = $tenantData->short_name;
				
				echo"<tr>
                        <td>$sn</td>
                        <td><a href=\"site_downLog.php?sid=$siteID\" data-toggle=\"modal\" data-target=\"#siteModal\">$site_id</a></td>
                        <td>$tenant</td>
                        <td>$notice </td>
                        <td>$status</td>
                        <td>$cause</td>
                        <td>$time_up</td>
                        <td>$comment</td>
						<td>";
						if($_SESSION['level']=="Supervisor") {
							echo"<a href=\"edit_esc.php?eid=$id\" data-toggle=\"modal\" data-target=\"#siteModal\"><i class=\"fa fa-edit\"></i></a> |
							<a href=\"".$_SERVER['PHP_SELF']."?eid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash\"></i></a>";
						}else{
							echo "N/A";
						}
						echo"</td>
                     </tr>";
			 }
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Down Time Logged</div>';   
	   }
	}
	
	function getRequestSent() {	
		$this->connect_db();
		if($_SESSION['level']=='Engineer'){
		$sql = "SELECT * FROM transfer_request where requested_by = '".$_SESSION['userid']."' ORDER BY time_created desc";
		}else{
			$sql = "SELECT * FROM transfer_request ORDER BY time_created desc";
		}
				
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		   
	   if($num_rows > 0){
			echo"<table class=\"table table-bordered table-striped\"  id=\"example\">
               <thead>
                    <tr>
                    <th>SN</th>
                    <th>Trans Ref</th>
                    <th>Item</th>
                    <th>From Site</th>
                    <th>To Site</th>
                    <th>Date Sent</th>
                    <th>Reponse</th>
                    <th>Status</th>
                    <th>Status Date</th>
                    <th>Action</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 $total_amt = 0;
			 while($tranfer = mysql_fetch_object($result)) {
				$sn += 1;
				$rand = rand();
				$id 			= $tranfer->id;
				$ref 			= $tranfer->trans_ref;
				$item 			= $tranfer->transfer_item;
				$from_site 		= $tranfer->from_site;
				$to_site 		= $tranfer->to_site;
				$request_date 	= date('D M,Y - H:m:i',$tranfer->request_date);
				$req_reponse	= $tranfer->request_reponse;
				$req_status		= $tranfer->request_status;
				$status_date	= $tranfer->status_date;
				
				//get site ID
				$siteData1 = $this->getSiteInfo($from_site);
				$fromSite = $siteData1->site_id;
				
				$siteData2 = $this->getSiteInfo($to_site);
				$toSite = $siteData2->site_id;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>BCT/TRQ/$ref</td>
                        <td>$item</td>
                        <td>$fromSite</td>
                        <td>$toSite </td>
                        <td>$request_date</td>
                        <td><span class=\"label label-";
						if($req_reponse=="Pending"){echo"warning";}elseif($req_reponse=="Approved"){echo"success";}elseif($req_reponse=="Not Approved"){echo"danger";}
						echo"\">$req_reponse</span></td>
                        <td><span class=\"label label-";
						if($req_status=="Done"){echo"success";}else{echo"danger";}
						echo"\">$req_status</span></td>
                        <td>$status_date</td>
						<td>";
						if($_SESSION['level']=="Supervisor") {
							echo"<a href=\"viewtransreq.php?trqid=$id\" data-toggle=\"modal\" data-target=\"#siteModal\" title=\"Open Request\"><i class=\"fa fa-folder-o\"></i></a> |
							<a href=\"".$_SERVER['PHP_SELF']."?trqid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash\"></i></a>";
						}else{
							if($req_reponse=="Approved"){
								if($req_status == "Not Done") {
									echo"<a href=\"tranreq_status.php?trqid=$id&sta=done\" data-toggle=\"modal\" data-target=\"#siteModal2\" title=\"Tranfer Done\"><i class=\"fa fa-check \"></i></a> | ";
								}else {
									echo"<a href=\"tranreq_status.php?trqid=$id&sta=ntdone\" data-toggle=\"modal\" data-target=\"#siteModal2\" title=\"Tranfer Done\"><i class=\"fa fa-times\"></i></a> | ";
								}
							}
							echo"<a href=\"edit_tranreq.php?trqid=$id\" data-toggle=\"modal\" data-target=\"#siteModal\"><i class=\"fa fa-edit\"></i></a> |
							<a href=\"".$_SERVER['PHP_SELF']."?trqid=$id&del=$rand\" onclick=\"return confirm('Are you sure you want to delete this?');\"><i class=\"fa fa-trash\"></i></a>";	
														
						}
						echo"</td>
                     </tr>";
			 }
			echo "</tbody>
				 </table>";
	   }else{
			echo'<div class="alert alert-danger">No Transfer request made yet</div>';   
	   }
	}
	
	function generateExcel($query,$table) {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = $creator.$time.'.xlsx';
		
		if($table=="supply") {
		
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Supply Report by ".$creator)
						->setSubject("Supply Report")
						->setDescription("Supply Report")
						->setKeywords("Supply Report")
						->setCategory("Supply Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'Supply Date')
					->setCellValue('B1', 'Site ID')
					->setCellValue('C1', 'BCT ID')
					->setCellValue('D1', 'Address')
					->setCellValue('E1', ' Initial Stock')
					->setCellValue('F1', 'Quantity Supplied')
					->setCellValue('G1', 'Total Stock')
					->setCellValue('H1', 'CPD')
					->setCellValue('I1', 'Next Supply Date')
					->setCellValue('J1', 'Time Submitted')
					->setCellValue('K1', 'Days to next Supply');
					for($col = ord('a'); $col<= ord('k'); $col++){
						$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
					}
					$sn = 2;
			while($supplyData = mysql_fetch_object($result)) {	
				//get supply details
				$supplyDetialsData = $this->getSupplyDetails($supplyData->id,$supplyData->site_id);				
				//get site details
				$Sitedata = $this->getSiteInfo($supplyData->site_id);
				//get the number of days from supply to next supply
				$daysDiff = $this->getSupplyDateDiff($supplyData->id);
				//get number of days passt since supply
				$daysPast = $this->getDaysPastfromSupply($supplyData->id); 
				$timeSubmitted = date("Y-m-d, h:i:s a",$supplyData->time_created);
				
				//get remainder of diesel since last supply
				$totalUsed = $supplyData->cpd * $daysPast;
				$remainder = $supplyDetialsData->qty - $totalUsed;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $supplyData->supply_date)
						->setCellValue('B'.$sn, $Sitedata->site_id)
						->setCellValue('C'.$sn, $Sitedata->bct_id)
						->setCellValue('D'.$sn, $Sitedata->address)
						->setCellValue('E'.$sn, $supplyDetialsData->stock)
						->setCellValue('F'.$sn, $supplyDetialsData->qty)
						->setCellValue('G'.$sn, $supplyDetialsData->total)
						->setCellValue('H'.$sn, $supplyData->cpd)
						->setCellValue('I'.$sn, $supplyData->next_supply_date)
						->setCellValue('J'.$sn, $timeSubmitted)
						->setCellValue('K'.$sn, $daysDiff.' Days');
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="service") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Service Report by ".$creator)
						->setSubject("Service Report")
						->setDescription("Service Report")
						->setKeywords("Service Report")
						->setCategory("Service Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'Site ID')
					->setCellValue('B1', 'Site Engr.')
					->setCellValue('C1', 'Service Date')
					->setCellValue('D1', 'Current Running Hr. Gen 1')
					->setCellValue('E1', 'Current Running Hr. Gen 2')
					->setCellValue('F1', 'Next Running Hr. Gen 1')
					->setCellValue('G1', 'Next Running Hr. Gen 2')
					->setCellValue('H1', 'Cost')
					->setCellValue('I1', 'Service Count')
					->setCellValue('J1', 'Next Service Date')
					->setCellValue('K1', 'Comment')
					->setCellValue('L1', 'Time Submitted');
					for($col = ord('a'); $col<= ord('l'); $col++){
						$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
					}
					$sn = 2;
			while($serviceData = mysql_fetch_object($result)) {	
				
				$Sitedata = $this->getSiteInfo($serviceData->site_id);
				$cost = number_format($serviceData->cost,2);
				$timeSubmitted = date("Y-m-d, h:i:s a",$serviceData->time_created);
				
				
				
				//get site engr name
				$EngrData = $this->getUserInfo($serviceData->engr_id);
				$EngrName = $EngrData->name;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $Sitedata->site_id)
						->setCellValue('B'.$sn, $EngrName)
						->setCellValue('C'.$sn, $serviceData->service_date);
				
				//get supply details
				$serviceQuery = mysql_query("select * from servicing_details where service_id = '".$serviceData->id."' and site_id='".$serviceData->site_id."'")or die(mysql_error());
				
				$colunm1='D';
				$colunm2='F';
				while($serviceDetialsData = mysql_fetch_object($serviceQuery)){
					$objPHPExcel->getActiveSheet()->setCellValue($colunm1.$sn, $serviceDetialsData->curr_running_hrs);
					$objPHPExcel->getActiveSheet()->setCellValue($colunm2.$sn, $serviceDetialsData->next_running_hrs);
					
					$colunm1++;	
					$colunm2++;	
				}	
					
				$objPHPExcel->getActiveSheet()
						->setCellValue('H'.$sn, $cost)
						->setCellValue('I'.$sn, $serviceData->count)
						->setCellValue('J'.$sn, $serviceData->next_service_date)
						->setCellValue('K'.$sn, $serviceData->comment)
						->setCellValue('L'.$sn, $timeSubmitted);	
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="weekreport") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
			$header = 'a1:k1';
			
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Site Week Report by ".$creator)
						->setSubject("Site Week Report")
						->setDescription("Site Week Report")
						->setKeywords("Site Week Report")
						->setCategory("Site Week Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');
			
			//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'S/N')
					->setCellValue('B1', 'SITE ID')
					->setCellValue('C1', 'REPORT DATE')
					->setCellValue('D1', 'ADDRESS')
					->setCellValue('E1', 'Tank 1  DIESEL LEVEL')
					->setCellValue('F1', 'Tank 2  DIESEL LEVEL')
					->setCellValue('G1', 'Gen 1 RUNNING HOURS')
					->setCellValue('H1', 'Gen 2 RUNNING HOURS')
					->setCellValue('I1', 'COMMENT')
					->setCellValue('J1', 'Engr')
					->setCellValue('K1', 'DATE SUBMITTED');
					
					
			for($col = ord('a'); $col<= ord('k'); $col++){
				$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
			}
					
					$counter = 2;
					$sn = 0;
					//$alphabetCounter = 3;
			while($weekData = mysql_fetch_object($result)) {	
				$sn += 1;
				$wid = $weekData->id;
				$sid = $weekData->site_id;
				$engrid = $weekData->engr_id;
				$rdate = $weekData->report_date;
				$comment = $weekData->comment;
				$Submitted = date("Y-m-d, h:i:s a",$weekData->time_created);
				
				$engrData = $this->getUserInfo($engrid);
				$engrName = $engrData->name;
				
				$siteData = $this->getSiteInfo($sid);
				$siteID = $siteData->site_id;
				$address = $siteData->address;
				
				$objPHPExcel->getActiveSheet()						
				->setCellValue('A'.$counter, $sn)
				->setCellValue('B'.$counter, $siteID)
				->setCellValue('C'.$counter, $rdate)
				->setCellValue('D'.$counter, $address);
				
				//get the different diesel tank levels
				$DieselLevel = mysql_query("select * from weekly_diesel_level where week_id = '$wid' order by tank")or die(mysql_error());
				
				$colunm='E';
				while($dieselData = mysql_fetch_object($DieselLevel)) {
					$tank = $dieselData->tank;
					$liters = $dieselData->diesel_level;
					
					$objPHPExcel->getActiveSheet(0)->setCellValue($colunm.$counter, $liters);
					
					$colunm++;
				}
				
				//get the different Gen running hours
				$DieselLevel = mysql_query("select * from weekly_running_hours where week_id = '$wid'")or die(mysql_error());
				
				$colunm2='G';
				while($runhrData = mysql_fetch_object($DieselLevel)) {
					$pid = $runhrData->power_id;
					$hours = $runhrData->run_hours;
					
					$objPHPExcel->getActiveSheet(0)->setCellValue($colunm2.$counter, $hours);
					
					$colunm2++;
				}
				
				$objPHPExcel->getActiveSheet()						
					->setCellValue('I'.$counter, $comment)
					->setCellValue('J'.$counter, $engrName)
					->setCellValue('K'.$counter, $Submitted);
					
				$counter++;
			}
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
			// If you want to output e.g. a PDF file, simply do:
			//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="invoice") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Customer Payment Report by ".$creator)
						->setSubject("Customer Payment Report")
						->setDescription("Customer Payment Report")
						->setKeywords("Customer Payment Report")
						->setCategory("Customer Payment Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'TENANT')
					->setCellValue('B1', 'SITE ID')
					->setCellValue('C1', 'INVOICE DATE')
					->setCellValue('D1', 'DUE DATE')
					->setCellValue('E1', 'AMOUNT')
					->setCellValue('F1', 'STATUS');
					$sn = 2;
			while($invoiceData = mysql_fetch_object($result)) {	
		
				$customer_id  	= $invoiceData->customer_id;
				
				//get site engrid
				$CustomerData = $this->getCustomerInfo($customer_id);
				$siteID = $CustomerData->site_id;
				$customerName = $CustomerData->customer_name;
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $customerName)
						->setCellValue('B'.$sn, $site_id)
						->setCellValue('C'.$sn, $invoiceData->invoice_date)
						->setCellValue('D'.$sn, $invoiceData->due_date)
						->setCellValue('E'.$sn, $invoiceData->amount)
						->setCellValue('F'.$sn, $invoiceData->status);
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="itp") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("ITP Report by ".$creator)
						->setSubject("ITP Report")
						->setDescription("ITP Report")
						->setKeywords("ITP Report")
						->setCategory("ITP Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'CLIENT')
					->setCellValue('B1', 'SITE ID')
					->setCellValue('C1', 'ANNIVERSARY')
					->setCellValue('D1', 'COMMERCIAL TERMS');
					$sn = 2;
			while($itp = mysql_fetch_object($result)) {	
		
				$siteID  	= $itp->site_id;
				$anniversary 	= date("d-M-Y",strtotime($itp->anniversary));
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $itp->client)
						->setCellValue('B'.$sn, $site_id)
						->setCellValue('C'.$sn, $anniversary)
						->setCellValue('D'.$sn, $itp->commercial_terms);
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="expenses") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Expenses Report by ".$creator)
						->setSubject("Expenses Report")
						->setDescription("Expenses Report")
						->setKeywords("Expenses Report")
						->setCategory("Expenses Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'SITE ID')
					->setCellValue('B1', 'DATE')
					->setCellValue('C1', 'AMOUNT')
					->setCellValue('D1', 'DESCRIPTION')
					->setCellValue('E1', 'ISSUED TO')
					->setCellValue('F1', 'ADDED BY')
					->setCellValue('G1', 'TIME ADDED');
					$sn = 2;
			while($expenses = mysql_fetch_object($result)) {	
				
				$siteID 		= $expenses->site_id;
				$exDate			= date("Y-m-d",strtotime($expenses->ex_date));
				$exDesc			= $expenses->ex_desc;
				$amount	 		= $expenses->ex_amount;
				$issuedTo 		= $expenses->issued_to;
				$submitted		= date("Y-m-d, h:i:s a",$expenses->time_created);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $site_id)
						->setCellValue('B'.$sn, $exDate)
						->setCellValue('C'.$sn, $amount)
						->setCellValue('D'.$sn, $exDesc)
						->setCellValue('E'.$sn, $issuedTo)
						->setCellValue('F'.$sn, '-')
						->setCellValue('G'.$sn, $submitted);
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="contribution") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Contribution Report by ".$creator)
						->setSubject("Contribution Report")
						->setDescription("Contribution Report")
						->setKeywords("Contribution Report")
						->setCategory("Contribution Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'S/N')
					->setCellValue('B1', 'SITE ID')
					->setCellValue('C1', 'SITE ADDRESS')
					->setCellValue('D1', 'TENANCY')
					->setCellValue('E1', 'REVENUE')
					->setCellValue('F1', 'MTCE')
					->setCellValue('G1', 'DIESEL COST')
					->setCellValue('H1', 'CONTRIBUTION');
					$sn = 2;
			while($contr = mysql_fetch_object($result)) {	
				
				$siteID 		= $expenses->site_id;
				$exDate			= date("Y-m-d",strtotime($expenses->ex_date));
				$exDesc			= $expenses->ex_desc;
				$amount	 		= $expenses->ex_amount;
				$issuedTo 		= $expenses->issued_to;
				$submitted		= date("Y-m-d, h:i:s a",$expenses->time_created);
				
				//get site info
				$siteData = $this->getSiteInfo($siteID);
				$site_id = $siteData->site_id;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $site_id)
						->setCellValue('B'.$sn, $exDate)
						->setCellValue('C'.$sn, $amount)
						->setCellValue('D'.$sn, $exDesc)
						->setCellValue('E'.$sn, $issuedTo)
						->setCellValue('F'.$sn, '-')
						->setCellValue('G'.$sn, $submitted);
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}
	}
	
	function generateExcelQA($query,$table) {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "QA".$time.'.xlsx';
		
		if($table=="supply") {
		
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Supply Report by ".$creator)
						->setSubject("Supply Report")
						->setDescription("Supply Report")
						->setKeywords("Supply Report")
						->setCategory("Supply Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'Supply Date')
					->setCellValue('B1', 'Site ID')
					->setCellValue('C1', 'QA')
					->setCellValue('D1', 'Address')
					->setCellValue('E1', ' Initial Stock')
					->setCellValue('F1', 'Quantity Supplied')
					->setCellValue('G1', 'Total Stock')
					->setCellValue('H1', 'CPD')
					->setCellValue('I1', 'Next Supply Date')
					->setCellValue('J1', 'Time Submitted')
					->setCellValue('K1', 'Days to next Supply');
					for($col = ord('a'); $col<= ord('k'); $col++){
						$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
					}
					$sn = 2;
			while($supplyData = mysql_fetch_object($result)) {	
				//get supply details
				$supplyDetialsData = $this->getSupplyDetailsQA($supplyData->id,$supplyData->site_id);				
				//get site details
				$Sitedata = $this->getSiteInfo($supplyData->site_id);
				//get the number of days from supply to next supply
				$daysDiff = $this->getSupplyDateDiffQA($supplyData->id);
				//get number of days passt since supply
				$daysPast = $this->getDaysPastfromSupplyQA($supplyData->id); 
				$timeSubmitted = date("Y-m-d, h:i:s a",$supplyData->time_created);
				
				//user
				$engrData = $this->getUserInfo($supplyData->engr_id);
				$engrName = $engrData->name;
				
				//get remainder of diesel since last supply
				$totalUsed = $supplyData->cpd * $daysPast;
				$remainder = $supplyDetialsData->qty - $totalUsed;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $supplyData->supply_date)
						->setCellValue('B'.$sn, $Sitedata->site_id)
						->setCellValue('C'.$sn, $engrName)
						->setCellValue('D'.$sn, $Sitedata->address)
						->setCellValue('E'.$sn, $supplyDetialsData->stock)
						->setCellValue('F'.$sn, $supplyDetialsData->qty)
						->setCellValue('G'.$sn, $supplyDetialsData->total)
						->setCellValue('H'.$sn, $supplyData->cpd)
						->setCellValue('I'.$sn, $supplyData->next_supply_date)
						->setCellValue('J'.$sn, $timeSubmitted)
						->setCellValue('K'.$sn, $daysDiff.' Days');
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="service") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
		
		
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Service Report by ".$creator)
						->setSubject("Service Report")
						->setDescription("Service Report")
						->setKeywords("Service Report")
						->setCategory("Service Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'Site ID')
					->setCellValue('B1', 'Site Engr.')
					->setCellValue('C1', 'Service Date')
					->setCellValue('D1', 'Current Running Hr. Gen 1')
					->setCellValue('E1', 'Current Running Hr. Gen 2')
					->setCellValue('F1', 'Next Running Hr. Gen 1')
					->setCellValue('G1', 'Next Running Hr. Gen 2')
					->setCellValue('H1', 'Cost')
					->setCellValue('I1', 'Service Count')
					->setCellValue('J1', 'Next Service Date')
					->setCellValue('K1', 'Comment')
					->setCellValue('L1', 'Time Submitted');
					for($col = ord('a'); $col<= ord('l'); $col++){
						$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
					}
					$sn = 2;
			while($serviceData = mysql_fetch_object($result)) {	
				
				$Sitedata = $this->getSiteInfo($serviceData->site_id);
				$cost = number_format($serviceData->cost,2);
				$timeSubmitted = date("Y-m-d, h:i:s a",$serviceData->time_created);
				
				
				
				//get site engr name
				$EngrData = $this->getUserInfo($serviceData->engr_id);
				$EngrName = $EngrData->name;
			
				$objPHPExcel->getActiveSheet()
						->setCellValue('A'.$sn, $Sitedata->site_id)
						->setCellValue('B'.$sn, $EngrName)
						->setCellValue('C'.$sn, $serviceData->service_date);
				
				//get supply details
				$serviceQuery = mysql_query("select * from qa_servicing_details where service_id = '".$serviceData->id."' and site_id='".$serviceData->site_id."'")or die(mysql_error());
				
				$colunm1='D';
				$colunm2='F';
				while($serviceDetialsData = mysql_fetch_object($serviceQuery)){
					$objPHPExcel->getActiveSheet()->setCellValue($colunm1.$sn, $serviceDetialsData->curr_running_hrs);
					$objPHPExcel->getActiveSheet()->setCellValue($colunm2.$sn, $serviceDetialsData->next_running_hrs);
					
					$colunm1++;	
					$colunm2++;	
				}	
					
				$objPHPExcel->getActiveSheet()
						->setCellValue('H'.$sn, $cost)
						->setCellValue('I'.$sn, $serviceData->count)
						->setCellValue('J'.$sn, $serviceData->next_service_date)
						->setCellValue('K'.$sn, $serviceData->comment)
						->setCellValue('L'.$sn, $timeSubmitted);	
						
				$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');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}elseif($table=="weekreport") {
			//execute query
			$result = mysql_query($query)or die(mysql_error());
			$header = 'a1:k1';
			
			$objPHPExcel = new PHPExcel();
			// Set properties
			$objPHPExcel->getProperties()->setCreator($creator)
						->setLastModifiedBy($creator)
						->setTitle("Site Week Report by ".$creator)
						->setSubject("Site Week Report")
						->setDescription("Site Week Report")
						->setKeywords("Site Week Report")
						->setCategory("Site Week Report");
			$objPHPExcel->getActiveSheet()->setTitle('sheet1');
			
			//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

			$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'S/N')
					->setCellValue('B1', 'SITE ID')
					->setCellValue('C1', 'REPORT DATE')
					->setCellValue('C1', 'REPORT DATE')
					->setCellValue('D1', 'ADDRESS')
					->setCellValue('E1', 'Tank 1  DIESEL LEVEL')
					->setCellValue('F1', 'Tank 2  DIESEL LEVEL')
					->setCellValue('G1', 'Gen 1 RUNNING HOURS')
					->setCellValue('H1', 'Gen 2 RUNNING HOURS')
					->setCellValue('I1', 'COMMENT')
					->setCellValue('J1', 'QA')
					->setCellValue('K1', 'DATE SUBMITTED');
					
					
			for($col = ord('a'); $col<= ord('k'); $col++){
				$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
			}
					
					$counter = 2;
					$sn = 0;
					//$alphabetCounter = 3;
			while($weekData = mysql_fetch_object($result)) {	
				$sn += 1;
				$wid = $weekData->id;
				$sid = $weekData->site_id;
				$engrid = $weekData->engr_id;
				$rdate = $weekData->report_date;
				$comment = $weekData->comment;
				$Submitted = date("Y-m-d, h:i:s a",$weekData->time_created);
				
				$engrData = $this->getUserInfo($engrid);
				$engrName = $engrData->name;
				
				$siteData = $this->getSiteInfo($sid);
				$siteID = $siteData->site_id;
				$address = $siteData->address;
				
				$objPHPExcel->getActiveSheet()						
				->setCellValue('A'.$counter, $sn)
				->setCellValue('B'.$counter, $siteID)
				->setCellValue('C'.$counter, $rdate)
				->setCellValue('D'.$counter, $address);
				
				//get the different diesel tank levels
				$DieselLevel = mysql_query("select * from qa_weekly_diesel_level where week_id = '$wid' order by tank")or die(mysql_error());
				
				$colunm='E';
				while($dieselData = mysql_fetch_object($DieselLevel)) {
					$tank = $dieselData->tank;
					$liters = $dieselData->diesel_level;
					
					$objPHPExcel->getActiveSheet(0)->setCellValue($colunm.$counter, $liters);
					
					$colunm++;
				}
				
				//get the different Gen running hours
				$DieselLevel = mysql_query("select * from qa_weekly_running_hours where week_id = '$wid'")or die(mysql_error());
				
				$colunm2='G';
				while($runhrData = mysql_fetch_object($DieselLevel)) {
					$pid = $runhrData->power_id;
					$hours = $runhrData->run_hours;
					
					$objPHPExcel->getActiveSheet(0)->setCellValue($colunm2.$counter, $hours);
					
					$colunm2++;
				}
				
				$objPHPExcel->getActiveSheet()						
					->setCellValue('I'.$counter, $comment)
					->setCellValue('J'.$counter, $engrName)
					->setCellValue('K'.$counter, $Submitted);
					
				$counter++;
			}
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
			// If you want to output e.g. a PDF file, simply do:
			//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
			$objWriter->save("exports/".$FileName);
				
				return $FileName;
		}
	}	
	
	function generateExcelSite() {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "Site".$time.'.xlsx';
		
		//execute query
		$query = "select * from site";
		$result = mysql_query($query)or die(mysql_error());
		$header = 'a1:k1';
		
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()->setCreator($creator)
					->setLastModifiedBy($creator)
					->setTitle("Site Week Report by ".$creator)
					->setSubject("Site Week Report")
					->setDescription("Site Week Report")
					->setKeywords("Site Week Report")
					->setCategory("Site Week Report");
		$objPHPExcel->getActiveSheet()->setTitle('sheet1');
		
		//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', 'S/N')
			->setCellValue('B1', 'SITE ID')
			->setCellValue('C1', 'STATE')
			->setCellValue('D1', 'ADDRESS')
			->setCellValue('E1', 'LONGITUDE')
			->setCellValue('F1', 'LATITUDE')
			->setCellValue('G1', 'TENANTS COUNT')
			->setCellValue('H1', 'TENANTS');
				
				
		for($col = ord('a'); $col<= ord('h'); $col++) {
			$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
		}
				
		$counter = 2;
		$sn = 0;
		//$alphabetCounter = 3;
		while($site = mysql_fetch_object($result)) {	
			$sn += 1;
			$id = $site->id;
			$sid = $site->site_id;
			$state = $site->state;
			$address = $site->address;
			$longitude = $site->longitude;
			$latitude = $site->latitude;
						
			$objPHPExcel->getActiveSheet()						
			->setCellValue('A'.$counter, $sn)
			->setCellValue('B'.$counter, $sid)
			->setCellValue('C'.$counter, $state)
			->setCellValue('D'.$counter, $address)
			->setCellValue('E'.$counter, $longitude)
			->setCellValue('F'.$counter, $latitude);
			
			//get the different diesel tank levels
			$tenantsSQL = mysql_query("select * from site_tenants where site_id = '$id'")or die(mysql_error());
			
			$tenantsArray  = array();
			while($tenants = mysql_fetch_object($tenantsSQL)) {
				$custid = $tenants->customer_id;
				//get customer name
				$custData = $this->getCustomerInfo($custid);
				$customer = $custData->short_name;
				$tenantsArray[] = $customer;
			}
			//count number of tenants for site;
			$tenantCount = $this->countSiteTenants($id);
			$siteTenants = implode(',',$tenantsArray);			
			$objPHPExcel->getActiveSheet()
				->setCellValue('G'.$counter, $tenantCount)
				->setCellValue('H'.$counter, $siteTenants);
			
			$counter++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// If you want to output e.g. a PDF file, simply do:
		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
		$objWriter->save("exports/".$FileName);
			
		return "<div class=\"alert alert-success\">
		Excel File Generated. Click on the download Button to download it.
		<a href=\"exports/$FileName\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
		</div>";
	}	
	
	function generateExcelLiveSite() {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "Site".$time.'.xlsx';
		
		//execute query
		$query = "select * from site where status = 'Live'";
		$result = mysql_query($query)or die(mysql_error());
		$header = 'a1:k1';
		
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()->setCreator($creator)
					->setLastModifiedBy($creator)
					->setTitle("Site Week Report by ".$creator)
					->setSubject("Site Week Report")
					->setDescription("Site Week Report")
					->setKeywords("Site Week Report")
					->setCategory("Site Week Report");
		$objPHPExcel->getActiveSheet()->setTitle('sheet1');
		
		//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', 'S/N')
			->setCellValue('B1', 'SITE ID')
			->setCellValue('C1', 'STATE')
			->setCellValue('D1', 'ADDRESS')
			->setCellValue('E1', 'LONGITUDE')
			->setCellValue('F1', 'LATITUDE')
			->setCellValue('G1', 'TENANTS COUNT')
			->setCellValue('H1', 'TENANTS');
				
				
		for($col = ord('a'); $col<= ord('h'); $col++) {
			$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
		}
				
		$counter = 2;
		$sn = 0;
		//$alphabetCounter = 3;
		while($site = mysql_fetch_object($result)) {	
			$sn += 1;
			$id = $site->id;
			$sid = $site->site_id;
			$state = $site->state;
			$address = $site->address;
			$longitude = $site->longitude;
			$latitude = $site->latitude;
						
			$objPHPExcel->getActiveSheet()						
			->setCellValue('A'.$counter, $sn)
			->setCellValue('B'.$counter, $sid)
			->setCellValue('C'.$counter, $state)
			->setCellValue('D'.$counter, $address)
			->setCellValue('E'.$counter, $longitude)
			->setCellValue('F'.$counter, $latitude);
			
			//get the different diesel tank levels
			$tenantsSQL = mysql_query("select * from site_tenants where site_id = '$id'")or die(mysql_error());
			
			$tenantsArray  = array();
			while($tenants = mysql_fetch_object($tenantsSQL)) {
				$custid = $tenants->customer_id;
				//get customer name
				$custData = $this->getCustomerInfo($custid);
				$customer = $custData->short_name;
				$tenantsArray[] = $customer;
			}
			
			//count number of tenants for site;
			$tenantCount = $this->countSiteTenants($id);
			$siteTenants = implode(',',$tenantsArray);			
			$objPHPExcel->getActiveSheet()
				->setCellValue('G'.$counter, $tenantCount);
			
			$counter++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// If you want to output e.g. a PDF file, simply do:
		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
		$objWriter->save("exports/".$FileName);
			
		return "<div class=\"alert alert-success\">
		Excel File Generated. Click on the download Button to download it.
		<a href=\"exports/$FileName\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
		</div>";
	}			
	
	function PowerConsumptionExcel() {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "Site".$time.'.xlsx';
		
		//execute query
		$query = "select * from site";
		$result = mysql_query($query)or die(mysql_error());
		$header = 'a1:k1';
		
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()->setCreator($creator)
					->setLastModifiedBy($creator)
					->setTitle("Site Power Consumption Report by ".$creator)
					->setSubject("Site Power Consumption Report")
					->setDescription("Site Power Consumption Report")
					->setKeywords("Site Power Consumption Report")
					->setCategory("Site Power Consumption Report");
		$objPHPExcel->getActiveSheet()->setTitle('sheet1');
		
		//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', 'S/N')
			->setCellValue('B1', 'SITE ID')
			->setCellValue('C1', 'STATE')
			->setCellValue('D1', 'ADDRESS')
			->setCellValue('E1', 'LONGITUDE')
			->setCellValue('F1', 'LATITUDE')
			->setCellValue('G1', 'TENANTS COUNT')
			->setCellValue('H1', 'TENANTS')
			->setCellValue('I1', 'POWER THRESHOLD')
			->setCellValue('J1', 'CURR CONSUMPTION')
			->setCellValue('K1', 'MONTHLY DIESEL USAGE')
			->setCellValue('L1', 'MONTHLY DIESEL COST');
				
				
		for($col = ord('a'); $col<= ord('l'); $col++) {
			$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
		}
				
		$counter = 2;
		$sn = 0;
		//$alphabetCounter = 3;
		while($site = mysql_fetch_object($result)) {	
			$sn += 1;
			$id = $site->id;
			$sid = $site->site_id;
			$state = $site->state;
			$address = $site->address;
			$longitude = $site->longitude;
			$latitude = $site->latitude;
			$Threshold = $site->power_threshold;
						
			$objPHPExcel->getActiveSheet()						
			->setCellValue('A'.$counter, $sn)
			->setCellValue('B'.$counter, $sid)
			->setCellValue('C'.$counter, $state)
			->setCellValue('D'.$counter, $address)
			->setCellValue('E'.$counter, $longitude)
			->setCellValue('F'.$counter, $latitude);
			
			//get the different diesel tank levels
			$tenantsSQL = mysql_query("select * from site_tenants where site_id = '$id'")or die(mysql_error());
			
			$tenantsArray  = array();
			while($tenants = mysql_fetch_object($tenantsSQL)) {
				$custid = $tenants->customer_id;
				//get customer name
				$custData = $this->getCustomerInfo($custid);
				$customer = $custData->short_name;
				$tenantsArray[] = $customer;
			}
			//count number of tenants for site;
			$tenantCount = $this->countSiteTenants($id);
			$powerConsumed = $this->getSitePowerConsumption($id);
			$cpdValue = $this->getCurrentCPD($id);
			$cpmValue = $cpdValue * 30;
			$dieselCost = 150*$cpmValue;
			$siteTenants = implode(',',$tenantsArray);			
			$objPHPExcel->getActiveSheet()
				->setCellValue('G'.$counter, $tenantCount)
				->setCellValue('H'.$counter, $siteTenants)
				->setCellValue('I'.$counter, $Threshold."kw")
				->setCellValue('J'.$counter, $powerConsumed."kw")
				->setCellValue('K'.$counter, $cpmValue)
				->setCellValue('L'.$counter, $dieselCost);
			
			$counter++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// If you want to output e.g. a PDF file, simply do:
		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
		$objWriter->save("exports/".$FileName);
			
		return "<div class=\"alert alert-success\">
		Excel File Generated. Click on the download Button to download it.
		<a href=\"exports/$FileName\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
		</div>";
	}
	
	function DowntimeLog2Excel() {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "Downtimelog_".$time.'.xlsx';
		
		//execute query
		$query = "select * from downtime where escalation_valid = 'True' order by time_created desc";
		$result = mysql_query($query)or die(mysql_error());
		$header = 'a1:l1';
		
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()->setCreator($creator)
					->setLastModifiedBy($creator)
					->setTitle("Sites Downtime Log by ".$creator)
					->setSubject("Sites Downtime Log")
					->setDescription("Sites Downtime Log")
					->setKeywords("Sites Downtime Log")
					->setCategory("Sites Downtime Log");
		$objPHPExcel->getActiveSheet()->setTitle('sheet1');
		
		//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', 'S/N')
			->setCellValue('B1', 'Site ID')
			->setCellValue('C1', 'BCT ID')
			->setCellValue('D1', 'Address')
			->setCellValue('E1', 'Tenant')
			->setCellValue('F1', 'Time Down')
			->setCellValue('G1', 'Validity')
			->setCellValue('H1', 'Cause')
			->setCellValue('I1', 'Time up')
			->setCellValue('J1', 'Cause Status')
			->setCellValue('K1', 'Down Time Duration')
			->setCellValue('L1', 'Comments');
				
		//automatically adjust the colunm width		
		for($col = ord('a'); $col<= ord('l'); $col++) {
			$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
		}
				
		$counter = 2;
		$sn = 0;
		//$alphabetCounter = 3;
		while($downtime = mysql_fetch_object($result)) {
			$sn +=1;
			$id 			= $downtime->id;
			$siteID 		= $downtime->site_id;
			$tenantID 		= $downtime->tenant_id;
			$down_time		 = $downtime->time_down;
			$validity 		= $downtime->escalation_valid;
			$status 		= $downtime->status;
			$cause			= $downtime->downtime_cause;
			$cause_status	= $downtime->esc_cause_status;
			$time_up		= $downtime->time_up;
			$comment		= $downtime->comment;
			
			//get site ID
			$siteData = $this->getSiteInfo($siteID);
			$site_id = $siteData->site_id;
			$bct_id = $siteData->bct_id;
			$address = $siteData->address;
						
			$dteStart = new DateTime($down_time);
			$dteEnd   = new DateTime($time_up);
			$dteDiff  = $dteStart->diff($dteEnd);
			$duration = $dteDiff->format("%D day(s): %H hrs:%I mins");
			
			//get percentage downtime
			
			
			//get Tenant
			$tenantData = $this->getCustomerInfo($tenantID);
			$tenant = $tenantData->short_name;
						
			$objPHPExcel->getActiveSheet()						
			->setCellValue('A'.$counter, $sn)
			->setCellValue('B'.$counter, $site_id)
			->setCellValue('C'.$counter, $bct_id)
			->setCellValue('D'.$counter, $address)
			->setCellValue('E'.$counter, $tenant)
			->setCellValue('F'.$counter, $down_time)
			->setCellValue('G'.$counter, $validity)
			->setCellValue('H'.$counter, $cause)
			->setCellValue('I'.$counter, $time_up)
			->setCellValue('J'.$counter, $cause_status)
			->setCellValue('K'.$counter, $duration)
			->setCellValue('L'.$counter, $comment);
			
			$counter++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// If you want to output e.g. a PDF file, simply do:
		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
		$objWriter->save("exports/".$FileName);
			
		return "<div class=\"alert alert-success\">
		Excel File Generated. Click on the download Button to download it.
		<a href=\"exports/$FileName\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
		</div>";
	}
	
	function DowntimeLogSearch2Excel($query) {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "Downtimelog_".$time.'.xlsx';
		
		//execute query
		$result = mysql_query($query)or die(mysql_error());
		$header = 'a1:l1';
		
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()->setCreator($creator)
					->setLastModifiedBy($creator)
					->setTitle("Sites Downtime Log by ".$creator)
					->setSubject("Sites Downtime Log")
					->setDescription("Sites Downtime Log")
					->setKeywords("Sites Downtime Log")
					->setCategory("Sites Downtime Log");
		$objPHPExcel->getActiveSheet()->setTitle('sheet1');
		
		//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', 'S/N')
			->setCellValue('B1', 'Site ID')
			->setCellValue('C1', 'BCT ID')
			->setCellValue('D1', 'Address')
			->setCellValue('E1', 'Tenant')
			->setCellValue('F1', 'Time Down')
			->setCellValue('G1', 'Validity')
			->setCellValue('H1', 'Cause')
			->setCellValue('I1', 'Time up')
			->setCellValue('J1', 'Cause Status')
			->setCellValue('K1', 'Down Time Duration')
			->setCellValue('L1', 'Comments');
				
		//automatically adjust the colunm width		
		for($col = ord('a'); $col<= ord('l'); $col++) {
			$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
		}
				
		$counter = 2;
		$sn = 0;
		//$alphabetCounter = 3;
		while($downtime = mysql_fetch_object($result)) {
			$sn +=1;
			$id 			= $downtime->id;
			$siteID 		= $downtime->site_id;
			$tenantID 		= $downtime->tenant_id;
			$down_time		 = $downtime->time_down;
			$validity 		= $downtime->escalation_valid;
			$status 		= $downtime->status;
			$cause			= $downtime->downtime_cause;
			$cause_status	= $downtime->esc_cause_status;
			$time_up		= $downtime->time_up;
			$comment		= $downtime->comment;
			
			//get site ID
			$siteData = $this->getSiteInfo($siteID);
			$site_id = $siteData->site_id;
			$bct_id = $siteData->bct_id;
			$address = $siteData->address;
						
			$dteStart = new DateTime($down_time);
			$dteEnd   = new DateTime($time_up);
			$dteDiff  = $dteStart->diff($dteEnd);
			$duration = $dteDiff->format("%D day(s): %H hrs:%I mins");
			
			//get percentage downtime
			
			
			//get Tenant
			$tenantData = $this->getCustomerInfo($tenantID);
			$tenant = $tenantData->short_name;
						
			$objPHPExcel->getActiveSheet()						
			->setCellValue('A'.$counter, $sn)
			->setCellValue('B'.$counter, $site_id)
			->setCellValue('C'.$counter, $bct_id)
			->setCellValue('D'.$counter, $address)
			->setCellValue('E'.$counter, $tenant)
			->setCellValue('F'.$counter, $down_time)
			->setCellValue('G'.$counter, $validity)
			->setCellValue('H'.$counter, $cause)
			->setCellValue('I'.$counter, $time_up)
			->setCellValue('J'.$counter, $cause_status)
			->setCellValue('K'.$counter, $duration)
			->setCellValue('L'.$counter, $comment);
			
			$counter++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// If you want to output e.g. a PDF file, simply do:
		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
		$objWriter->save("exports/".$FileName);
			
		return $FileName;
	}
	
	function siteDailyAvalibility($downTime, $upTime) {
			$dteEnd   = new DateTime($upTime);
			$dteStart = new DateTime($downTime);
			$dteDiff  = $dteStart->diff($dteEnd);
			$daysDown = $dteDiff->format("%D");
			$hoursDown = $dteDiff->format("%H");
			$minutesDown = $dteDiff->format("%I");
			
			$MTTR_mins = (($daysDown * 24) *1440) + ($hoursDown * 60) + $minutesDown;
			
	}
	
	function generateContributionExcel($month,$year) {
		$this->connect_db();
		
		$time = date("y-d-m _H-i-sa",time());
		$creator = $_SESSION['username'];
		$FileName = "Site".$time.'.xlsx';
		
		//execute query
		$query = "SELECT id,site_id,address FROM site where status='Live'";
		$result = mysql_query($query)or die(mysql_error());
		
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()->setCreator($creator)
					->setLastModifiedBy($creator)
					->setTitle("Contribution Report by ".$creator)
					->setSubject("Site Contribution Report")
					->setDescription("Site Contribution Report")
					->setKeywords("Site Contribution Report")
					->setCategory("Site Contribution Report");
		$objPHPExcel->getActiveSheet()->setTitle('Contribution per Site');
		
		//$objPHPExcel->setActiveSheetIndex(0)->getStyle($header)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('00ffff00');

		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', 'S/N')
			->setCellValue('B1', 'SITE ID')
			->setCellValue('C1', 'ADDRESS')
			->setCellValue('D1', 'TENANCY')
			->setCellValue('E1', 'REVENUE')
			->setCellValue('F1', 'MAINTENANCE')
			->setCellValue('G1', 'DIESEL COST')
			->setCellValue('H1', 'CONTRIBUTION')
			->setCellValue('I1', 'STATUS');
				
				
		for($col = ord('a'); $col<= ord('h'); $col++) {
			$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension(chr($col))->setAutoSize(true);
		}
				
		$counter = 2;
		$sn = 0;
		//$alphabetCounter = 3;
		while($site = mysql_fetch_object($result)) {	
			$sn += 1;
			$id = $site->id;
			$sid = $site->site_id;
			$address = $site->address;
			
			//count number of tenants for site;
			$tenantCount = $this->countSiteTenants($id);	
			
			//get site revenue;
			$siteRevenue = $this->getSiteRevenue($id);		
			
			//get site Mainatenance Cos;
			$siteMtce = $this->getSiteMainatenanceCost($id,$month,$year);	
			
			//get site Mainatenance Cos;
			$siteDieselCost = $this->getSiteDieselCost($id,$month,$year);	
			
			$totalCost = $siteMtce + $siteDieselCost;
			
			$contribution = $siteRevenue - $totalCost;
					
			$objPHPExcel->getActiveSheet()						
			->setCellValue('A'.$counter, $sn)
			->setCellValue('B'.$counter, $sid)
			->setCellValue('C'.$counter, $address)
			->setCellValue('D'.$counter, $tenantCount)
			->setCellValue('E'.$counter, $siteRevenue)
			->setCellValue('F'.$counter, $siteMtce)
			->setCellValue('G'.$counter, $siteDieselCost)
			->setCellValue('H'.$counter, $contribution);
			
			if($totalCost>$siteRevenue) {
				$objPHPExcel->getActiveSheet()->setCellValue('I'.$counter, "Loss");
			}elseif($totalCost==$siteRevenue){
				$objPHPExcel->getActiveSheet()->setCellValue('I'.$counter, "Even");
			}elseif($totalCost<$siteRevenue){
				$objPHPExcel->getActiveSheet()->setCellValue('I'.$counter, "Gained");
			}
			
			
			$counter++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// If you want to output e.g. a PDF file, simply do:
		//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
		$objWriter->save("exports/".$FileName);
			
		return $FileName;
	}
	
	function contributionReport($month,$year) {
		$this->connect_db();
		
		$sql = "SELECT id,site_id,address FROM site where status='Live'";
		$result = mysql_query($sql)or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		
		if($num_rows > 0){
	   
			//generate excel File 
			$excelFile = $this->generateContributionExcel($month,$year);
				
				echo"<div class=\"panel panel-piluku\">
					<div class=\"panel-heading\">
						<h3 class=\"panel-title\">
							<span class=\"panel-options\">
								<a href=\"exports/$excelFile\" target=\"_blank\" class=\"btn btn-default btn-sm\" data-toggle=\"tooltip\" title=\"Download Excel\"><i class=\"fa fa-download\"></i></a>
								<a href=\"#\" class=\"btn btn-default btn-sm\" data-toggle=\"modal\" data-target=\"#myModalBulkEmail\" title=\"Email Excel\"><i class=\"fa fa-envelope\"></i></a>
							</span>
						</h3>
					</div>
					<div class=\"panel-body\">
                    <div class=\"small-size\">";
				
			echo"<table id=\"example1\" class=\"table table-bordered table-striped table-hover\">
               <thead>
                    <tr>
						<th width=\"5%\">S/N</th>
						<th>Site Name</th>
						<th>Site Address.</th>
						<th>Tenanct</th>
						<th>Revenue</th>
						<th>Mtce</th>
						<th>Diesel</th>
						<th>Total Cost</th>
						<th>Contribution</th>
						<th>Status</th>
                    </tr>
                </thead>
				<tbody>";
			 $sn = 0;
			 while($site = mysql_fetch_object($result)) {
				$sn += 1;
				$id 			= $site->id;
				$siteID 		= $site->site_id;
				$address 		= $site->address;				
				
				//count number of tenants for site;
				$tenantCount = $this->countSiteTenants($id);	
				
				//get site revenue;
				$siteRevenue = $this->getSiteRevenue($id);		
				
				//get site Mainatenance Cos;
				$siteMtce = $this->getSiteMainatenanceCost($id,$month,$year);	
				
				//get site Mainatenance Cos;
				$siteDieselCost = $this->getSiteDieselCost($id,$month,$year);	
				
				$totalCost = $siteMtce + $siteDieselCost;
				
				$contribution = $siteRevenue - $totalCost;
				
				echo"<tr>
                        <td>$sn</td>
                        <td>$siteID</td>
                        <td>$address</td>
                        <td>$tenantCount</td>
                        <td>N".number_format($siteRevenue,2)."</td>
                        <td>N".number_format($siteMtce,2)."</td>
                        <td>N".number_format($siteDieselCost,2)."</td>
                        <td>N".number_format($totalCost,2)."</td>
                        <td>N".number_format($contribution,2)."</td>
                        <td>";
						if($totalCost>$siteRevenue) {
							echo"<div class=\"label label-danger\">Loss</div>";
						}elseif($totalCost==$siteRevenue){
							echo"<div class=\"label label-primary\">Even</div>";
						}elseif($totalCost<$siteRevenue){
							echo"<div class=\"label label-success\">Gained</div>";
						}
						echo"</td>
                     </tr>";
			 }
			echo"</tbody></table>
				<!-- Modal -->
				<div class=\"modal fade\" id=\"myModalBulkEmail\" tabindex=\"-2\" role=\"dialog\" aria-labelledby=\"myModalBulkEmailLabel\" aria-hidden=\"true\">
				<form name=\"form_email2\" method=\"post\" action=\"". $_SERVER['PHP_SELF']."\">
				  <div class=\"modal-dialog\">
					<div class=\"modal-content\">
					  <div class=\"modal-header\">
						<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
						<h4 class=\"modal-title\" id=\"myModalBulkEmailLabel\">Send Date Report to Email</h4>
					  </div>
					  <div class=\"modal-body\">
						<label>Email Address</label>
						<input type=\"text\" class=\"form-control\" placeholder=\"example@email.com\" name=\"email_add\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$excelFile\" name=\"file_name\" required />
						<input type=\"hidden\" class=\"form-control\" value=\"$dateString\" name=\"dateString\" required />
					  </div>
					  <div class=\"modal-footer\">
						<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>
						<input type=\"submit\" name=\"send_bulk_em\" class=\"btn btn-primary\" value=\"Send Report\" />
					  </div>
					</div>
				  </div>
				  </form>
				</div>
			</div>
                </div><!-- /.box-body -->
             </div><!-- /.box -->";
			 
		}else{
			echo"<div class=\"alert alert-danger\">No Supplies Report for selected Date</div>";   
	   }
	}

	function homeNavBox() {
	
		if($_SESSION['level']=="Supervisor") {
			echo"<div class=\"row IN3LAKD-d-a\">
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(23,27,153);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"dash.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">h</p> 
							<p class=\"IN3LAKD-Z-g\">Dash Board</p> 
							<p class=\"IN3LAKD-Z-f\">Quick Activity Overview.</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">View all important activities e.g. Invoices, work orders etc at a glance.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(236, 110, 79);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"projects.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">3</p> 
							<p class=\"IN3LAKD-Z-g\">Projects</p> 
							<p class=\"IN3LAKD-Z-f\">Track all Tenants</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Access all ongoing projects.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(0, 221, 136);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"maintenance.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">A</p> 
							<p class=\"IN3LAKD-Z-g\">Maintenance</p> 
							<p class=\"IN3LAKD-Z-f\">Track sites and tenants</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Track your site, tenants and all related opponent.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(153,102,255);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"invoice.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">n</p> 
							<p class=\"IN3LAKD-Z-g\">Invoice</p> <p class=\"IN3LAKD-Z-f\">See Invoices faster</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Track all tenants invoice</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(250,194,42);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"reports.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">Z</p> 
							<p class=\"IN3LAKD-Z-g\">Reports</p> 
							<p class=\"IN3LAKD-Z-f\">quickly view reports</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Run reports on site related opponents</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(241, 157, 82);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"mng_tickets.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">W</p> 
							<p class=\"IN3LAKD-Z-g\">Tickets</p> 
							<p class=\"IN3LAKD-Z-f\">track tickets</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">View, open and respond to tickets</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(72, 163, 205);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"exp_dash.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">o</p> 
							<p class=\"IN3LAKD-Z-g\">Expenses</p> 
							<p class=\"IN3LAKD-Z-f\">Control your spending.</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Record expenses and budget your company spending.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(42, 56, 97);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"purchase.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">$</p> 
							<p class=\"IN3LAKD-Z-g\">Purchasing</p> 
							<p class=\"IN3LAKD-Z-f\">Simplify your purchasing.</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Easily order products and pay vendors on time.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(50,146,98);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"viewasset.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">z</p> 
							<p class=\"IN3LAKD-Z-g\">Assets</p> 
							<p class=\"IN3LAKD-Z-f\">Track Your site properties.</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Keep record of all your site properties and stop wondering where they are.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(157,34,64);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"config.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">y</p> 
							<p class=\"IN3LAKD-Z-g\">Configurations</p> 
							<p class=\"IN3LAKD-Z-f\">Setup your system</p>
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Setup Sites, Assets, and other related functions.</p> 
						</div>
					</a> 
				</div>
			</div>
		</div>";
		}elseif($_SESSION['level']=="Engineer" || $_SESSION['level']=="QA"){
			echo"<div class=\"row IN3LAKD-d-a\">
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(236, 110, 79);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"engrsupplybatch.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">Z</p> 
							<p class=\"IN3LAKD-Z-g\">Supply Report</p> 
							<p class=\"IN3LAKD-Z-f\">Submitt Supply Report</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Manage all your sites supply reports.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(0, 221, 136);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"engr_sites_service.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">Z</p> 
							<p class=\"IN3LAKD-Z-g\">Service Report</p> 
							<p class=\"IN3LAKD-Z-f\">Submitt Supply Report</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Manage all your sites service reports.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(153,102,255);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"engr_week_report.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">Z</p> 
							<p class=\"IN3LAKD-Z-g\">Weekly Report</p> <p class=\"IN3LAKD-Z-f\">Submitt Weekly Report</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Manage all your sites weekly reports.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(250,194,42);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"mng_tickets.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">W</p> 
							<p class=\"IN3LAKD-Z-g\">Tickets</p> 
							<p class=\"IN3LAKD-Z-f\">track tickets</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Open and follow up site tickets</p> 
						</div>					
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(250,194,42);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"downtime.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">W</p> 
							<p class=\"IN3LAKD-Z-g\">Down Time Logger</p> 
							<p class=\"IN3LAKD-Z-f\">Log Site Down time</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Register all site escalation</p>
						</div>					
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(157,34,64);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"transreq.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">F</p> 
							<p class=\"IN3LAKD-Z-g\">Transfer Request</p> 
							<p class=\"IN3LAKD-Z-f\">Move diesel, equipments etc</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Place request on item movement from site to site</p> 
						</div>
					</a> 
				</div>
			</div>
		</div>";
		}elseif($_SESSION['level']=="Accountant"){
			echo"<div class=\"row IN3LAKD-d-a\">
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(153,102,255);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"invoice.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">n</p> 
							<p class=\"IN3LAKD-Z-g\">Invoice</p> <p class=\"IN3LAKD-Z-f\">See Invoices faster</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Track all tenants invoice</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(250,194,42);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"reports.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">Z</p> 
							<p class=\"IN3LAKD-Z-g\">Reports</p> 
							<p class=\"IN3LAKD-Z-f\">quickly view reports</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Run reports on site related opponents</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(72, 163, 205);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"exp_dash.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">o</p> 
							<p class=\"IN3LAKD-Z-g\">Expenses</p> 
							<p class=\"IN3LAKD-Z-f\">Control your spending.</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Record expenses and budget your company spending.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(42, 56, 97);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"purchase.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">$</p> 
							<p class=\"IN3LAKD-Z-g\">Purchasing</p> 
							<p class=\"IN3LAKD-Z-f\">Simplify your purchasing.</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Easily order products and pay vendors on time.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(12, 26, 97);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"viewasset.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">z</p> 
							<p class=\"IN3LAKD-Z-g\">Assets</p> 
							<p class=\"IN3LAKD-Z-f\">Track Your site properties.</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Keep record of all your site properties and stop wondering where they are.</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(157,34,64);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"userfiles.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">F</p> 
							<p class=\"IN3LAKD-Z-g\">User Files</p> 
							<p class=\"IN3LAKD-Z-f\">Store images and videosk</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Dump all related image and video files related to your work</p> 
						</div>
					</a> 
				</div>
			</div>
		</div>";
		}if($_SESSION['level']=="NOC Admin") {
			echo"<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(0, 221, 136);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"track_downt.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">A</p> 
							<p class=\"IN3LAKD-Z-g\">Track Down Time</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Record & Track Escalations</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(153,102,255);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"noc_timet.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">n</p> 
							<p class=\"IN3LAKD-Z-g\">NOC Timetable</p>
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Manage and view NOC Timetable</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(50,146,98);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"viewasset.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">z</p> 
							<p class=\"IN3LAKD-Z-g\">Sites</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">View all Sites and details</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(157,34,64);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"addusers.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">g</p> 
							<p class=\"IN3LAKD-Z-g\">Manage Team</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Add new NOC Team staff</p> 
						</div>
					</a> 
				</div>
			</div>
		</div>";
		}if($_SESSION['level']=="NOC Team") {
			echo"<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(50,146,98);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"viewasset.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">z</p> 
							<p class=\"IN3LAKD-Z-g\">Sites</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">View all Sites and details</p> 
						</div>
					</a> 
				</div>
			</div>
			<div class=\"col-xs-6 col-sm-6 col-md-3 IN3LAKD-Z-d slideUp\">
				<div style=\"background-color: rgb(157,34,64);\" class=\"IN3LAKD-Z-a\"> 
					<a href=\"track_downt.php\" class=\"IN3LAKD-Z-b\">
						<div class=\"tile-inner\"> 
							<p class=\"picto-font picto-font-fixed-width img-circle IN3LAKD-Z-e\">A</p> 
							<p class=\"IN3LAKD-Z-g\">Track Down Time</p> 
						</div> 
						<div class=\"tile-inner tile-inner-down\"> 
							<p class=\"IN3LAKD-Z-c\">Record & Track Escalations</p> 
						</div>
					</a> 
				</div>
			</div>
			
		</div>";
		}
	}
	
}

?>
