<?php

class Router
{
    private $routes = [];
    
    public function get($path, $action)
    {
        $this->addRoute('GET', $path, $action);
    }
    
    public function post($path, $action)
    {
        $this->addRoute('POST', $path, $action);
    }
    
    private function addRoute($method, $path, $action)
    {
        $this->routes[] = [
            'method' => $method,
            'path' => $path,
            'action' => $action
        ];
    }
    
    public function dispatch($uri, $method)
    {
        // Remove query string and base path
        $uri = parse_url($uri, PHP_URL_PATH);
        
        // Handle both /samanta_crm/ and /samanta_crm/public/ paths
        $uri = str_replace('/samanta_crm/public', '', $uri);
        $uri = str_replace('/samanta_crm', '', $uri);
        
        if ($uri === '' || $uri === '/') $uri = '/';
        
        foreach ($this->routes as $route) {
            if ($route['method'] !== $method) continue;
            
            // Convert route path to regex
            $pattern = preg_replace('/\{[^}]+\}/', '([^/]+)', $route['path']);
            $pattern = '#^' . $pattern . '$#';
            
            if (preg_match($pattern, $uri, $matches)) {
                array_shift($matches); // Remove full match
                $this->executeAction($route['action'], $matches);
                return;
            }
        }
        
        // 404 Not Found
        http_response_code(404);
        echo "404 - Page Not Found";
    }
    
    private function executeAction($action, $params = [])
    {
        if (is_string($action)) {
            list($controller, $method) = explode('@', $action);
            
            $controllerFile = "../app/Controllers/{$controller}.php";
            if (file_exists($controllerFile)) {
                require_once $controllerFile;
                $controllerInstance = new $controller();
                call_user_func_array([$controllerInstance, $method], $params);
            } else {
                echo "Controller not found: {$controller}";
            }
        }
    }
}
