<?php

declare(strict_types=1);

namespace KupShop\GraphQLBundle\ApiAdmin\Types\OrderDiscount;

use KupShop\GraphQLBundle\ApiShared\ApiUtil;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

#[Type]
class DiscountCoupon
{
    public function __construct(
        private array $coupon,
    ) {
    }

    #[Field(description: 'ID.')]
    public function getId(): int
    {
        return $this->coupon['id'];
    }

    #[Field(description: 'Název.')]
    public function getName(): string
    {
        return $this->coupon['name'];
    }

    #[Field(description: 'Kód.')]
    public function getCode(): string
    {
        return $this->coupon['code'];
    }

    #[Field(description: 'Datum, kdy byl kupón aktivován. Pokud je `null`, tak není aktivní.')]
    public function getDateActivated(): ?\DateTimeInterface
    {
        if (empty($this->coupon['date_activated'])) {
            return null;
        }

        return ApiUtil::prepareDateTimeFromDB($this->coupon['date_activated']);
    }

    #[Field(description: 'Datum, od kdy je kupón platný. Pokud je `null`, tak nemá počáteční platnost.')]
    public function getDateFrom(): ?\DateTimeInterface
    {
        if (empty($this->coupon['date_from'])) {
            return null;
        }

        return ApiUtil::prepareDateTimeFromDB($this->coupon['date_from']);
    }

    #[Field(description: 'Datum, do kdy je kupón platný. Pokud je `null`, tak nemá konečnou platnost.')]
    public function getDateTo(): ?\DateTimeInterface
    {
        if (empty($this->coupon['date_to'])) {
            return null;
        }

        return ApiUtil::prepareDateTimeFromDB($this->coupon['date_to']);
    }

    #[Field(description: 'Informace, zda je kupón použit.')]
    public function getIsUsed(): bool
    {
        return $this->coupon['used'] === 'Y';
    }

    #[Field(description: 'Informace, zda je kupón možné použít.')]
    public function getIsUsable(): bool
    {
        return $this->getIsActive() && !$this->getIsUsed();
    }

    private function getIsActive(): bool
    {
        if (!$this->coupon['date_activated']) {
            return false;
        }

        $isActive = true;
        if (!empty($this->coupon['date_from'])) {
            $dateFrom = new \DateTime($this->coupon['date_from']);
            if ($dateFrom > (new \DateTime())) {
                $isActive = false;
            }
        }

        if (!empty($this->coupon['date_to'])) {
            $dateTo = new \DateTime($this->coupon['date_to']);
            if ($dateTo < (new \DateTime())) {
                $isActive = false;
            }
        }

        return $isActive;
    }
}
