<?php
    class Request {
        protected $controllerName;
        protected $uriParameters;
        protected static $singleton = NULL;

        public function __construct() {
            $this->jsonReceived = null;
            $this->initBaseURI();
            $this->initControllerAndParametersFromURI();
        }

        public static function getCurrentRequest() {
            if (is_null(static::$singleton))
                static::$singleton = new static();
                
            return static::$singleton;
        }

        public function jsonContent() {
            if(is_null($this->jsonReceived))
               $this->jsonReceived = json_decode(file_get_contents("php://input"));

            return $this->jsonReceived;
         }

        protected function initBaseURI() {
            $this->baseURI = explode('/api.php', $_SERVER['SCRIPT_NAME'])[0];
        }

        protected function initControllerAndParametersFromURI(){
            $url = trim($_SERVER['PATH_INFO'], '/');
            $urlSegments = explode('/', $url);

            $scheme = ['controller', 'params'];
            $route = [];

            foreach ($urlSegments as $index => $segment){
                if ($scheme[$index] == 'params'){
                    $route['params'] = array_slice($urlSegments, $index);
                    break;
                } else {
                    $route[$scheme[$index]] = $segment;
                }
            }

            $this->controllerName = $route['controller'] != "" ? $route['controller'] : "default";
            $this->uriParameters = isset($route['params']) ? $route['params'] : [];
        }

        // ==============
        // Public API
        // ==============
        public function getControllerName() {
            return $this->controllerName;
        }

        public function getHttpMethod() {
            return $_SERVER["REQUEST_METHOD"];
        }

        public function getUriParameters() {
            return $this->uriParameters;
        }

        public function getJwtToken() {
            $headers = getallheaders();
            $autorization = $headers['Authorization'];
            $arr = explode(" ", $autorization);
        
            if (count($arr) < 2)
                throw new Exception("Missing JWT token");
        
            $jwt_token = $arr[1];
        
            return $jwt_token;
        }
    }
?>