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

namespace WordpressModels\ORM\WooCommerceEntity\PostType;

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;
use WordpressModels\Serialization\TreeDepthObjectNormalizer;

#[Entity]
class ShopOrder extends Post
{

    // line items
    #[OneToMany(mappedBy: 'order', targetEntity: OrderItem::class)]
    #[Groups(['read_order'])]
    #[Context(normalizationContext: [
        TreeDepthObjectNormalizer::ENABLE_MAX_TREE_DEPTH => true,
        TreeDepthObjectNormalizer::TREE_DEPTH_LIMIT => 2,
        'groups' => ['read_order_item_simple']
    ])]
    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(
            normalizationContext: [
                TreeDepthObjectNormalizer::ENABLE_MAX_TREE_DEPTH => true,
                TreeDepthObjectNormalizer::TREE_DEPTH_LIMIT => 2,
                'groups' => ['read_user_simple']
            ])]
    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;
    }

}