<?php

namespace AppBundle\Mail;

use SendinBlue\Client\Configuration;
use SendinBlue\Client\ApiException;
use SendinBlue\Client\HeaderSelector;
use SendinBlue\Client\ObjectSerializer;
use SendinBlue\Client\Api\TransactionalEmailsApi;
use SendinBlue\Client\Model\SendSmtpEmail;
use SendinBlue\Client\Model\CreateContact;
use SendinBlue\Client\Api\ContactsApi;
use GuzzleHttp\Client;

use Psr\Log\LogLevel;
use Psr\Log\LoggerInterface;

class Mailer {

    /**
     * @var string
     */
    private $api_key;

    private $sender_name;
    
    private $sender_email;

    private $config;

    /**
     * @var LoggerInterface
     */
    private $logger;


    public function __construct(string $api_key, string $sender_name, string $sender_email, LoggerInterface $logger ) {
        

        $this->api_key = $api_key;
        $this->sender_name = $sender_name;
        $this->sender_email = $sender_email;
        $this->logger = $logger;

        // Configure API key authorization: api-key
        $this->config = Configuration::getDefaultConfiguration()->setApiKey('api-key', $this->api_key);
    }

    public function send_email($message) {

        $apiInstance = new TransactionalEmailsApi (
            new Client(),
            $this->config
        );
        
        $tos = $message['to'];
        $recipients = [];
        foreach($tos as $email => $name) {
            if(is_null($name)){
                $name = $email;
            }
            $recipients[] = ['email' => $email, 'name' => $name];
        }

        $sendSmtpEmail = new SendSmtpEmail(); // \SendinBlue\Client\Model\SendSmtpEmail | Values to send a transactional email
        $sendSmtpEmail['sender'] = ['email' => $this->sender_email, 'name' => $this->sender_name]; 
        $sendSmtpEmail['to'] = $recipients;
        $sendSmtpEmail['replyTo'] = ['email' => $message['from'][0], 'name' => $message['from'][1]];
        $sendSmtpEmail['subject'] = $message['subject'];;
        $sendSmtpEmail['htmlContent'] = $message['html'];
        $sendSmtpEmail['textContent'] = $message['text'];
        $sendSmtpEmail['headers'] = $message['headers'];
        $sendSmtpEmail['attachment'] = $message['attachment'];
        
        
        try {
            $result = $apiInstance->sendTransacEmail($sendSmtpEmail);
            return $result;
        } catch (Exception $e) {
            $logLevel = LogLevel::ERROR;
            $this->logger->log($logLevel, 'Mailer ' , array_merge([
                'description' => "MAILER",
                'response' => "API KEY : " .  $this->api_key,
            ], [$e->getMessage()]));

            return false;
        }
    }

    public function create_update_user($data) {
        $apiInstance = new ContactsApi(
            new Client(),
            $this->config
        );
        $createContact = new CreateContact();
        $createContact['email'] = $data['email'];
        $createContact['listIds'] = $data['listid'];
        $createContact['attributes'] = $data['attributes'];
        $createContact['emailBlacklisted'] = $data['blacklisted'];
        $createContact['smsBlacklisted'] = $data['blacklisted_sms'];
        
        try {
            $result = $apiInstance->createContact($createContact);
            $this->logger->log(LogLevel::INFO, 'Mailer ' , ['RESPONSE' => json_encode( $result)]);
            return ['code' => 'success'];
        } catch (ApiException $e) {
            $this->logger->log(LogLevel::ERROR, 'Mailer ' , ['ERROR' => json_encode($e->getMessage())]);
            return false;
            
        }
    }
}
