<?php

namespace RTMCustomMails\EmailOptions;

use RTMCustomMails\Email\RTMCustomEmail;

class TriggerHooksOption extends AbstractEmailOption
{

    public function addOption(array $formFields)
    {
        $instance = RTMCustomEmail::asCustomEmail($this->email);
        $defaultTriggers = $instance->getTriggerHooks();
        if (!$instance->get_option('trigger_hooks')) {
            $instance->update_option('trigger_hooks', $defaultTriggers);
        }

        $hooks = apply_filters('wrce_email_trigger_hook_options', [], $instance);
        $hooks = apply_filters('wrce_email_trigger_hook_options/email_id=' . $instance->id, $hooks, $instance);
        $hooks = apply_filters('wrce_email_trigger_hook_options/object_type=' . $instance->getObjectType(), $hooks, $instance);

        foreach ($hooks as $group => $array) {
            if (is_array($array)) {
                continue;
            }

            // set the trigger to an empty named group.
            $hooks[''][$group] = $array;
            unset($hooks[$group]);
        }

        $formFields['trigger_hooks'] = [
            'title' => __('Trigger Hooks', 'wrce'),
            'description' => __('This email will sent when specific event(s) occurs.', 'wrce'),
            'type' => 'multiselect',
            'default' => apply_filters('wrce_email_trigger_hooks', $defaultTriggers, $instance),
            'options' => $hooks
        ];

        return $formFields;
    }
}