<?php

namespace KupShop\OrderDiscountBundle\Twig\Components\Discounts\Handlers;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Entity\Thumbnail;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataProvider;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@OrderDiscount/components/Discounts/Upsell/Upsell.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class Upsell extends AbstractOrderDiscount
{
    #[Required]
    public ProductDataProvider $provider;

    public array $id_products = [];

    private ?\Product $mainProduct = null;

    public function getThumbnail()
    {
        $product = $this->getMainProduct();

        return new Thumbnail($product->photoId, $product->photoDescr, $product->photoDateUpdate);
    }

    public function getDescription()
    {
        return $this->data['description'] ?? '';
    }

    public function getPrice()
    {
        return $this->getMainProduct()->getProductPrice();
    }

    protected function getMainProduct(): \Product
    {
        if (is_null($this->mainProduct)) {
            foreach ($this->id_products as $id_product) {
                $product = $this->provider->getProduct($id_product);

                if ($this->mainProduct === null || $product->getProductPrice()->getPriceWithVat()->lowerThan($this->mainProduct->getProductPrice()->getPriceWithVat())) {
                    $this->mainProduct = $product;
                }
            }
        }

        return $this->mainProduct;
    }
}
