<?php
class Router {
    private $routes = [];
    private $notFoundCallback;

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

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

    public function notFound($callback) {
        $this->notFoundCallback = $callback;
    }

    public function resolve() {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        
        // Remove trailing slash if not root
        if ($path !== '/' && substr($path, -1) === '/') {
            $path = rtrim($path, '/');
            header('Location: ' . $path);
            exit;
        }

        // Check for exact match
        if (isset($this->routes[$method][$path])) {
            call_user_func($this->routes[$method][$path]);
            return;
        }
        
        // Check for routes with parameters
        foreach ($this->routes[$method] as $route => $callback) {
            if (strpos($route, ':') !== false) {
                $routeRegex = preg_replace('/:[^\/]+/', '([^\/]+)', $route);
                $routeRegex = '#^' . $routeRegex . '$#';
                
                if (preg_match($routeRegex, $path, $matches)) {
                    array_shift($matches); // Remove the full match
                    call_user_func_array($callback, $matches);
                    return;
                }
            }
        }
        
        // No route found
        if ($this->notFoundCallback) {
            call_user_func($this->notFoundCallback);
        } else {
            header("HTTP/1.0 404 Not Found");
            echo "404 Page Not Found";
        }
    }
}
