<?php
namespace App\Core;

class Router {
    protected $routes = [];
    protected $baseUrl = '';

    public function __construct() {
        $scriptName = $_SERVER['SCRIPT_NAME'];
        $this->baseUrl = str_replace('/public/index.php', '', $scriptName);
        if ($this->baseUrl === '/') {
            $this->baseUrl = '';
        }
        define('BASE_URL', $this->baseUrl);
    }

    public function getBaseUrl() {
        return $this->baseUrl;
    }

    public function add(array $methods, $path, $handler) {
        $this->routes[] = [
            'methods' => $methods,
            'path' => $path,
            'handler' => $handler
        ];
    }

    public function dispatch() {
        $requestUri = $_SERVER['REQUEST_URI'];
        $path = str_replace($this->baseUrl, '', $requestUri);
        $path = parse_url($path, PHP_URL_PATH);
        
        $method = $_SERVER['REQUEST_METHOD'];

        foreach ($this->routes as $route) {
            if (!in_array($method, $route['methods'])) {
                continue;
            }

            $pattern = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<$1>[^/]+)', $route['path']);
            $pattern = '#^' . $pattern . '$#';

            if (preg_match($pattern, $path, $matches)) {
                $params = [];
                foreach ($matches as $key => $value) {
                    if (is_string($key)) {
                        $params[$key] = urldecode($value);
                    }
                }

                return $this->executeHandler($route['handler'], $params);
            }
        }

        // Fallback: Dynamic URL routing (DB Slugs for categories/articles/compatibility)
        $slug = trim($path, '/');
        if ($slug !== '') {
            return $this->executeHandler('ClientController@resolveSlug', ['slug' => $slug, 'fullPath' => $path]);
        }

        $this->send404();
    }

    protected function executeHandler($handler, $params = []) {
        list($controllerName, $action) = explode('@', $handler);
        $fullControllerName = '\\App\\Controllers\\' . $controllerName;
        
        if (class_exists($fullControllerName)) {
            $controller = new $fullControllerName();
            return call_user_func_array([$controller, $action], $params);
        }

        $this->send404();
    }

    public function send404() {
        http_response_code(404);
        $controller = new \App\Controllers\ClientController();
        $controller->notFound();
        exit;
    }
}
