<?php
namespace App\Service;
use App\Controller\SystemActionsInterface;
use App\Entity\Sms;
use App\Entity\SmsSetup;
use App\Entity\User;
use App\Entity\WayBill;
use App\Messages\SMSMessage;
use DateTime;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Messenger\MessageBusInterface;
class ActionMatrix implements SystemActionsInterface {
private MessageBusInterface $messageBus;
private ObjectManager $em;
private BuildSMSMessage $buildSMSMessage;
private WayBill $waybill;
public function __construct(MessageBusInterface $messageBus,ObjectManager $objectManager, WayBill $waybill)
{
$this->messageBus = $messageBus;
$this->em = $objectManager;
$this->waybill = $waybill;
}
function registeringAction(User $user): void
{
$action = 'registering';
$this->buildHelper($user,$action);
}
function payingAction(User $user,string $paymentMode): void
{
$action = 'paying';
$this->buildHelper($user,$action);
}
function loadingAction(User $user): void
{
$action = 'loading';
$this->buildHelper($user,$action);
}
function receivingAction(User $user): void
{
$action = 'receiving';
$this->buildHelper($user,$action);
}
function collectingAction(User $user): void
{
$action = 'collecting';
$this->buildHelper($user,$action);
}
private function buildHelper(User $user,$action): void
{
$messageTemplates = $this->em->getRepository(SmsSetup::class)->findBy([
'action' => $action
]);
$receiverPhone = str_replace(' ', '', $this->waybill->getReceiverPhoneNumber());
$senderPhone = str_replace(' ', '', $this->waybill->getSenderPhoneNumber());
$buildSms = new BuildSMSMessage($this->waybill);
foreach ($messageTemplates as $index => $messageTemplate) {
$smsMessage = $buildSms->build($messageTemplate->getSampleMessage());
$sendTo = '+254'.substr($senderPhone,1);
if($messageTemplate->getSendTo() == 'receiver'){
$sendTo = '+254'.substr($receiverPhone,1);
}
$availableSms = $this->em->getRepository(Sms::class)->findBy([
'transaction' => $this->waybill->getTransaction(),
'recepient' => $sendTo,
'action' => $action
]);
if(!$availableSms){
$sms = new Sms();
$sms->setSms($smsMessage);
$sms->setTransaction($this->waybill->getTransaction());
$sms->setRecepient($sendTo);
$sms->setCreatedAt(new DateTime());
$sms->setCreatedBy($user);
$sms->setAmount(0);
$sms->setAction($action);
$this->em->persist($sms);
$this->em->flush();
$this->messageBus->dispatch(new SMSMessage($sms->getId()));
}
}
}
function resendAction(): void {
$smses = $this->em->getRepository(WayBill::class)->findFailedSmsByInserficient();
foreach ($smses as $index => $sms) {
$this->messageBus->dispatch(new SMSMessage($sms['id']));
}
}
}