<?

	// Start session
	session_start();

	// Includes
	include_once('config.inc.php');
	include_once('database.inc.php');
	include_once('render.inc.php');


	// Init
	$action = $_GET['action'];
	$username = $_GET['username'];
	$password = $_GET['password'];
	$result = $_GET['result'];
	
	// Redirect if not logged in
	if (!$_SESSION['username'] && $action != 'login') {
		header('location:'.$scriptName.'?action=login');
		exit;
	}

	// Show login page or process login
	if (!$_SESSION['username'] && $action == 'login') {
	
		if (!$username) {
			$content = '<h1>Login</h1>
						<form action="'.$scriptName.'" method="GET">
						<input type="hidden" name="action" value="login">
						<input type="text" name="username"><br />
						<input type="password" name="password"><br />
						<input type="submit">
						</form>';
			if ($result == 'failure') 
				$content = '<p style="color: #f00; font-weight: bold;">Login attempt failed</p>'.$content;
		} else {
			
			// Get password from database
			$sql = 'SELECT * from users where UserID = \''.$username.'\';';
			$rs = mysql_query($sql, $dbh);
			$result = mysql_fetch_object($rs);
			
			// If password matches --> login and redirect
			if ($result->Password === $password) {
				$_SESSION['username'] = $username;
				$_SESSION['language'] = $result->Language;
				$_SESSION['admin'] = $result->IsAdmin;
				$_SESSION['updateAll'] = $result->UpdateAll;
				header('location:'.$scriptName);				
			} else {
				header('location:'.$scriptName.'?action=login&result=failure');								
			}
		
		}
	}
	
	if ($_SESSION['username']) {
	
		if ($action == 'logout') {
			unset($_SESSION['username']);
			header('location:'.$scriptName.'?action=login');
		} else {
			$content = printMenu();
		}
	
	}

	
	// Do the output	
	renderContent($content);
	
	function printMenu() {
		
		global $config;
		
		$output = '<h1>Main Menu</h1>
				   <fieldset>
				   <legend>Keywords</legend>
				   <ol>
				   	<li><a href="'.$config['list'].'">List/edit/translate keywords</a></li>
				   	<li><a href="'.$config['add'].'">Add keyword</a></li>
				   	<li><a href="'.$config['export'].'">Export repertory</a></li>
				   </ol>
				   </fieldset><br />
				   <fieldset>
				   <legend>Essences</legend>
				   <ol>
					 	<li><a href="'.$config['list_essences'].'">List/edit/translate essences</a></li>
				   </ol>
					 </fieldset>';
		
		return $output;
		
	}
?>