<?php

declare(strict_types=1);

namespace KupShop\GTMBundle\Utils;

use KupShop\CatalogBundle\Util\ActiveCategory;
use KupShop\KupShopBundle\Views\View;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Service\Attribute\Required;

/**
 * @property View $view
 */
trait ViewDataHelper
{
    protected ActiveCategory $activeCategory;
    protected RequestStack $requestStack;

    protected function fetchView(?View $view = null): View
    {
        if (!$view) {
            $view = $this->getRequest()->get('view');
        }

        return $view === null ? $this->view : $view;
    }

    public function getBreadcrumbs(?View $view = null): array
    {
        $view = $this->fetchView($view);

        if ($view->getTemplateData()['body']['returnNav'][0] ?? false) {
            $nav = $view->getTemplateData()['body']['returnNav'][0];
        } else {
            if (findModule(\Modules::COMPONENTS)) {
                $nav = $view->getBreadcrumbsNew() ?? [];
            } else {
                $nav = $view->getBreadcrumbs()[0] ?? [];
            }
        }

        return $nav;
    }

    public function getBreadcrumbsWithoutCurrent(?View $view = null): array
    {
        $catPath = $this->getBreadcrumbs($view);
        unset($catPath[0]);

        return $this->getCategoriesMap($catPath);
    }

    public function getPageTitle(?View $view = null): string
    {
        $view = $this->fetchView($view);

        return $view->getTemplateData()['header']['pageTitle'] ?? ($view->getMetaTitle() ?? '');
    }

    public function getCategoriesMap($categories): array
    {
        return array_values(array_map(function ($cat) {
            if (!empty($cat) && is_int($cat)) {
                $cat = $this->activeCategory->getSectionById($cat);
            }

            return [
                'id' => $cat['ID'] ?? '',
                'name' => $cat['text'] ?? $cat['name'] ?? '',
            ];
        }, $categories));
    }

    protected function getRequest(): Request
    {
        return $this->requestStack->getCurrentRequest();
    }

    #[Required]
    public function setActiveCategory(ActiveCategory $activeCategory): void
    {
        $this->activeCategory = $activeCategory;
    }

    #[Required]
    public function setRequestStack(RequestStack $requestStack): void
    {
        $this->requestStack = $requestStack;
    }
}
