<?php

namespace Lc\ShopBundle\Services\Order;


use Lc\ShopBundle\Context\OrderPaymentInterface;

trait OrderUtilsPaymentTrait
{
        public function createOrderPayment($orderShop, $meanPayment, $amount, $reference = null, $comment = null, $paidAt = null)
        {
                $classOrderPayment = $this->em->getClassMetadata(OrderPaymentInterface::class)->getName();
                $orderPayment = new $classOrderPayment;

                $orderPayment->setOrderShop($orderShop);
                $orderPayment->setMeanPayment($meanPayment);
                $orderPayment->setAmount($amount);
                $orderPayment->setReference($reference);
                $orderPayment->setComment($comment);
                $orderPayment->setEditable(false);
                $orderPayment->setCreatedBy($orderShop->getUser());
                $orderPayment->setUpdatedBy($orderShop->getUser());

                if ($paidAt) {
                        $orderPayment->setPaidAt($paidAt);
                } else {
                        $orderPayment->setPaidAt(new \DateTime('now'));
                }

                $this->em->persist($orderPayment);
                $this->em->flush();

                return $orderPayment;
        }

        public function isOrderPaid($order, $mergeComplementaryOrderShop = false)
        {

                if ($this->getTotalOrderPayments($order, $mergeComplementaryOrderShop) >= $this->priceUtils->getTotalWithTax($order) && $this->priceUtils->getTotalWithTax($order) > 0) {
                        return true;
                } else {
                        return false;
                }


        }

        public function getTotalOrderPayments($order, $mergeComplementaryOrderShop = false): float
        {
                $totalAmount = floatval(0);
                foreach ($order->getOrderPayments() as $orderPayment) {
                        $totalAmount = $orderPayment->getAmount() + $totalAmount;
                }
                if($mergeComplementaryOrderShop) {
                        foreach ($order->getComplementaryOrderShops() as $complementaryOrderShop) {
                                foreach ($complementaryOrderShop->getOrderPayments() as $orderPayment) {
                                        $totalAmount = $orderPayment->getAmount() + $totalAmount;
                                }
                        }
                }
                return $totalAmount;
        }

}
