<?php

declare(strict_types=1);

namespace BrandCrockAquaTheme\Service;

use Shopware\Core\Content\Product\Cms\ProductListingCmsElementResolver;
use Shopware\Core\Content\Cms\Aggregate\CmsSlot\CmsSlotEntity;
use Shopware\Core\Content\Cms\DataResolver\Element\ElementDataCollection;
use Shopware\Core\Content\Cms\DataResolver\ResolverContext\ResolverContext;
use Shopware\Core\Content\Cms\SalesChannel\Struct\ProductListingStruct;
use Shopware\Core\Content\Product\SalesChannel\Sorting\ProductSortingCollection;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;

class ListingServiceDecorator extends ProductListingCmsElementResolver
{
    private ProductListingCmsElementResolver $inner;

    /**
     * @internal
     */
    public function __construct(
        ProductListingCmsElementResolver $inner
    ) {
        $this->inner = $inner;
    }

    public function getType(): string
    {
        return 'product-listing';
    }

    public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
    {
        $this->inner->enrich($slot, $resolverContext, $result);

        $data = new ProductListingStruct();

        $slot->setData($data);

        $request = $resolverContext->getRequest();
        $session = $request->getSession();
        $boxLayoutParam = $request->query->get('boxLayout');
        $config = $slot->getTranslation('config');

        if ($boxLayoutParam) {
            $configValue = 'standard'; 

            if (!empty($config['boxLayout']) && !empty($config['boxLayout']['value'])) {
                $configValue = $config['boxLayout']['value'];
            }

            $session->set('boxLayoutBc', $configValue);

            $config['boxLayout']['value'] = $boxLayoutParam;

            $translated = $slot->getTranslated();

            $translated['config']['boxLayout']['value'] = $boxLayoutParam;

            $slot->setTranslated($translated);
            $slot->setConfig($config);
            $session->set('boxLayout', $boxLayoutParam);
        } else if ($request->isXmlHttpRequest()) {
            if ($session->get('boxLayoutBc') != null) {
                $config['boxLayout']['value'] = $session->get('boxLayoutBc');
                $translated['config']['boxLayout']['value'] = $session->get('boxLayoutBc');

                $slot->setTranslated($translated);
                $slot->setConfig($config);
                $session->set('boxLayout', $session->get('boxLayoutBc'));
            } else {
                $session->set('boxLayout', $config['boxLayout']['value']);
            }
        } else {
            $session->remove('boxLayoutBc');
        }

        $this->inner->enrich($slot, $resolverContext, $result);
    }
}
