<?php

namespace AppBundle\SMS;

use AppBundle\Entity\SMS;
use Psr\Log\LogLevel;
use Psr\Log\LoggerInterface;
//use SendinBlue\SendinBlueApiBundle\Wrapper\Mailin;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * Gestion des newsletter via le fournisseur SendinBlue
 * 
 * @see https://fr.sendinblue.com/ Official site
 */
class SMSSender
{
    //private $sender;
    private $logger;
    private $translator;
    private $flashBag;
    private $fromLabel;
    private $responses = [];
    private $successes = [];
    private $errors = [];

    /**
     * Constructor
     * 
     * @param Mailin $sender 
     * @param LoggerInterface $logger 
     * @param string $fromLabel 
     */
    public function __construct(
        // Mailin $sender,
        LoggerInterface $logger, 
        SessionInterface $session, 
        TranslatorInterface $translator, 
        string $fromLabel = null
    )
    {
        //$this->sender = $sender;
        $this->logger = $logger;
        $this->translator = $translator;
        $this->flashBag = $session->getFlashBag();
        $this->fromLabel = $fromLabel;
    }

    public function getResponses()
    {
        return $this->responses;
    }

    public function getSuccesses()
    {
        return $this->successes;
    }

    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Send a transactional SMS.
     *
     * @param SMS $sms
     * @param bool $displayFlashMessages Indicates if flash messages should be displayed after the SMS have been send
     * @param string $tag : The tag that you can associate with the message
     * @param string $callback : The web URL that can be called once the message is successfully delivered
     * @return mixed
     */
    public function sendSMS(SMS &$sms, bool $displayFlashMessages = false, $tag = null, $callback = null)
    {
        $data = [
            "from" => $this->fromLabel,
            "to" => $sms->getMobile(),
            "text" => $sms->getContent(),
            "web_url" => $callback, // Callback
            "tag" => $tag,
            "type" => "transactional"
        ];

        //$response = $this->sender->send_sms($data);

        // @see https://apidocs.sendinblue.com/fr/mailin-sms/#1
        // $response = array(
        //         "code" => "success",
        //         "message" => "Data retrieved",
        //         "data"=> [ 
        //             "status"=> "OK", 
        //             "number_sent"=> 1,
        //             "to"=> "00333333333333",
        //             "sms_count"=>  3,
        //             "credits_used"=> 13.5,
        //             "remaining_credit"=> 95.5, 
        //             "reference"=> [ "1" => "cz2tg3t9qn4tj9hpa" ]
        //         ],
        //         "msg_status"=> "sent"
        // );
        $this->responses[] = $response;

        $sms->setSendinblueApiReturn($response);
        $sms->setSendedDate(new \DateTime());


        // @see https://apidocs.sendinblue.com/fr/response/ && https://apidocs.sendinblue.com/fr/mailin-sms/#1
        if ('failure' === $response['code'] || 'success' === $response['code']) {
            if ('failure' === $response['code']) { // No sms have been send :(
                $this->errors[] = array_merge($response, ["recipient" => $sms->getUser()->getFirstname() . " " . $sms->getUser()->getLastname()]);

                $flashBagType = 'error';
                $logLevel = LogLevel::ERROR;
                $translationKey = 'notice.sms.sent.failure';
                $sms->setSended(SMS::STATE_ERROR);
            } else { // All SMS have been send :D
                $this->successes[] = array_merge($response, ["recipient" => $sms->getUser()->getFirstname() . " " . $sms->getUser()->getLastname() ]);
                
                $flashBagType = 'success';
                $logLevel = LogLevel::INFO;
                $translationKey = 'notice.sms.sent.success';
                $sms->setSended(SMS::STATE_SENDED);
            }

            if ( isset($response["data"]["reference"]["1"]) ) {
                $sms->setSendinblueRef($response["data"]["reference"]["1"]);
            }
            if ( isset($response["data"]["sms_count"]) ) {
                $sms->setSendinblueNbSms($response["data"]["sms_count"]);
            }
            if ( isset($response["data"]["credits_used"]) ) {
                $sms->setSendinblueCreditUsed($response["data"]["credits_used"]);
            }

            $logged_data = array_merge([
                'reference' => (isset($response["data"]["reference"]["1"]) ? $response["data"]["reference"]["1"] : ( isset($response["data"]["description"]) ? $response["data"]["description"] : "Unknow")),
                'response' => $response['message'],
            ], $data);

            // Log the API response
            $this->logger->log($logLevel, 'SMS ' . $response['code'], $logged_data);

            // Handle flash messages
            if ($displayFlashMessages) {
                $this->flashBag->add($flashBagType, $this->translator->transchoice(
                    $translationKey,
                    1,
                    ['%description%' => (isset($tag) ? "\"" . $tag . "\"" : "")],
                    'notice'
                ));
            }
        }

        return $data;
    }
}
