<?php
	
	if (!empty($_REQUEST['logout'])) {
		$_SESSION['userID'] = "";
		$_SESSION['clientID'] = "";
		$_SESSION['userAuth'] = "";
		$_SESSION['userName'] = "";
		$_SESSION['userFirstName'] = "";
		$_SESSION['userlastName'] = "";
		$_SESSION['userEmail'] = "";
		include('pages/login.php');
	} elseif (!empty($_POST['uName'])) { // Get user information asn set Session variables
		$uName = $_POST['uName'];
		$uPass = $_POST['uPass'];
	
		$query = 'SELECT userSalt FROM users WHERE userName="' . $uName . '"';
		$result = $con->query($query);
		$row = mysqli_fetch_assoc($result);
		$pwCheck =  hash("sha256", $uPass . $row['userSalt']);
		
		$query = 'SELECT * FROM users WHERE userName="' . $uName . '" AND userPass="'. $pwCheck .'"'; 
		//$query = 'SELECT * FROM users WHERE userName="' . $_POST['userName'] . '" AND userPassword="' . $_POST['userPassword'] . '"'; 
		$result = $con->query($query);
		
		if ($result) {
			$row = $result->fetch_array(MYSQLI_ASSOC);
			if (($row['userStatus'] == 1) && ($row['userExpireDate'] <= $today)) {
				$_SESSION['userID'] = $row['userID'];
				$_SESSION['clientID'] = $row['clientID'];
				$_SESSION['userAuth'] = $row['userAuth'];
				$_SESSION['userName'] = $row['userName'];
				$_SESSION['userFirstName'] = $row['userFirstName'];
				$_SESSION['userlastName'] = $row['userLastName'];
				$_SESSION['userEmail'] = $row['userEmail'];
				$result->free();
				$query = 'UPDATE users SET userLastLogin="' . $today . '" WHERE userID="' . $_SESSION['userID'] . '"'; 
				$result = $con->query($query);
				include('inc/pageContent.php');
			} else { // Invalid Username or Password
				$content .= $loginLink;
				$content .= '<h1>Invalid Username or Password</h1>';
			}
		} else { // Invalid Username or Password
			$content .= $loginLink;
			$content .= '<h1>Invalid Username or Password</h1>';
		}
	}
	elseif (!empty($_SESSION['userName'])) { 
		include('inc/pageContent.php');
	}
	else {// Start Session and Display Login Form
		include('pages/login.php');
	}

?>