<?php

namespace Velis\Mvc\View\Helper;

use Phalcon\Mvc\Router\Route;
use Velis\App;
use Velis\Exception as VelisException;
use Velis\Mvc\Router;
use Velis\Mvc\View;
use Velis\Output;

class NonSwitchableUrl
{
    /**
     * For a given route returns /module/controller/action url if module is switched, standard ini url if not
     * Use in tab hrefs, dashboard widgets and other places that should render tpls via ajax
     * Pass $fallbackPath as the last argument to override the standard MVC url
     */
    public function __invoke(string $routeName, string $switchableModule, ?string $fallbackPath = null): string
    {
        /** @var View $view */
        $view = App::getService('view');

        /** @var Router|\Phalcon\Mvc\Router $currentRouter */
        $currentRouter = App::getService('router');

        if ($currentRouter instanceof Router && $currentRouter->isModuleSwitched($switchableModule)) {
            if ($fallbackPath) {
                return $fallbackPath;
            }

            $route = $currentRouter->getRouteByName($routeName);
            $paths = $route->getPaths();

            $module = Output::toKebabCase($paths['module']);
            $controller = Output::toKebabCase($paths['controller']);
            $action = Output::toKebabCase($paths['action']);

            if ($route instanceof Route && $module && $controller && $action) {
                return "/$module/$controller/$action";
            }

            VelisException::raise("No route found for route name $routeName");

            return '';
        }

        return $view->url($routeName);
    }
}
