<?php

namespace App\Core;

class Router
{
    private $routes = [];

    public function get($uri, $action)
    {
        $this->addRoute('GET', $uri, $action);
    }

    public function post($uri, $action)
    {
        $this->addRoute('POST', $uri, $action);
    }

    private function addRoute($method, $uri, $action)
    {
        // Converte {param} para regex
        $uriPattern = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '([^/]+)', $uri);
        $this->routes[] = [
            'method' => $method,
            'pattern' => '#^' . $uriPattern . '$#',
            'action' => $action
        ];
    }

    public function dispatch($uri, $method)
    {
        // Remove query string e ajusta base path se necessario
        $uri = parse_url($uri, PHP_URL_PATH);
        // Remove trailing slash
        $uri = rtrim($uri, '/');
        if ($uri === '') $uri = '/';

        // Tenta remover o path do projeto se estiver rodando em subpasta
        // Ajuste manual: assumindo rodar na raiz do vhost ou /osiricascudo.com.br
        // Se usar vhost osiricascudo.local, o URI vem limpo.
        
        foreach ($this->routes as $route) {
            if ($route['method'] === $method && preg_match($route['pattern'], $uri, $matches)) {
                array_shift($matches); // remove full match
                
                $action = $route['action'];
                if (is_array($action)) {
                    $controllerName = $action[0];
                    $methodName = $action[1];
                    $controller = new $controllerName();
                    return call_user_func_array([$controller, $methodName], $matches);
                }
            }
        }

        http_response_code(404);
        echo "404 - Página não encontrada";
    }
}
