<?php

declare(strict_types=1);

namespace KupShop\ReservationBundle\Entity;

use KupShop\I18nBundle\Entity\Currency;
use KupShop\I18nBundle\Entity\Language;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Template\ArrayAccess;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\Price\Price;

class Reservation extends ArrayAccess
{
    public int $id;

    public \DateTimeImmutable $dateCreated;

    public ?Language $language = null;

    public ?Currency $currency = null;

    public ?int $userId = null;

    public ?int $orderId = null;

    public int $productId;

    public ?int $variationId = null;

    public float $price;

    public float $tax;

    public string $email;

    public string $name;

    public string $surname;

    public string $phone;

    public ?\Order $order = null;

    private array $data = [];

    public function setDateCreated(string $dateCreated): self
    {
        $this->dateCreated = new \DateTimeImmutable($dateCreated);

        return $this;
    }

    public function setIdLanguage(?string $language): self
    {
        $this->language = Contexts::get(LanguageContext::class)->getSupported()[$language] ?? null;

        return $this;
    }

    public function setCurrency(?string $currency): self
    {
        $this->currency = Contexts::get(CurrencyContext::class)->getOrDefault($currency);

        return $this;
    }

    public function setIdOrder(?int $orderId): self
    {
        $this->orderId = $orderId;

        return $this;
    }

    public function setIdUser(?int $userId): self
    {
        $this->userId = $userId;

        return $this;
    }

    public function setIdProduct(int $productId): self
    {
        $this->productId = $productId;

        return $this;
    }

    public function setIdVariation(?int $variationId): self
    {
        $this->variationId = $variationId;

        return $this;
    }

    public function setOrder(\Order $order): self
    {
        $this->order = $order;

        return $this;
    }

    public function setData(?string $data): self
    {
        $this->data = json_decode($data ?: '', true) ?? [];

        return $this;
    }

    public function getOrder(): ?\Order
    {
        if ($this->order) {
            return $this->order;
        }
        if ($this->orderId) {
            return \Order::get($this->orderId);
        }

        return null;
    }

    public function getProduct(): \Product
    {
        $product = \Variation::createProductOrVariation($this->productId, $this->variationId);
        $product->createFromDB();

        return $product;
    }

    public function getPrice(): Price
    {
        return new Price(toDecimal($this->price), $this->currency, $this->tax);
    }

    public function getData(): array
    {
        return $this->data;
    }
}
