<?php
	session_start();
	
	$UserName = $Password = "";
	$UserNameErr = $PasswordErr = "";
	$error = 0;
	
	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		if (empty($_POST["username"])) {
			$UserNameErr = "UserName is required";
			$error++;
		}
		else {
			$UserName = test_input($_POST["username"]);
			$UserName = filter_var($UserName, FILTER_SANITIZE_STRING);
			if (!preg_match ("/^[a-zA-Z0-9]*$/", $UserName)) {
				$UserNameErr = "UserName can only have letters and numbers";
				$error++;
			}
		}
		
		if (empty($_POST["password"])) {
			$PasswordErr = "Password is required";
			$error++;
		}
		else {
			$Password = test_input($_POST["password"]);
			$Password = filter_var($Password, FILTER_SANITIZE_STRING);
			if (!preg_match ("/^[a-zA-Z0-9]*$/", $Password)) {
				$PasswordErr = "Password can only have letters and numbers";
				$error++;
			}
		}
		
		if ($error == 0) {
			Login ($UserName, $Password);
		}
		
	}
	
	function test_input($data)
	{
		$data = trim($data);
		$data = stripslashes($data);
		$data = htmlspecialchars($data);
		return $data;
	}
	
	function ActivityLog($UserName)
	{
		$Status = "in";
		$IP = $_SERVER["REMOTE_ADDR"];
		
		$ServerName = "localhost";
		$ServerUserName = "root";
		$ServerPassword = "root";
		
		//Create Connection
		$conDataBase = new mysqli($ServerName, $ServerUserName, $ServerPassword);
		if ($conDataBase->connect_error) {
			die ("Connection Failed");
		}
		
		$sql = "INSERT INTO brentsweldingadmin.activitylog (username,status,ipaddress) VALUES('".$UserName."','".$Status."','".$IP."');";
		if ($conDataBase->query($sql) === TRUE) {
			$conDataBase->close();
			return;
		}
		else {
			$conDataBase->close();
			die("fatal error");
		}
	}
	
	function Login($UserName, $Password)
	{
		$ServerName = "localhost";
		$ServerUserName = "root";
		$ServerPassword = "root";
		$dbname = "brentsweldingadmin";
		
		//Create Connection
		$conDataBase = new mysqli($ServerName, $ServerUserName, $ServerPassword);
		if ($conDataBase->connect_error) {
			die ("Connection failed");
		}
		
		$user = mysqli_escape_string($conDataBase, $UserName);
		$pass = mysqli_escape_string($conDataBase, $Password);
		
		$sql = "select * from brentsweldingadmin.users where username='".$user."' and password='".$pass."';";
		$result = mysqli_query($conDataBase, $sql);
		$row = mysqli_fetch_array($result, MYSQL_ASSOC);
		$count = mysqli_num_rows($result);
		
		if ($count == 1) {
			$conDataBase->close();
			$_SESSION["adminusername"] = $UserName;
			session_write_close();
			ActivityLog($UserName);
			echo ("<script>window.location = 'AccountManager.php';</script>");
		}
		else {
			$conDataBase->close();
			echo ("<p>Wrong UserName or Password</p>");
		}
	}
?>