<?php
	require("settings.php");
	require_once("helper.php");

	session_start();
	html_start("Webtasks");

	echo "<H1>Webtasks</H1>\n";

	$link = db_connect();

	$auth = false;
	if(session_is_registered("id") && ($_SESSION["id"] != "")) {
		$auth = true;
	} else if (isset($_REQUEST["user"]) && isset($_REQUEST["pass"])) {
		$user = mysql_real_escape_string(htmlspecialchars($_REQUEST["user"]), $link);
		$pass = md5($_REQUEST["pass"]);

		$query = "
			SELECT u.id FROM users u, capabilities c
			WHERE u.id = c.id AND u.user = \"$user\" AND u.pass = \"$pass\" AND c.capability = \"login\"";
		$result = mysql_query($query, $link)
		or die("Query failed in file". __FILE__ ." line ". __LINE__ ." with: ". mysql_error($link));
		$num = mysql_num_rows($result);

		$result = mysql_fetch_array($result);
		$_SESSION["id"] = $result["id"];
		$_SESSION["user"] = htmlentities($_REQUEST["user"]);

		if($num == 1) {
			$auth = true;
		} else {
			echo "Login failed!<BR><BR>\n";
		}
	}

	if(!$auth) {
		login_form("index.php");
		echo "<A href=\"register.php\">Register</A>\n";
		die();
	}


	echo "<H3>Tasks</H3>\n";

	$query = "SELECT tid, title FROM tasks ORDER BY tid";
	$result = mysql_query($query, $link) or die("Can't fetch tasks: ".mysql_error($link));
	if(check_capa($_SESSION["id"], "taskedit", $link)) {
		echo "<UL class=\"task\">\n";
	} else {
		echo "<UL class=\"assignment\">\n";
	}
	while($task = mysql_fetch_array($result)) {
		echo "<LI><A href=\"assignment.php?tid={$task["tid"]}\">{$task["title"]}</A></LI>\n";
	}
	echo "</UL>\n";

	if(check_capa($_SESSION["id"], "taskedit", $link)) {
		echo "<A href=\"tasks.php\"><IMG src=\"icons/report.png\" alt=\"task\">Task Managment</A><BR>\n";
	}

	echo "<H3>Managment</H3>\n";

	echo "<A href=\"profil.php\"><IMG src=\"icons/vcard_edit.png\" alt=\"edit\">Edit own profile</A><BR>\n";

	if(check_capa($_SESSION["id"], "useredit", $link)) {
		echo "<A href=\"users.php\"><IMG src=\"icons/user.png\" alt=\"user\">User managment</A><BR>\n";
	}
	mysql_close($link);

	echo "<DIV class=\"footer\">\n";
	echo "<A href=\"logout.php\"><IMG src=\"icons/door_in.png\" alt=\"logout\">Logout</A>\n";
	echo "</DIV>\n";
?>
 </BODY>
</HTML>
