<?php

require './vendor/autoload.php';

use \SendGrid\Mail\To;
use \SendGrid\Mail\Mail;
use \SendGrid\Mail\From;
use \SendGrid\Mail\HtmlContent;
use \SendGrid\Mail\Personalization;

class SendGridService {
	public static function sendEmail($email) {
		global $savvyext;

		$apiKey = $savvyext->cfgReadChar('mailsend.api_key');
		$sg = new \SendGrid($apiKey);

		$response = $sg->send($email);
		return $response;
	}

	public static function prepareSengridToObject($receiver = [], $substitutions = NULL) {
		return new \SendGrid\Mail\To(
			$receiver['email'],
			$receiver['firstname'] ?? '',
			$substitutions ?? NULL
		);
	}

	public static function prepareEmail($receivers, $subject, $template, $globalSubstitutions) {
		global $savvyext;

		$fromEmail = $savvyext->cfgReadChar('mailsend.from');
		$fromName = $savvyext->cfgReadChar('mailsend.name');

		$email = new Mail(
			new From($fromEmail, $fromName),
			NULL,
			$subject, // or array of subjects, these take precendence
			$plainTextContent ?? NULL,
			new HtmlContent($template),
			$globalSubstitutions ?? NULL
		);

		foreach($receivers as $receiver) {
			$personalization = SendGridService::createPersonalize($receiver);
			$email->addPersonalization($personalization);
		}

		return $email;
	}

	public static function createPersonalize($to) {
		$personalize = new Personalization();
		$personalize->addTo($to);

		return $personalize;
	}
}