<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Form\Action;

use YOOtheme\Config;
use YOOtheme\Middleware;
use ZOOlanders\YOOessentials\Form\Http\FormSubmissionResponse;

class ActionListener
{
    private static $registered = false;

    public static function initCustomizer(Config $config, ActionManager $actionManager)
    {
        $actions = [];

        // get actions panels and options
        foreach ($actionManager->actions() as $name => $action) {
            $actions[$action->name()] = array_merge($action->panel(), [
                'name' => $action->name(),
                'title' => $action->title(),
            ]);
        }

        $config->set('customizer.yooessentials.form_actions', $actions);
    }

    /**
     * @param FormSubmissionResponse $response
     * @param callable $next
     */
    public static function handleFormActions($response, $next)
    {
        if (self::$registered) {
            return $next($response);
        }

        $form = $response->submission()->form();

        if ($form->hasExternalActionUrl()) {
            return $next($response);
        }

        $middleware = new Middleware(function () use ($next, $response) {
            return $next($response);
        }, $form->actions());

        self::$registered = true;

        /** @var FormSubmissionResponse $response */
        return $middleware($response);
    }
}
