<?php

namespace RTMCustomMails\ContextBuilder;

use RTMCustomMails\Email\RTMCustomEmail;
use RTMMailComposer\ContextBuilder\ContextBuilderRegistry;
use RTMMailComposer\ContextBuilder\ContextBuilderInterface;
use RTMMailComposer\Model\CustomMail;

class WPContextBuilder implements ContextBuilderInterface
{

    public function __construct(protected ContextBuilderRegistry $registry = new ContextBuilderRegistry())
    {
        add_action('wrce_register_context_builders', [$this, 'addDefaultContextBuilders']);
    }

    public function addDefaultContextBuilders(ContextBuilderRegistry $registry)
    {
        $registry->registerContextBuilder(new OrderContextBuilder());
        $registry->registerContextBuilder(new UserContextBuilder());
        $registry->registerContextBuilder(new AdminContextBuilder());
        $registry->registerContextBuilder(new CustomerContextBuilder());
    }

    /**
     * @return ContextBuilderRegistry
     */
    public function getRegistry(): ContextBuilderRegistry
    {
        return $this->registry;
    }

    /**
     * Generates the generic base context
     * @param array $context The initial context
     * @param RTMCustomEmail $mail The mail to use for building base context
     *
     * @return array The initial context combined with the generated generic default context
     */
    public function defaultContext(array $context, RTMCustomEmail $mail): array
    {
        return $context + [
                $mail->getObjectType() => $mail->object,
                'email_heading' => $mail->get_heading(),
                'additional_content' => $mail->get_additional_content(),
                'sent_to_admin' => true,
                'plain_text' => false,
                'email' => $mail,
            ];
    }

    /**
     * @inheritDoc
     */
    public function prepareContext(CustomMail $mail, $mailObject, array $context = []): array
    {
        //builds a default context with the heading and other variables
        if ($mail instanceof RTMCustomEmail) {
            $context = $this->defaultContext($context, $mail);
        }

        // prepare object and recipient type context
        $context = $this->registry->prepareContext($mail, $mailObject, $context);

        /**
         * @hook wrce_prepare_context
         * @param array $context
         * @param RTMCustomEmail $mail
         * @param object $mailObject
         * @return array
         */
        return apply_filters("wrce_prepare_context", $context, $mail, $mailObject);
    }

    public function getSubject(): string
    {
        return '';
    }

    public function getWhitelist(): array
    {
        return [];
    }
}
