<?php

namespace AutoAdmin\Bundle\Admin\Twig\Extension;

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

class AdminExtension extends AbstractExtension
{
    private Environment $twig;
    private RequestStack $requestStack;
    private ConfigManager $configManager;
    private TranslatorInterface $translator;

    public function __construct(
        Environment         $twig,
        RequestStack        $requestStack,
        ConfigManager       $configManager,
        TranslatorInterface $translator
    )
    {
        $this->twig = $twig;
        $this->requestStack = $requestStack;
        $this->configManager = $configManager;
        $this->translator = $translator;
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('aa_admin_entity_tab_menu', [$this, 'getEntityTabMenu'], ['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;
    }
}
