<?php
/**
 * BlogPostAI Router
 * Simple routing system for API endpoints
 */

class Router {
    private $routes = [];
    private $middlewares = [];

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

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

    public function put($path, $handler) {
        $this->addRoute('PUT', $path, $handler);
    }

    public function delete($path, $handler) {
        $this->addRoute('DELETE', $path, $handler);
    }

    private function addRoute($method, $path, $handler) {
        $this->routes[] = [
            'method' => $method,
            'path' => $path,
            'handler' => $handler
        ];
    }

    public function middleware($middleware) {
        $this->middlewares[] = $middleware;
    }

    public function run() {
        $requestMethod = $_SERVER['REQUEST_METHOD'];
        $requestUri = $_SERVER['REQUEST_URI'];

        // Remove query string
        if (($pos = strpos($requestUri, '?')) !== false) {
            $requestUri = substr($requestUri, 0, $pos);
        }

        // Remove trailing slash except for root
        $requestUri = rtrim($requestUri, '/');
        if ($requestUri === '') {
            $requestUri = '/';
        }

        // Run middlewares
        foreach ($this->middlewares as $middleware) {
            $result = call_user_func($middleware);
            if ($result === false) {
                return;
            }
        }

        // Find matching route
        foreach ($this->routes as $route) {
            if ($route['method'] !== $requestMethod) {
                continue;
            }

            $pattern = $this->pathToPattern($route['path']);

            if (preg_match($pattern, $requestUri, $matches)) {
                array_shift($matches); // Remove full match
                call_user_func_array($route['handler'], $matches);
                return;
            }
        }

        // No route found
        Response::error('Endpoint not found', 404);
    }

    private function pathToPattern($path) {
        // Convert path parameters like {id} to regex
        $pattern = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '([^/]+)', $path);
        return '#^' . $pattern . '$#';
    }
}

// Get request body for PUT/POST/DELETE
function getRequestBody() {
    $body = file_get_contents('php://input');
    if (!empty($body)) {
        $decoded = json_decode($body, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return $decoded;
        }
    }
    return [];
}

// Get query parameters
function getQueryParams() {
    return $_GET;
}

// Get request header
function getHeader($name) {
    $name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
    return $_SERVER[$name] ?? null;
}
