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

use function YOOtheme\App;
use YOOtheme\Arr;
use ZOOlanders\YOOessentials\Util;
use ZOOlanders\YOOessentials\Form\Http\FormSubmissionRequest;
use ZOOlanders\YOOessentials\Vendor\Respect\Validation\Validator;

return [
    'transforms' => [
        'render' => function (object $node, array $params) {
            /** @var FormSubmissionRequest $submission */
            $submission = app(FormSubmissionRequest::class);

            $controlName = $node->controls->select['name'];
            $controlProps = $node->controls->select['props'];
            $defaultValue = $controlProps['value'] ?? '';

            $fieldset = Util\Node::findClosestType($params, 'yooessentials_form_fieldset');

            if ($fieldset && !$fieldset->props['fields_show_label']) {
                $controlProps['label'] = '';
            }

            $node->control = (object) [
                'name' => $controlName,
                'id' => $controlProps['id'] ?? null,
                'errors' => $submission->validator()->errors($controlName) ?? [],
                'value' => Arr::wrap($submission->data($controlName) ?? $defaultValue),
                'props' => $controlProps,
            ];
        },
    ],

    'controls' => [
        'select' => function ($node) {
            $props = Util\Prop::filterByPrefix($node->props, 'control_');
            $options = array_map(function ($child) {
                return $child->props['value'] ?? '';
            }, $node->children);

            return compact('props', 'options');
        },
    ],

    'validation' => function ($control, Validator $validator) {
        $props = $control['props'];
        $multiple = $props['multiple'] ?? false;

        if ($props['required'] ?? false) {
            $validator->notOptional();
        }

        if (!$multiple) {
            return $validator;
        }

        if ($min = $props['min'] ?? false) {
            $validator->length($min);
        }

        if ($max = $props['max'] ?? false) {
            $validator->length(null, $max);
        }

        return $validator;
    },
];
