<?php
session_start();
ob_start();

function doLogin()
{

	// if we found an error save the error message in this variable
	$errorMessage = '';
	
	$username = $_POST['mec_username'];
	$password = $_POST['mec_password'];
	
	// first, make sure the username & password are not empty
	if ($username == '') {
		$errorMessage = 'You Must Enter Administrator User Name';
	} else if ($password == '') {
		$errorMessage = 'You Must Enter Administrator Password';
	} 

     else {
		// check the database and see if the username and password combo do match md5($str)

				
				 $sql="select * from mec_admin where mec_username='".$username."' and mec_password='".$password."'";
				
				$result=mysql_query($sql);
				
		//$result = dbQuery($sql);
	
		if (mysql_num_rows($result) == 1) {
			$row = mysql_fetch_assoc($result);
			$_SESSION['mec_admin_id'] = $row['mec_admin_id'];
			 $_SESSION['mec_admin_id']; 
		
			// log the time when the user last login
			/*$sql = "UPDATE tbl_user 
			        SET user_last_login = NOW() 
					WHERE user_id = '{$row['user_id']}'";
			dbQuery($sql);*/

			// now that the user is verified we move on to the next page
            // if the user had been in the admin pages before we move to
			// the last page visited
			if (isset($_SESSION['mec_admin_id'])) {
				header('Location: welcomepage.php');
				exit;
			} else {
				header('Location:index.php');
				exit;
			}
		} else {
			$errorMessage = 'Wrong username or password';
		}		
			
	}
	
	return $errorMessage;
}
	
///////////////////check user or logout//////////////

function checkUser()
{

// if the session id is not set, redirect to login page
	if (!isset($_SESSION['mec_admin_id'])) {
		header('Location: index.php');
		exit;
	}
	
	// the user want to logout
	if (isset($_GET['logout'])) {
		doLogout();
	}
}

function doLogout()
{
if (isset($_SESSION['mec_admin_id'])) {
		unset($_SESSION['mec_admin_id']);
		session_unregister('mec_admin_id');
	}
		
	header('Location: login.php');
	exit;
}

?>