<?php
/**
 * (c) 2023 iCrewTracker. All rights reserved.
 * 
 * This file is part of the iCrewTracker software suite.
 * Unauthorized copying, modification, distribution, or use of this file, 
 * via any medium, is strictly prohibited. This file is proprietary and confidential.
 * For license information, please see the LICENSE.md file.
 *
 * @author ICREWSYSTEMS SOFTWARE ENGINEERING LLP
 * @contact legal(at)icrewsystems.com 
 * @license UID cbb8060f-5d4c-45aa-8850-f4b8a87d0bcc
 * @package-bundle-hash:fe8Hghmq7t7GsZsW7KzHuTe/38L9upjcIflUqo8C5qr9iv/PeQNS
 */

namespace iCrewTracker\Base;

use Exception;

class Router {
    private $routes = [
        'GET' => [],
        'POST' => []
    ];

    public function get($path, $controller) {
        $this->routes['GET'][$path] = $controller;
    }

    public function post($path, $controller) {
        $this->routes['POST'][$path] = $controller;
    }

   
    public function dispatch($method, $uri) {
    	
    	 $uri = str_replace('/index.php', '', $uri);
    	
        foreach ($this->routes[$method] as $route => $controllerAction) {
            // Convert route to a regular expression
            if (preg_match($this->convertRouteToRegex($route), $uri, $matches)) {
                list($controller, $method) = explode('@', $controllerAction);

                // We remove the first match, which is the entire URL.
                array_shift($matches);

                // Instantiate the controller and call the method with route parameters
                $controllerInstance = new $controller;


                call_user_func_array([$controllerInstance, $method], $matches);

                // try {
                    
                // } catch (Exception $e) {
                //     return "Whoops! Something went wrong. {$e->getMessage()}";
                // }
                

                return;
            }
        }

        // If no routes match, 404 handling here

        $this->notFound($method, $uri);

    }

    private function convertRouteToRegex($route) {
        $route = preg_replace('/\//', '\/', $route);
        $route = preg_replace('/\{[a-z]+\}/', '([^/]+)', $route);
        return "/^" . $route . "$/i";
    }

    private function notFound($method, $uri) {
        // http_response_code(404);
        echo "Error 404. Unable to {$method} - \"{$uri}\". Perhaps check if it is declared?";
    }
}
