<?php

class Router
{
    public static function dispatch(): void
    {
        $page = $_GET['page'] ?? 'home';
        $action = $_GET['action'] ?? 'index';

        $controllerMap = [
            'home' => 'HomeController',
            'productos' => 'ProductosController',
            'galeria' => 'GaleriaController',
            'contacto' => 'ContactoController',
            'login' => 'LoginController',
            'registro' => 'RegistroController',
            'pedidos' => 'PedidosController',
            'auth' => 'AuthController'
        ];

        $controllerName = $controllerMap[$page] ?? 'HomeController';
        $controllerFile = APP_ROOT . '/app/controllers/' . $controllerName . '.php';

        if (!file_exists($controllerFile)) {
            http_response_code(404);
            echo 'Controlador no encontrado';
            return;
        }

        require_once $controllerFile;
        $controller = new $controllerName();

        if (method_exists($controller, $action)) {
            $controller->$action();
            return;
        }

        if (method_exists($controller, 'index')) {
            $controller->index();
            return;
        }

        http_response_code(404);
        echo 'Método no encontrado';
    }
}
