<?php

namespace KupShop\ComponentsBundle\Twig\Components;

use Doctrine\DBAL\Exception;
use KupShop\CatalogBundle\Util\Product\CalculateProductDiscountUtil;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataTrait;
use Query\Operator;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

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

    public function __construct(private readonly CalculateProductDiscountUtil $calculateProductDiscountUtil)
    {
    }

    /**
     * @throws Exception
     * @throws \Doctrine\DBAL\Driver\Exception
     */
    public function isMultiset(): bool
    {
        if (findModule(\Modules::PRODUCTS, \Modules::SUB_SETS) == \Modules::JS_MULTISETS) {
            if (sqlQueryBuilder()
                ->select('COUNT(*)')
                ->from('set_products')
                ->andWhere(Operator::equals(['id_product_master' => $this->id_product]))
                ->execute()
                ->fetchOne() > 0) {
                return true;
            } else {
                return false;
            }
        }

        return false;
    }

    public function getDiscount(): \Decimal
    {
        $result = $this->calculateProductDiscountUtil->calculate([
            'product' => $this->product,
        ]);

        return $result->getObject()->getDiscount();
    }

    public function getUrl(): string
    {
        return htmlspecialchars(createScriptURL(['s' => 'cart']), ENT_QUOTES);
    }

    public function getPriceArrayVat(): \Decimal
    {
        return $this->product->price_array['vat'] ?? \DecimalConstants::zero();
    }

    public function getPriceArrayValueWithoutVat(): \Decimal
    {
        return $this->product->price_array['value_without_vat'] ?? \DecimalConstants::zero();
    }

    public function getPriceArrayValueWithVat(): \Decimal
    {
        return $this->product->price_array['value_with_vat'] ?? \DecimalConstants::zero();
    }
}
