<?php
/*
 * Copyright (c) 2023. RTM Business
 */

namespace WordpressModels\ORM\WooCommerceEntity\PostType;

use AcademiaExtensions\Serialization\ObjectNormalizer;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\OneToMany;
use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Annotation\Groups;
use WordpressModels\ORM\Entity\Post;
use WordpressModels\ORM\Entity\User;
use WordpressModels\ORM\EntityManagerFactory;
use WordpressModels\ORM\WooCommerceEntity\OrderItem;

#[Entity]
class ShopOrder extends Post
{

    // line items
    #[OneToMany(mappedBy: 'order', targetEntity: OrderItem::class)]
    #[Groups(['read_order'])]
    #[Context([
        'normalization_context' => [
            ObjectNormalizer::ENABLE_MAX_TREE_DEPTH => true,
            ObjectNormalizer::TREE_DEPTH_LIMIT => 1,
            'groups' => ['read_order_item']
        ]
    ])]
    private Collection $items;

    public function __construct()
    {
        parent::__construct();
        $this->items = new ArrayCollection();
    }

    #[Groups(['read_order'])]
    public function getOrderNumber(): string
    {
        return $this->getMetaValue('_order_number');
    }

    #[Groups(['read_order'])]
    public function getOrderDate(): \DateTimeInterface
    {
        return $this->getDate();
    }

    #[Groups(['read_order'])]
    public function getOrderStatus(): string
    {
        return str_replace('wc-', '', $this->getStatus());
    }

    #[
        Groups(['read_order']),
        Context([
            'normalization_context' => [
                ObjectNormalizer::ENABLE_MAX_TREE_DEPTH => true,
                ObjectNormalizer::TREE_DEPTH_LIMIT => 1,
                'groups' => ['read_simple_user']
            ]
        ])]
    public function getCustomer(): User|null
    {
        $metaValue = $this->getMetaValue('_customer_user');
        if (!$metaValue) {
            return null;
        }
        return EntityManagerFactory::instance()->getRepository(User::class)->find($metaValue);
    }

    // order items getter, setter, adder, remover
    public function getItems(): Collection
    {
        return $this->items;
    }

    public function setItems(Collection $items): ShopOrder
    {
        $this->items = $items;
        return $this;
    }

    public function addItem(OrderItem $lineItem): ShopOrder
    {
        $this->items->add($lineItem);
        return $this;
    }

    public function removeItem(OrderItem $lineItem): ShopOrder
    {
        $this->items->removeElement($lineItem);
        return $this;
    }

}