<?php
namespace App\EventSubscriber;
use App\Event\OrderPlacedEvent;
use App\Service\SmsProClient;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderPlacedSubscriber implements EventSubscriberInterface
{
private SmsProClient $smsProClient;
private LoggerInterface $logger;
public function __construct(SmsProClient $smsProClient, LoggerInterface $logger)
{
$this->smsProClient = $smsProClient;
$this->logger = $logger;
}
public static function getSubscribedEvents(): array
{
return [
OrderPlacedEvent::class => 'onOrderPlaced',
];
}
public function onOrderPlaced(OrderPlacedEvent $event): void
{
$this->logger->info('SMS DEBUG: OrderPlacedSubscriber declenche');
$this->logger->info('SMS DEBUG: donnees commande', [
'ticket' => $event->getReference(),
'telephone' => $event->getCustomerPhone(),
'total' => $event->getTotal(),
]);
$telephone = $this->normalizePhone($event->getCustomerPhone());
if ($telephone === null || $telephone === '') {
$this->logger->warning('SMS skipped: missing or invalid customer phone.', [
'ticket' => $event->getReference(),
'phone' => $event->getCustomerPhone(),
]);
return;
}
$message = sprintf(
'Votre commande N°%s a ete recue. Montant: %s FCFA. Merci.',
$event->getReference(),
number_format($event->getTotal(), 0, ',', ' ')
);
$lieu = trim((string) $event->getDeliveryAddress());
if ($lieu !== '') {
$message .= ' Livraison: ' . $lieu;
}
$result = $this->smsProClient->sendSms($telephone, $message);
if (!empty($result['success'])) {
$this->logger->info('Order SMS sent successfully.', [
'ticket' => $event->getReference(),
'recipient' => $telephone,
'http_code' => $result['http_code'] ?? null,
]);
return;
}
$this->logger->error('Order SMS failed.', [
'ticket' => $event->getReference(),
'recipient' => $telephone,
'http_code' => $result['http_code'] ?? null,
'error' => $result['error'] ?? null,
'raw' => $result['raw'] ?? null,
]);
}
private function normalizePhone(?string $phone): ?string
{
$phone = trim((string) $phone);
if ($phone === '') {
return null;
}
$phone = str_replace(' ', '', $phone);
if (strpos($phone, '00') === 0) {
$phone = '+' . substr($phone, 2);
}
return $phone;
}
}