<?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\Listener;

use YOOtheme\Arr;

class AddFormPanel
{
    public function handle($type)
    {
        // constraint types
        if (!in_array($type['name'], ['section', 'column', 'fragment'])) {
            return $type;
        }

        // make sure the main fieldset is set
        if (!Arr::has($type, 'fieldset.default')) {
            return $type;
        }

        $tabs = array_reduce(
            $type['fieldset']['default']['fields'],
            function ($carry, $v) {
                return array_merge($carry, [$v['title'] ?? null]);
            },
            []
        );

        if (($index = array_search('Advanced', $tabs)) === false) {
            return $type;
        }

        $statusField = [
            'type' => 'checkbox',
            'name' => 'yooessentials_form.state',
            'label' => 'Form',
            'text' => 'Enable as Form Area',
        ];

        $configButton = [
            'name' => '_yooessentials_form',
            'text' => 'Configuration',
            'type' => 'button-panel',
            'panel' => 'yooessentials-form-settings',
            'enable' => 'yooessentials_form.state',
            'description' => 'Enable this element as a Form Area, and set it submission configuration.',
        ];

        // set button right after status field
        Arr::splice($type['fieldset']['default']['fields'][$index]['fields'], 2, 0, [$statusField, $configButton]);

        return $type;
    }
}
