<?php

require_once("includes/config.php");
require_once("includes/global.php");

if (!empty($users['authed'])){
	if (!empty($_SESSION['destination'])){
		$page = $_SESSION['destination'];
		$_SESSION['destination'] = '';
	}
	else{
		$page = "index.php";
	}
	redirects($page);
}

$username = '';
$password = '';

$password = substr($password,0,16);

if(!empty($_POST['auth'])&&empty($_POST['reg'])&&empty($_POST['fusername'])){
	if(empty($_POST['username']) || empty($_POST['password'])){
		$errors['form-help'][] = 'Missing required fields';
		if(empty($_POST['username'])){
			$errors['form-help'][] = 'Username field required';
			$errors['username'] = 'Required';
		}
		else{
			$username = $_POST['username'];
		}
		if(empty($_POST['password'])){
			$errors['form-help'][] = 'Password field required';
			$errors['password'] = 'Required';
		}
		else{
			$password = $_POST['password'];
		}
	}
	else{
		$username = $_POST['username'];
		$password = $_POST['password'];
		if (!doLogin($username,$password)) {
			$errors['form-help'][] = 'Could not log in using the credentials provided';
			$errors['username'] = 'Invalid';
			$errors['password'] = 'Invalid';
		}
		else{
			authenticate($username);
			$_SESSION['runaway'] = true;
			$_SESSION['runaway_Username'] = $username;
			if(!empty($_SESSION['destination'])){
				$page = $_SESSION['destination'];
			}
			else{
				$page = "index.php";
			}
			redirects("$page");
			$_SESSION['destination'] = '';
		}
	}
}

require_once("theme/login/home.php");