<?php

namespace common\components\BulkMailer;

use common\helpers\Mailjet;
use Mailjet\Client;

class BulkMailerMailjet implements BulkMailerInterface
{
    public function sendEmails(array $contactsArray, string $fromName, string $fromEmail, string $subject, string $htmlContent, string $textContent = null)
    {
        $client = new Client(
            Mailjet::getApiKey('public'),
            Mailjet::getApiKey('private'),
            true,
            ['version' => 'v3.1']
        );

        $data = ['Messages' => []] ;

        foreach($contactsArray as $user) {
            $data['Messages'][] = [
                'From' => [
                    'Email' => $fromEmail,
                    'Name' => $fromName
                ],
                'To' => [
                    [
                        'Email' => $user['email'],
                        'Name' => $user['name'].' '.$user['lastname']
                    ]
                ],
                'Subject' => $subject,
                'HTMLPart' => $htmlContent,
                'TextPart' => $textContent
            ] ;

            if(count($data['Messages']) == 50) {
                $this->requestPostEmailViaApi($client, $data);
                $data['Messages'] = [] ;
            }
        }

        if(count($data['Messages']) > 0) {
            $this->requestPostEmailViaApi($client, $data);
        }
    }

    public function requestPostEmailViaApi(Client $client, array $data)
    {
        $client->post(\Mailjet\Resources::$Email, ['body' => $data]);
    }
}