<?php
/**
 * MediFlash SOS+ Router
 * Simple routing system for the application
 */

class Router {
    private $routes = [];
    private $currentRoute = null;
    
    public function __construct() {
        $this->currentRoute = $this->getCurrentRoute();
    }
    
    /**
     * Add a GET route
     */
    public function get($path, $callback) {
        $this->addRoute('GET', $path, $callback);
        return $this;
    }
    
    /**
     * Add a POST route  
     */
    public function post($path, $callback) {
        $this->addRoute('POST', $path, $callback);
        return $this;
    }
    
    /**
     * Add a PUT route
     */
    public function put($path, $callback) {
        $this->addRoute('PUT', $path, $callback);
        return $this;
    }
    
    /**
     * Add a DELETE route
     */
    public function delete($path, $callback) {
        $this->addRoute('DELETE', $path, $callback);
        return $this;
    }
    
    /**
     * Add route for any HTTP method
     */
    private function addRoute($method, $path, $callback) {
        $pattern = $this->convertPathToPattern($path);
        $this->routes[] = [
            'method' => $method,
            'path' => $path,
            'pattern' => $pattern,
            'callback' => $callback
        ];
    }
    
    /**
     * Convert path with parameters to regex pattern
     */
    private function convertPathToPattern($path) {
        // Convert :param to named capture groups
        $pattern = preg_replace('/\:([a-zA-Z0-9_]+)/', '(?P<$1>[^/]+)', $path);
        // Add start and end anchors
        return '#^' . $pattern . '$#';
    }
    
    /**
     * Get current route from request
     */
    private function getCurrentRoute() {
        $method = $_SERVER['REQUEST_METHOD'];
        $uri = $_SERVER['REQUEST_URI'];
        
        // Remove query string
        if (false !== $pos = strpos($uri, '?')) {
            $uri = substr($uri, 0, $pos);
        }
        
        // Remove trailing slash (except for root)
        $uri = '/' . trim($uri, '/');
        if ($uri !== '/') {
            $uri = rtrim($uri, '/');
        }
        
        return [
            'method' => $method,
            'uri' => $uri
        ];
    }
    
    /**
     * Handle the current request
     */
    public function handleRequest() {
        $matched = false;
        
        foreach ($this->routes as $route) {
            if ($route['method'] !== $this->currentRoute['method']) {
                continue;
            }
            
            if (preg_match($route['pattern'], $this->currentRoute['uri'], $matches)) {
                $matched = true;
                
                // Extract named parameters
                $params = [];
                foreach ($matches as $key => $value) {
                    if (is_string($key)) {
                        $params[$key] = $value;
                    }
                }
                
                // Execute callback
                $this->executeCallback($route['callback'], $params);
                break;
            }
        }
        
        if (!$matched) {
            $this->handleNotFound();
        }
    }
    
    /**
     * Execute route callback
     */
    private function executeCallback($callback, $params = []) {
        if (is_callable($callback)) {
            // Direct function callback
            call_user_func_array($callback, [$params]);
        } elseif (is_string($callback) && strpos($callback, '@') !== false) {
            // Controller@method format
            list($controller, $method) = explode('@', $callback);
            
            $controllerClass = 'Controllers\\' . $controller;
            if (class_exists($controllerClass)) {
                $instance = new $controllerClass();
                if (method_exists($instance, $method)) {
                    call_user_func_array([$instance, $method], [$params]);
                } else {
                    throw new Exception("Method {$method} not found in {$controllerClass}");
                }
            } else {
                throw new Exception("Controller {$controllerClass} not found");
            }
        } else {
            throw new Exception("Invalid callback format");
        }
    }
    
    /**
     * Handle 404 Not Found
     */
    private function handleNotFound() {
        http_response_code(404);
        
        if (strpos($this->currentRoute['uri'], '/api/') !== false) {
            // API 404
            header('Content-Type: application/json');
            echo json_encode([
                'error' => 'Not Found',
                'message' => 'L\'endpoint demandé n\'existe pas'
            ]);
        } else {
            // Web 404
            echo "<!DOCTYPE html>
            <html lang='fr'>
            <head>
                <meta charset='UTF-8'>
                <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                <title>Page non trouvée - " . APP_NAME . "</title>
                <style>
                    body { 
                        font-family: 'Inter', sans-serif; 
                        text-align: center; 
                        padding: 50px; 
                        background: hsl(210, 40%, 96%);
                        color: hsl(210, 40%, 8%);
                    }
                    .container {
                        max-width: 600px;
                        margin: 0 auto;
                        background: white;
                        padding: 40px;
                        border-radius: 12px;
                        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                    }
                    .error-code { 
                        font-size: 72px; 
                        font-weight: bold; 
                        color: hsl(213, 94%, 68%); 
                        margin: 0;
                    }
                    .error-message { 
                        font-size: 24px; 
                        margin: 20px 0; 
                        color: hsl(210, 40%, 8%);
                    }
                    .back-link { 
                        display: inline-block;
                        background: hsl(213, 94%, 68%);
                        color: white;
                        padding: 12px 24px;
                        text-decoration: none; 
                        border-radius: 8px;
                        font-weight: 600;
                        margin-top: 20px;
                    }
                    .back-link:hover {
                        background: hsl(213, 94%, 58%);
                    }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='error-code'>404</div>
                    <div class='error-message'>Page non trouvée</div>
                    <p>La page que vous recherchez n'existe pas ou a été déplacée.</p>
                    <a href='/' class='back-link'>← Retour à l'accueil</a>
                </div>
            </body>
            </html>";
        }
    }
    
    /**
     * Redirect to a URL
     */
    public static function redirect($url, $code = 302) {
        header("Location: {$url}", true, $code);
        exit();
    }
    
    /**
     * Get current request method
     */
    public static function getMethod() {
        return $_SERVER['REQUEST_METHOD'];
    }
    
    /**
     * Get current request URI
     */
    public static function getUri() {
        $uri = $_SERVER['REQUEST_URI'];
        if (false !== $pos = strpos($uri, '?')) {
            $uri = substr($uri, 0, $pos);
        }
        return $uri;
    }
}
?>
