<?php
/** 
 * @package     VikRestaurants
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2023 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

namespace E4J\VikRestaurants\Cron\Traits;

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

use E4J\VikRestaurants\Mail\MailTemplateAware;

/**
 * Helper trait used to deliver mail templates.
 * 
 * @since 1.10
 */
trait NotificationMailDispatcher
{
    /**
     * Delivers the mail template.
     * 
     * @param   array|string       $recipients
     * @param   MailTemplateAware  $mailTemplate
     * 
     * @return  void
     * 
     * @throws  \Exception
     */
    protected function sendNotification($recipients, MailTemplateAware $mailTemplate)
    {
        if (!$recipients)
        {
            // missing e-mail recipient
            throw new \InvalidArgumentException('Missing e-mail recipient.', 400);
        }

        // obtain mail instance from template
        $mail = $mailTemplate->getMail();

        // add recipients one by one to preserve the default ones
        foreach ((array) $recipients as $recipient)
        {
            $mail->addRecipient($recipient);
        }

        // attempt to deliver the e-mail
        $sent = (new \E4J\VikRestaurants\Mail\MailDeliverer)->send($mail);

        if (!$sent)
        {
            // an error has occurred
            throw new \UnexpectedValueException(sprintf('An error occurred while sending the e-mail notification to: %s.', implode(', ', (array) $recipients)), 500);
        }
    }
}
