<?php

namespace KupShop\ComponentsBundle\Twig\Components\Account\OrderDetail;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Dto\OrderItem;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\OrderDataTrait;
use KupShop\OrderingBundle\Util\Order\OrderItemInfo;
use KupShop\PreordersBundle\Entity\UserPreorder;
use Query\Operator;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Account/OrderDetail/Items/Items.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class Items extends BaseComponent
{
    use OrderDataTrait;

    public ?string $title = null;
    protected array $items;
    protected array $photos;
    protected array $coupons;

    public bool $showPriceWithoutVat = false;

    public function __construct(protected OrderItemInfo $orderItemInfo)
    {
    }

    public function getIsPreorder(): bool
    {
        return $this->order->getObject() instanceof UserPreorder;
    }

    public function getItems(): array
    {
        return $this->order->getItems();
    }

    public function getItemInfo(OrderItem $product): array
    {
        $order = $this->order->getObject();
        if (!($order instanceof \Order)) {
            return [];
        }

        return $order->getItemInfo($product->toArray());
    }

    protected function getOrderCoupons(): array
    {
        $order = $this->order->getObject();
        if (!($order instanceof \Order)) {
            return [];
        }

        if (!isset($this->coupons)) {
            $this->coupons = [];
            if ($order->isActive() && $order->isPaid()) {
                $coupons = sqlQueryBuilder()->select('*')
                    ->from('discounts_coupons', 'dc')
                    ->andWhere(Operator::equals(['dc.id_order_purchased' => $this->id_order]))
                    ->sendToMaster()
                    ->execute()->fetchAllAssociative();
                foreach ($coupons as $coupon) {
                    $url = path('kupshop_orderingbundle_pdfcoupon', [
                        'id_order' => $this->id_order,
                        'id_coupon' => $coupon['id'],
                        'cf' => $order->getSecurityCode(),
                    ], 0);
                    $this->coupons[$coupon['id_order_item']][$coupon['code']] = $url;
                }
            }
        }

        return $this->coupons;
    }

    public function getCoupons(int $id_item): ?array
    {
        return getVal($id_item, $this->getOrderCoupons());
    }
}
