<?php
	// @TODO Comments
	$mysql = new \sven\sys\mysql\mysql();
	$session = new \sven\sys\security\session;
	$fluent = $mysql->getBuilder();
	if(get_class($fluent) === "sven\sys\sven\uncallable") { \sven\sys\core::addException(new \sven\sys\Exception("\sven\sys\sven\uncallable", "Can't find/use FluentPDO"));}

	$body = \sven\sys\sven\web::getRequestBody();
	$array = (object) [];

	if(!$auth->loggedIn()) {
		$user = (isset($body->user)) ? $body->user : (isset($_GET['user']) ? $_GET['user'] : null);
		$pass = (isset($body->pass)) ? $body->pass : (isset($_GET['pass']) ? $_GET['pass'] : null);
		$csrf = (isset($body->csrf)) ? $body->csrf : (isset($_GET['csrf']) ? $_GET['csrf'] : null);
		if($user && $pass && $csrf) {
			$query = $fluent->from('t_benutzer')->select('t_benutzer.*')->where("Name = ?", $user);
			$data = $query->fetch();

			// verify user exists and password is right
			if($data && $auth->verifyPassword($pass, $data->Passwort)) {
				if($auth->validateCSRF("login", $csrf)) {
					$array = (object) [
						"token" => $auth->login($user),
						"msg" => "User logged in.",
						"state" => "successed"
					];
				} else {
					// CSRF wrong
					$array = (object) [
						"msg" => "CSRF Code wrong.",
						"error" => ["AUTHENTICATION_FAILED"]
					];
				}
			} else {
				// Username not found or password wrong
				$array = (object) [
					"msg" => "Username or password wrong.",
					"error" => ["AUTHENTICATION_FAILED"]
				];
			}
		} else {
			// BAD_REQUEST
			$array = (object) [
				"session" => $session->read("csrf_form_login"),
				"body" => $body,
				"msg" => "Could process request. Missing data?",
				"error" => ["BAD_REQUEST"]
			];
		}
	} else {
		$auth->logout();
		// USER LOGGED IN; LOGOUT
		$array = (object) [
			"msg" => "User logged out.",
			"error" => ["AUTHENTICATION_FAILED"]
		];
	}
	\sven\sys\core::replaceApiOutput($array);

?>
