<?php

namespace lib\core;

class parser
{
	private $qString, $controller, $method, $argument;
	public function __construct()
	{
		$appname = $GLOBALS['CONFIG']['APP_NAME'];
		$url = str_replace("?", "", $_SERVER['REQUEST_URI']);
		//$cleanPath = filter_var($url, FILTER_SANITIZE_URL);

		// Validasi hanya karakter: huruf, angka, garis miring, strip, titik
		/* if (!preg_match('/^\/[a-zA-Z0-9\/\-\.\_]*$/', $cleanPath)) {
			http_response_code(400);
			exit('Bad Request');
		} */

		if ($appname)
			$request  = str_replace($appname . "/", "", $url);
		else {
			$request  = substr($url, 1);
		}

		$this->qString = explode("/", str_replace("%20", " ", $request));

		$this->controller = current($this->qString);
		$this->method = next($this->qString);
		$this->argument = implode("/", array_slice($this->qString, 2));		
	}

	public function execute()
	{
		require_once $GLOBALS['CONFIG']['LIB'] . "/core/api.php";
		require_once $GLOBALS['CONFIG']['LIB'] . "/core/controller.php";
		if (!empty($this->controller)) {
			
			if (is_file($GLOBALS['CONFIG']['APP'] . "/" . $this->controller . ".php")) {
				require_once $GLOBALS['CONFIG']['APP'] . "/" . $this->controller . ".php";
			}
			if (class_exists($this->controller)) {
				new $this->controller($this->argument, $this->method);
			} else {

				global $ROUTER;
				$class = ''; //count($ROUTER[$this->controller])? $ROUTER[$this->controller]:['/']; 				 
				$param = explode("/", $class);
				if (count($param) > 1) {
					$arg = implode("/", array_slice($param, 2));
					$arg .= $this->argument;
					if (is_file($GLOBALS['CONFIG']['APP'] . "/" . $param[0] . ".php"))
						require_once $GLOBALS['CONFIG']['APP'] . "/" . $param[0] . ".php";
					$mod = new $param[0]($arg, $param[1]);
				} else {
					if (is_file($GLOBALS['CONFIG']['APP'] . "/" . $class . ".php")) {
						include_once $GLOBALS['CONFIG']['APP'] . "/" . $class . ".php";
						new $class($this->argument, $this->method);
					} else header('HTTP/1.0 400 BAD ERROR');
				}
				//echo "error";
			}
		} else {
			require_once $GLOBALS['CONFIG']['APP'] . "/App.php";
			new \App($this->argument, $this->method);
		}
	}
}
