<?php

namespace AutoAdmin\Bundle\Admin\Twig\Extension;

use AutoAdmin\Bundle\Admin\Configuration\ConfigManager;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AdminExtension extends AbstractExtension
{
    public function __construct(
        private RequestStack $requestStack,
        private ConfigManager $configManager,
    ) {
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('aa_admin_entity_tab_menu', [$this, 'getEntityTabMenu'], ['is_safe' => ['html'],]),
            new TwigFunction('aa_admin_querystring_merge', [$this, 'mergeQueryString'], ['is_safe' => ['html'],]),
        ];
    }

    public function getEntityTabMenu($action = 'update')
    {
        $request = $this->requestStack->getCurrentRequest();
        $slug = $request->get('entitySlug');

        $entityConfig = $this->configManager->getEntityConfigBySlug($slug);
        if (empty($entityConfig['tabs'][$action])) {
            return null;
        }
        $tabs = $entityConfig['tabs'][$action];

        $adminTab = $request->get('tab', 'default');

        foreach ($tabs as $name => $config) {
            $tabs[$name] = array_merge_recursive($config, ['active' => $name === $adminTab,]);
        }

        return $tabs;
    }

    public function mergeQueryString(array $params)
    {
        $request = $this->requestStack->getCurrentRequest();
        $query = [
            ...$request->query->all(),
            ...$params,
        ];

        return strtok($request->getRequestUri(), '?').'?'.http_build_query($query);
    }
}
