<?php

namespace KupShop\ComponentsBundle\Twig\Components\Product;

use KupShop\CatalogBundle\Entity\Wrapper\ProducerWrapper;
use KupShop\CatalogBundle\Repository\ProducersRepository;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Entity\EditableContent;
use KupShop\ComponentsBundle\Entity\ObjectInfo;
use KupShop\ComponentsBundle\Entity\Thumbnail;
use KupShop\ComponentsBundle\Interfaces\Microdata;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\MicrodataProvider;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataTrait;
use KupShop\I18nBundle\Translations\ProducersTranslation;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use Query\Operator;
use Query\Translation;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Product/ProducerSimple/ProducerSimple.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class ProducerSimple extends BaseComponent implements Microdata
{
    use ProductDataTrait;

    protected ProducersRepository $producersRepository;
    protected ?ProducerWrapper $producer = null;
    protected ?Thumbnail $thumbnail = null;

    public bool $show_name = true;
    public bool $hide_logo = false;
    public bool $show_btn = false;
    public string $btn_class = 'btn-primary';
    public ?string $image_type = null;
    public int $image_position = 0;

    public function __construct(protected readonly UrlFinder $urlFinder)
    {
    }

    public function hasProducer(): bool
    {
        return $this->getProducer() !== null;
    }

    protected function getProducer(): ?ProducerWrapper
    {
        if ($this->product->idProducer === null) {
            return null;
        }

        if (!isset($this->producer)) {
            $producer = sqlQueryBuilder()->select('pr.*')
                ->from('producers', 'pr')
                ->andWhere(Operator::equals(['pr.id' => $this->product->idProducer]))
                ->andWhere('pr.active="Y"')
                ->andWhere(Translation::coalesceTranslatedFields(ProducersTranslation::class,
                    ['name' => 'name', 'web' => 'web', 'data' => 'data_translated']))
                ->execute()->fetchAssociative();
            if (empty($producer)) {
                return null;
            }

            $producer['data'] = array_replace_recursive(json_decode($producer['data'], true) ?: [],
                json_decode($producer['data_translated'], true) ?: []);

            $this->producer = (new ProducerWrapper())->setObject($producer);
        }

        return $this->producer;
    }

    public function getId(): ?int
    {
        $producer = $this->getProducer();

        return $producer['id'] ?? null;
    }

    public function getName(): ?string
    {
        $producer = $this->getProducer();

        return $producer['name'] ?? null;
    }

    public function getBlockId(): ?int
    {
        $producer = $this->getProducer();

        return $producer['id_block'] ?? null;
    }

    public function getUrl(): ?string
    {
        $producer = $this->getProducer();

        return $producer['url'] ?? null;
    }

    public function getThumbnail(): ?Thumbnail
    {
        if ($this->thumbnail === null) {
            $producer = $this->getProducer();

            if ($producer['photo'] ?? null) {
                $this->thumbnail = new Thumbnail($this->getId(), $this->getName(), $this->producer['date_updated']);
            }
        }

        return $this->thumbnail;
    }

    public function getObjectInfo(): ObjectInfo
    {
        return new ObjectInfo(
            type: 'producers',
            id: $this->getId(),
            name: (translate('objects', 'blocks', true, true)['producer'] ?? 'producer').': '.$this->getName()
        );
    }

    public function getContent(): EditableContent
    {
        return new EditableContent(
            blockId: (int) $this->getBlockId(),
            objectInfo: $this->getObjectInfo()
        );
    }

    protected function getImages(): ?array
    {
        if ($this->product->idProducer === null) {
            return null;
        }

        return $this->producersRepository->getProducerEntity($this->product->idProducer)?->getPhotos() ?? [];
    }

    public function getImage(): ?Thumbnail
    {
        $allImages = $this->getImages();

        if ($allImages === null) {
            return null;
        }

        $image = array_values($allImages)[$this->image_position] ?? null;

        if (empty($image)) {
            return null;
        }

        return new Thumbnail((string) $image['id'], $image['descr'], (string) $image['date_update']);
    }

    public function initMicrodata(): array
    {
        if (!$this->getProducer()) {
            return [];
        }

        return [MicrodataProvider::PRODUCT => ['brand' => [
            '@type' => 'Brand',
            'name' => $this->getName(),
            'logo' => ($this->getThumbnail() ? $this->urlFinder->shopUrlAbsolute(getImagePath($this->getThumbnail()->id, 'producer')) : null),
        ]]];
    }

    #[Required]
    public function setProducersRepository(ProducersRepository $producersRepository): void
    {
        $this->producersRepository = $producersRepository;
    }
}
