<?php

namespace App\Core;

class Router
{
    private $routes = [];

    public function __construct(array $routes)
    {
        $this->routes = $routes;
    }

    public function dispatch($uri, $method)
    {
        $routeKey = "$method $uri";

        // Exact match first
        if (isset($this->routes[$routeKey])) {
            return $this->executeRoute($this->routes[$routeKey]);
        }

        // Try parameterized routes (for form IDs, lead IDs, etc.)
        foreach ($this->routes as $pattern => $handler) {
            if ($this->matchRoute($pattern, $routeKey)) {
                return $this->executeRoute($handler);
            }
        }

        // 404 Not Found
        http_response_code(404);
        echo "Page not found";
        return false;
    }

    private function matchRoute($pattern, $routeKey)
    {
        // Convert route pattern to regex
        $regex = preg_replace('/\{[^}]+\}/', '[^/]+', $pattern);
        $regex = str_replace('/', '\/', $regex);

        return preg_match("/^$regex$/", $routeKey);
    }

    private function executeRoute($handler)
    {
        if (is_array($handler) && count($handler) === 2) {
            $controllerClass = $handler[0];
            $method = $handler[1];

            if (class_exists($controllerClass) && method_exists($controllerClass, $method)) {
                $controller = new $controllerClass();
                return $controller->$method();
            }
        }

        http_response_code(500);
        echo "Invalid route handler";
        return false;
    }
}
