<?php
namespace App\Subscriber\Payment;
use App\Event\Payment\EncashmentEvent;
use App\Lib\Payment\Settlement;
use App\Service\Payment\BookingService;
use App\Service\Payment\EncashmentService;
use App\Service\Payment\PaymentService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EncashmentSubscriber implements EventSubscriberInterface
{
/**
* @var EncashmentService
*/
protected $encashmentService;
/**
* @var PaymentService
*/
protected $service;
/**
* @var BookingService
*/
protected $bookingService;
/**
* EncashmentSubscriber constructor.
*/
public function __construct(PaymentService $paymentService, BookingService $bookingService, EncashmentService $encashmentService)
{
$this->encashmentService = $encashmentService;
$this->service = $paymentService;
$this->bookingService = $bookingService;
}
public static function getSubscribedEvents(): array
{
return [
EncashmentEvent::class => [
['onEncashmentCreated', 0],
],
];
}
protected function getBookingService(): BookingService
{
return $this->bookingService;
}
protected function getPaymentService(): PaymentService
{
return $this->service;
}
/**
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function onEncashmentCreated(EncashmentEvent $event)
{
$encashment = $event->getEncashment();
$account = $encashment->getAccount();
$possibleSettlements = $this->getPaymentService()->getPossibleSettlementsByAmount($account, $encashment->getAmount());
$cleared = 0;
$fee = 0;
if (count($possibleSettlements)) {
$fee = round($encashment->getFee() / count($possibleSettlements), 2);
}
foreach ($possibleSettlements as $chargeback) {
$settlement = new Settlement();
$settlement->setBookingId($chargeback->getBookingId());
$settlement->setAmount(abs($chargeback->getAmount()));
$settlement->setVendor($chargeback->getVendor());
$settlement->setCustomerId($chargeback->getCustomerId());
$settlement->setFee($fee);
$settlement->setRealamount(abs($chargeback->getAmount()) + $fee);
$payment = $this->getBookingService()->storeConceptObject($settlement, $account);
if ($encashment->paymentProcess) {
$payment->setPaymentProcess($encashment->paymentProcess);
}
if ($encashment->paymentReference) {
$payment->setPaymentReference($encashment->paymentReference);
}
$this->getPaymentService()->storePayment($payment, [
'conceptObject' => $settlement,
]);
$cleared += abs($chargeback->getAmount());
$encashment->resultingPayments[] = $payment;
}
$encashment->setCleared($cleared);
$this->encashmentService->storeEntity($encashment);
}
}