<?php #lib/99_manager.php

// Missing:
// - Error handling
// - Proper response codes

class Manager
{
  private static $routes = [
  	//"Termine",
  	//"Dienstpläne",
  	"Personal",
  	//"Prozesse",
  	//"Spinde",
  	//"Einsätze",
  	//"Anwesenheiten",
  	//"Fahrzeuge"
  ];
  private function __construct() {}
  private function __destruct() {}
  
  public static function Answer() {
  	try {
	  	Request::ParseInput();
	    Login::Login();
	    
	  	if (Request::IsLogout()) {
	  		// Logout detected
	  		Login::Logout();
	  		Response::Get()->Code(200)->Message("Logout erkannt!");
	  	} else if (!Login::LoggedIn()) {
	  		// Login is necessary
		  	Response::Get()->Code(401);
	  	} else {
	  		
	  		// Include routes. Needed also for /-Request
	  		foreach (self::$routes as $route) {
					$file = "routes/".str_replace(["ä", "ö", "ü", "ß"], ["ae", "oe", "ue", "ss"], $route).".php";
					if (file_exists($file)) {
						include $file;
				} }
	  		
	  		if (Request::IsRoot()) {
	  			// POST (Login) or GET/OPTIONS... i dont care, all will result in the same
	  			$access = [];
	  			foreach (self::$routes as $route) {
	  				$class = "\\Routes\\".$route;
	  				$access[$route] = $class::Rights();
	  			}
	  			Response::Get()->Code(200)->Content($access)->ETag(hash('sha256', json_encode($access)));
	  		} else if (!in_array(Request::Route(), self::$routes)) {
	  			Response::Get()->Code(404)->Message("Route not found");
	  		} else {
	  			// This is the good path. We can try to answer the request
	  			$class = "\\Routes\\".Request::Route();
	      	(new $class)->Answer();
	    	} }
  	} catch (\Throwable $e) { // For PHP 7
  		Response::Get()->Code(500)->Message("<h5>Caught throwable:</h5>".$e);
		} catch (\Exception $e) { // For PHP 5
  		Response::Get()->Code(500)->Message("<h5>Caught exception:</h5>".$e);
} } }
