<?php

namespace Velis\Notification;

use Exception;
use Velis\App;
use Velis\Lang;
use Velis\Notification;
use Velis\Sms;

class SmsNotification
{
    protected SmsRenderer $renderer;
    protected SmsRecipients $recipients;
    protected bool $handleErrors;
    protected bool $multipleSms;

    public function __construct(
        SmsRenderer $renderer,
        SmsRecipients $recipients,
        ?bool $handleErrors = true,
        ?bool $multipleSms = false
    ) {
        $this->renderer = $renderer;
        $this->recipients = $recipients;
        $this->handleErrors = $handleErrors;
        $this->multipleSms = $multipleSms;
    }


    /**
     * @param array $recipients
     * @return void
     */
    public function addRecipients(array $recipients): void
    {
        foreach ($recipients as $recipient) {
            $this->recipients->add($recipient);
        }
    }


    public function hasRecipients(): bool
    {
        if ($_SERVER['ON_DEV']) {
            return true;
        }

        return !empty($this->recipients->get());
    }

    /**
     * @return string|null
     */
    public function sendMessage(): ?string
    {
        $error = null;
        try {
            if (count($this->recipients->get())) {
                $content = preg_replace(
                    '!\s+!',
                    ' ',
                    $this->renderer->renderMessage(Notification::RENDER_SMS)
                );

                $sms = new Sms();
                if ($this->multipleSms) {
                    $sms->setMultipleSms();
                }
                $sms->setContent($content);


                foreach ($this->recipients->get() as $smsNumber) {
                    $sms->setRecipientNumber($smsNumber);

                    try {
                        $sms->send();
                    } catch (Exception $e) {
                        if ($this->handleErrors && App::$di->has('flash')) {
                            App::$di['flash']->error(
                                Lang::get('GENERAL_SMS_FAILED_FOR') . $smsNumber . ': ' . $e->getMessage()
                            );
                        }
                    }
                }
            }
        } catch (Exception $ex) {
            $error = Lang::get('GENERAL_SMS_FAILED') . ' ' . $ex->getMessage();
        }

        return $error;
    }
}
