<?php

namespace Diamond\Application\Notification\SendSms;


use Diamond\Config\Sms;
use Shop\Infrastructure\Models\SmsLog\SmsLog;
use Shop\Infrastructure\Repositories\SmsLog\SmsLogRepository;
use SmsSender\Exceptions\SmsException;
use SmsSender\Sender;

class SendSmsHandler
{

    protected $confSms;

    protected $smsLogRepo;

    /**
     * SendSmsHandler constructor.
     * @param Sms $smsConf
     * @param SmsLogRepository $smsLogRepo
     */
    public function __construct(Sms $smsConf, SmsLogRepository $smsLogRepo)
    {
        $this->confSms = $smsConf;
        $this->smsLogRepo = $smsLogRepo;
    }

    /**
     * @param SendSmsCommand $command
     */
    public function handle(SendSmsCommand $command): void
    {

        $message = $command->getMessage();
        $phone = $command->getPhone();

        if ($this->confSms->getDebug() === 'sendToSmsDISSABLED') {
            return;
        }

        if ($this->confSms->getDebug() === 'DEBUG_PHONE' && $this->confSms->getDebugPhone() > '') {
            $phone = $this->confSms->getDebugPhone();
        } elseif ($this->confSms->getDebug() == 'DEBUG_PHONE') {
            throw new SmsNotificationException('Номер для отладки смс сообщений не задан.');
        }


        if (!$this->confSms->getLogin() || !$this->confSms->getPassword()) {
            throw new SmsNotificationException('Логин или пароль от сервиса смс сообщений не заданны.');
        }

        if ($this->confSms->getDebug() === 'DEBUG_DISPLAY') {

            $resultText = 'Отображение: Отправка смс на номер ' . $phone . ' Текст: ' . $message->getContent();

        } else {

            try {

                $smsSender = $this->build();

                $result = $smsSender->send($phone, $message->getContent());

                $resultText = $result->getMessage();

            } catch (SmsException $ex) {

                $smsLog = (new SmsLog())
                    ->setPhone($phone)
                    ->setStatus($ex->getMessage())
                    ->setContent($message->getContent());

                $this->smsLogRepo->save($smsLog);

                throw new SmsNotificationException('При отправке возникла непредвиденная ошибка: ' . $ex->getMessage());
            }

        }

        $smsLog = (new SmsLog())
            ->setPhone($phone)
            ->setStatus($resultText)
            ->setContent($message->getContent());

        $this->smsLogRepo->save($smsLog);

    }

    /**
     *
     * @return \SmsSender\Sender
     */
    private function build(): Sender
    {
        $config = new \SmsSender\Drivers\Smsc\Config;
        $config
            ->setLogin($this->confSms->getLogin())
            ->setPassword($this->confSms->getPassword())
            ->setFrom($this->confSms->getFrom());

        return new Sender(new \SmsSender\Drivers\Smsc\Smsc($config));
    }
}