<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Cart\Model\PaymentMethod;
use CpCreation\VitiCore\Cart\Repository\CartRepository;
use CpCreation\VitiCore\Payment\Model\Payment;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

class PaymentSubscriber implements EventSubscriber
{
    private $cartRepository;

    public function __construct(CartRepository $cartRepository)
    {
        $this->cartRepository = $cartRepository;
    }

    public function getSubscribedEvents()
    {

        return [
            Events::prePersist,
            Events::preUpdate,
        ];
    }

    /**
     * @param LifecycleEventArgs $event
     */
    public function prePersist(LifecycleEventArgs $event)
    {
        $entity        = $event->getObject();
        $entityManager = $event->getEntityManager();
        if ($entity instanceof Payment) {
            $paymentMethod  = $entityManager->getRepository(PaymentMethod::class)->findByDefaultForPaymentOnline();
            $cartExistToken = $this->cartRepository->findOneBy(['token' => $entity->getReference()]);
            if ($cartExistToken) {
                $entity->setReference($entity->getReference().'-1');
            }
            $entity->setPaymentMethod($paymentMethod);
        }
    }

    /**
     * @param LifecycleEventArgs $event
     */
    public function preUpdate(LifecycleEventArgs $event)
    {
        $entity        = $event->getObject();
        $entityManager = $event->getEntityManager();
        if ($entity instanceof Payment) {
            $paymentMethod = $entityManager->getRepository(PaymentMethod::class)->findByDefaultForPaymentOnline();
            $entity->setPaymentMethod($paymentMethod);
            $cartExistToken = $this->cartRepository->findOneBy(['token' => $entity->getReference()]);
            if ($cartExistToken) {
                $entity->setReference($entity->getReference().'-1');
            }
        }
    }
}
