<?php
require_once 'Autoloader.php';
Autoloader::init();

require_once __DIR__ . "/../../engine/app/view/View.php";

class Router
{

    private $routes;

    public function __construct()
    {

        $routesPath = __DIR__ . '/../routes.php';

        $this->routes = include($routesPath);
    }

    public function run()
    {
        $uri = $this->getURI();
        $controllerName = "";
        foreach ($this->routes as $uriPattern => $path) {
            if (preg_match("~$uriPattern~", $uri)) {
                $segments = explode('/', $path);
                $controllerName = array_shift($segments) . 'Controller';
                $controllerName = ucfirst($controllerName);
                $actionName = 'action' . ucfirst(array_shift($segments));
                $controllerObject = new $controllerName();
                $result = $controllerObject->$actionName();
                break;
                // var_dump($controllerFile);
            }

            if (!$controllerName) {
                // Page not found
                $obj = new MainController();
                $obj->actionNotFound();
                // break;
            }

        }
    }

    private function getURI()
    {
        if (!empty($_SERVER['REQUEST_URI'])) {
            return trim($_SERVER['REQUEST_URI'], '/');
        }
    }
}
