<?php
// app/Helpers/Router.php

class Router {
    private static $routes = [];

    public static function get($path, $callback) {
        self::$routes['GET'][$path] = $callback;
    }

    public static function post($path, $callback) {
        self::$routes['POST'][$path] = $callback;
    }

    public static function dispatch($uri, $method) {
        $path = parse_url($uri, PHP_URL_PATH);
        $path = str_replace('/restpo', '', $path); // Adjust based on your local setup

        if ($path == '') $path = '/';

        if (isset(self::$routes[$method][$path])) {
            $callback = self::$routes[$method][$path];
            if (is_array($callback)) {
                $controller = new $callback[0]();
                $method = $callback[1];
                $controller->$method();
            } else {
                call_user_func($callback);
            }
            return;
        }

        // If no exact route match, check if first path segment is a custom restaurant slug
        $cleanPath = ltrim($path, '/');
        if ($cleanPath !== '') {
            $parts = explode('/', $cleanPath);
            $slug = $parts[0] ?? '';
            $table_code = $parts[1] ?? null;

            if ($slug !== '') {
                $db = getDB();
                $stmt = $db->prepare('SELECT id FROM restaurants WHERE slug = ? LIMIT 1');
                $stmt->execute([$slug]);
                $restaurant = $stmt->fetch();

                if ($restaurant) {
                    $_GET['r'] = $slug;
                    if ($table_code) {
                        $_GET['code'] = $table_code;
                    }
                    $controller = new QrController();
                    $controller->menuBySlug($slug);
                    return;
                }
            }
        }

        // Fallback to 404
        http_response_code(404);
        echo "404 Not Found";
    }
}
