<?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\Templates\Miscellaneous\RuntimeMailTemplate;

/**
 * Generic mail template builder.
 * 
 * @since 1.10
 */
trait NotificationMailBuilder
{
    /**
     * Constructs a template boilerplate for e-mail notifications.
     * 
     * @param   string      $langtag  The preferred language tag.
     * @param   \JRegistry  $args     A registry holding the cron parameters.
     * @param   int         $id       An optional unique number to identify the e-mail template.
     * 
     * @return  E4J\VikRestaurants\Mail\MailTemplateAware
     * 
     * @throws  \Exception
     */
    protected function createMailTemplate(string $langtag, \JRegistry $args, int $id = 0)
    {
        // create an abstract class to handle a generic e-mail template
        return new class($langtag, $args, $id) extends RuntimeMailTemplate
        {
            /**
             * Class constructor.
             */
            public function __construct(string $langtag, \JRegistry $args, int $id)
            {
                // use default language if not specified
                $langtag = $langtag ? $langtag : \VikRestaurants::getDefaultLanguage();

                // reload the language according to the preferences of the user
                \VikRestaurants::loadLanguage($langtag, JPATH_SITE);

                $lang = substr($langtag, 0, 2);

                $options = [
                    // obtain subject and template from cron arguments
                    'subject' => $args->get('mail_subject_' . $lang, ''),
                    'template' => $args->get('mail_content_' . $lang, ''),
                    // copy language tag
                    'lang' => $langtag,
                    // add template identifier
                    'id' => 'cronjob.mail.' . $id,
                ];

                // prepare text to properly interpret included plugins
                \VREApplication::getInstance()->onContentPrepare($options['template']);
                $options['template'] = $options['template']->text;

                // construct class through parent
                parent::__construct($options);

                // use global sender
                $this->attachMailDecorator(new \E4J\VikRestaurants\Mail\Decorators\SenderMailDecorator);

                // inject generic company information, such as the restaurant name and the image logo
                $this->attachTemplateDecorator(new \E4J\VikRestaurants\Template\Decorators\CompanyDecorator);
            }
        };
    }
}
