<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\AccountHistory;
use App\Entity\ReservationPayment;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class ReservationPaymentSubscriber implements EventSubscriberInterface
{
private $tokentStorage;
private $entityManager;
public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $entityManager)
{
$this->tokentStorage = $tokenStorage;
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [
['updateAccount', EventPriorities::PRE_WRITE],
],
];
}
public function updateAccount(ViewEvent $event){
$reservationPayment = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
//die(strtolower($reservationPayment->getPaymentMethod()->getName()));
if (!$reservationPayment instanceof ReservationPayment || Request::METHOD_POST !== $method) {
return;
}
if($reservationPayment->getReservationBedroom() && (strtolower($reservationPayment->getPaymentMethod()->getName()) == "compte client")){
//die(strtolower($reservationPayment->getPaymentMethod()->getName()));
/*if($reservationPayment->getReservationBedroom()->getCustomer()->getAccount()){
$reservationPayment->getReservationBedroom()->getCustomer()->getAccount()->setAmount($reservationPayment->getReservationBedroom()->getCustomer()->getAccount()->getAmount() - $reservationPayment->getAmount());
}*/
$accountHistory = new AccountHistory();
$accountHistory->setAmount(-$reservationPayment->getAmount());
$accountHistory->setCreatedBy($this->tokentStorage->getToken()->getUser());
$accountHistory->setAccount($reservationPayment->getReservationBedroom()->getCustomer()->getAccount());
$reservationPayment->getReservationBedroom()->getCustomer()->getAccount()->setAmount($reservationPayment->getReservationBedroom()->getCustomer()->getAccount()->getAmount() - $reservationPayment->getAmount());
$this->entityManager->persist($accountHistory);
$this->entityManager->flush();
}
}
}