<?php

namespace Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes;

use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\ActionsAfterSubmit\ContactActionAfterSubmit;

class FormActionsLoader
{
    public function __construct()
    {
        \add_action('plugins_loaded', [$this, 'load']);
    }

    /**
     * @return void
     */
    public function load()
    {
        if (!Helper::isActive() || !defined('ELEMENTOR_PRO_VERSION')) {
            return;
        }

        if (version_compare(ELEMENTOR_PRO_VERSION, '3.5.0', '>=')) {
            add_action('elementor_pro/forms/actions/register', [$this, 'registerSince35'], 11);
        } else {
            add_action('elementor_pro/forms/register_action', [$this, 'registerBefore35'], 11);
        }
    }

    /**
     * @psalm-suppress UndefinedDocblockClass
     *
     * @param \ElementorPro\Modules\Forms\Registrars\Form_Actions_Registrar $actionsRegistrar
     *
     * @return void
     */
    public function registerSince35($actionsRegistrar)
    {
        foreach ($this->getActions() as $action) {
            $actionsRegistrar->register($action);
        }
    }

    /**
     * @psalm-suppress UndefinedDocblockClass
     *
     * @param \ElementorPro\Modules\Forms\Module $formsModule
     *
     * @return void
     */
    public function registerBefore35($formsModule)
    {
        foreach ($this->getActions() as $action) {
            $formsModule->add_form_action($action->get_name(), $action);
        }
    }

    /**
     * @return array
     */
    private function getActions()
    {
        return [
            new ContactActionAfterSubmit(),
        ];
    }
}
