<?php

namespace App\Core;

/**
 * Simple Router - للـ MVC Pattern
 * Routing system أساسي
 */
class Router
{
    private array $routes = [];
    private array $middlewares = [];

    /**
     * إضافة route
     */
    public function add(string $method, string $path, $handler, array $middlewares = []): void
    {
        $this->routes[] = [
            'method' => strtoupper($method),
            'path' => $path,
            'handler' => $handler,
            'middlewares' => $middlewares
        ];
    }

    /**
     * GET route
     */
    public function get(string $path, $handler, array $middlewares = []): void
    {
        $this->add('GET', $path, $handler, $middlewares);
    }

    /**
     * POST route
     */
    public function post(string $path, $handler, array $middlewares = []): void
    {
        $this->add('POST', $path, $handler, $middlewares);
    }

    /**
     * PUT route
     */
    public function put(string $path, $handler, array $middlewares = []): void
    {
        $this->add('PUT', $path, $handler, $middlewares);
    }

    /**
     * DELETE route
     */
    public function delete(string $path, $handler, array $middlewares = []): void
    {
        $this->add('DELETE', $path, $handler, $middlewares);
    }

    /**
     * Dispatch request
     */
    public function dispatch(string $method, string $path): void
    {
        $method = strtoupper($method);
        
        foreach ($this->routes as $route) {
            if ($route['method'] === $method && $this->matchPath($route['path'], $path, $params)) {
                // تنفيذ middlewares
                foreach ($route['middlewares'] as $middleware) {
                    if (is_callable($middleware)) {
                        $result = $middleware();
                        if ($result === false) {
                            return;
                        }
                    }
                }
                
                // تنفيذ handler
                if (is_callable($route['handler'])) {
                    call_user_func($route['handler'], $params);
                } elseif (is_string($route['handler'])) {
                    // Controller@method format
                    $this->callController($route['handler'], $params);
                }
                
                return;
            }
        }
        
        // 404 Not Found
        http_response_code(404);
        echo json_encode(['error' => 'Route not found']);
    }

    /**
     * Match path مع parameters
     */
    private function matchPath(string $routePath, string $requestPath, array &$params): bool
    {
        $params = [];
        
        // Convert route path to regex
        $pattern = preg_replace('/\{(\w+)\}/', '([^/]+)', $routePath);
        $pattern = '#^' . $pattern . '$#';
        
        if (preg_match($pattern, $requestPath, $matches)) {
            array_shift($matches);
            
            // Extract parameter names
            preg_match_all('/\{(\w+)\}/', $routePath, $paramNames);
            
            foreach ($paramNames[1] as $index => $name) {
                $params[$name] = $matches[$index] ?? null;
            }
            
            return true;
        }
        
        return false;
    }

    /**
     * Call controller method
     */
    private function callController(string $handler, array $params): void
    {
        if (strpos($handler, '@') === false) {
            return;
        }
        
        list($controller, $method) = explode('@', $handler);
        $controllerClass = "App\\Controllers\\{$controller}";
        
        if (class_exists($controllerClass)) {
            $controllerInstance = new $controllerClass();
            if (method_exists($controllerInstance, $method)) {
                call_user_func_array([$controllerInstance, $method], $params);
            }
        }
    }
}
