<?php

namespace KupShop\ComponentsBundle\Twig\Components\Header\Sections;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Entity\Thumbnail;
use KupShop\ComponentsBundle\GTM\PostMount\GTMDefaultData;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\SectionDataTrait;
use KupShop\ContentBundle\Entity\Slide;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Header/Sections/Banner/Banner.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class Banner extends BaseComponent
{
    use SectionDataTrait;
    use GTMDefaultData;

    private ?Slide $slideBanner = null;

    #[Required]
    public \KupShop\ComponentsBundle\GTM\Events\Promotions $gtmClass;

    public string $thumbnail_type = 'slider';

    public function getBanner($id_section)
    {
        $this->multiFetch()->fetchSliders();

        $menuSliders = array_filter($this->sectionDataProvider->getSection($id_section)->getObject()->getSliders(), function ($key) {
            return $key == 'menu';
        }, ARRAY_FILTER_USE_KEY);

        $images = $menuSliders['menu']['images'] ?? [];

        return reset($images);
    }

    public function getSlide(): ?Slide
    {
        if (!$this->slideBanner && ($image = $this->getBanner($this->id_section))) {
            $this->slideBanner = new Slide();
            $this->slideBanner
                ->setId($image['id'])
                ->setDescription($image['description'])
                ->setImage($image['photo'])
                ->setCustomData($image['custom_data'])
                ->setLink($image['link'])
                ->setSlider($image['slider']);
        }

        return $this->slideBanner;
    }

    public function getThumbnail(): ?Thumbnail
    {
        $image = $this->getSlide()->getImage();

        if ($image->getId() > 0) {
            return new Thumbnail((string) $image->getId(), $image->getDescription(), $image->getDateUpdated()->format('Y-m-d H:i:s'));
        }

        return null;
    }

    public function getGTMPlaceholders(): array
    {
        if ($slide = $this->getSlide()) {
            return ['promotions' => $this->gtmClass->getPromotion($slide)];
        }

        return [];
    }

    public function getGTMClickData(): ?string
    {
        if (($slide = $this->getSlide()) && ($gtmData = $this->gtmClass->getClickData($slide))) {
            return json_encode($gtmData, JSON_NUMERIC_CHECK | JSON_HEX_APOS);
        }

        return null;
    }
}
