<?php

namespace Mnv\Modules;

use Mnv\Core\Utilities\Curl\Curl;

/**
 * Отправка смс
 *
 * Class SmsGateway
 * @package Mnv\Models
 */
class SmsGateway
{
    /**
     * @var $sendUrl
     */
    private $sendUrl;

    /**
     * @var $smsLogin
     */
    private $smsLogin;

    /**
     * @var $smsPass
     */
    private $smsPass;

    /**
     * SmsGateway constructor.
     *
     * @param $sendUrl
     * @param $smsLogin
     * @param $smsPass
     */
    public function __construct($sendUrl, $smsLogin, $smsPass)
    {
        $this->sendUrl  = $sendUrl;
        $this->smsLogin = $smsLogin;
        $this->smsPass  = $smsPass;
    }

    /**
     * @param $phone
     * @return array|string|string[]|null
     */
    public function formatPhoneNumber($phone)
    {
        $phone = preg_replace('/[^0-9]/', '', $phone);
        return preg_replace('/([0-9]{3})([0-9]{2})([0-9]{3})([0-9]{2})([0-9]{2})/', '+$1 ($2) $3-$4-$5', $phone);
    }

    /**
     *  Отправка смс с кодом активации
     *
     * @param string $number @номер телефона
     * @param string $text @текст отправляемый в смс
     * @return bool
     */
    public function sendSms(string $number, string $text): bool
    {
        $postData = array(
            'messages' => array(
                0 => array(
                    'recipient' => $number,
                    'message-id' => 'abc'.sprintf('%017d', rand(1, 99999999999999999)),
                    'sms' => array(
                        'originator' => '3700',
                        'content' => array(
                            'text' => $text
                        )
                    )
                )
            )
        );

        $data = $this->requestCurl($postData);
        return $data == 'Request is received';
    }

    /**
     * Curl Отправка и получение ответа server
     *
     * @param $postData
     * @return string|null
     */
    private function requestCurl($postData): ?string
    {
        $curl = new Curl();
        $curl->setBasicAuthentication($this->smsLogin, $this->smsPass); // логин и пароль
        $curl->setHeader('Content-Type', 'application/json');
        $curl->post($this->sendUrl, $postData);
        if ($curl->error) {
            $curl->response = 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage;
        }

        return $curl->response;
    }


}