<?php
if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Utilities\Helper;
use EstatebudConnect\Configs\Icons;
use EstatebudConnect\Configs\Defaults;
use EstatebudConnect\Models\Field;

$icon_cross = Icons::get_svg_icon('xmark-large', Icons::SHAPE_SHARP, Icons::STYLE_SOLID, 16, 16, '#858585');

if (empty($group_title)) {
    $group_title = '';
}

if (!isset($options)) {
    $options = [];
}

if (isset($options) && !is_array($options)) {
    $options = array_values($options);
}

if (!isset($field) || !is_array($field)) {
    $field = [];
}

$field_obj = new Field($field);
$field_name = $field_obj->get_name();
$field_type = $field_obj->get_type();
$has_custom_options = !empty($field_obj->get_raw_options());
$is_custom_field_type = in_array($field_type, Defaults::CUSTOM_FIELD_TYPES, true);
$default_option = ['name' => 'any', 'type' => 'text', 'options' => [], 'filter' => ['range' => false]];

$selected_option =
    array_values(array_filter($options, fn($option) =>
        isset($option['name']) &&
        (
            (!empty($field_name) && $option['name'] === $field_name && !$has_custom_options && !$is_custom_field_type) ||
            (!empty($field_type) && $option['name'] === $field_type && !$is_custom_field_type)
        )
    ))[0] ??
    $default_option;

$is_api_field = $selected_option['name'] !== 'any';
$is_custom_field = !$is_api_field && in_array($field_obj->get_type(), Defaults::CUSTOM_FIELD_TYPES, true);
?>

<div class="estatebud-field-settings">
    <div class="estatebud-accordion-secondary-group">
        <div class="estatebud-accordion-name-group">
            <p class="estatebud-accordion-name"><?php echo esc_html($group_title); ?></p>
        </div>
        <div class="estatebud-accordion-cross-group">
            <?php echo wp_kses($icon_cross, Icons::get_kses_ruleset()); ?>
        </div>
    </div>

    <div class="estatebud-accordion-group" style="display: none">
        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Field',
                ]); ?>
            </div>
            <?php
            $has_custom_options = !empty($field_obj->get_raw_options());
            $field_name = $field_obj->get_name();
            
            $is_custom_field_type = in_array($field_obj->get_type(), Defaults::CUSTOM_FIELD_TYPES, true);
            $selectOptions = array_map(
                function($option) use ($field_obj, $has_custom_options, $field_name, $is_custom_field_type) {
                    $isApiFieldByName = !empty($field_name) && $field_name === $option['name'] && !$has_custom_options && !$is_custom_field_type;
                    $isTypeMatch = $field_obj->get_type() == $option['name'] && !$is_custom_field_type;
                    $isSelected = $isApiFieldByName || $isTypeMatch;
                    
                    return [
                        'value' => $option['name'],
                        'disabled' => false,
                        'selected' => $isSelected,
                        'label' => $option['label'],
                    ];
                },
                $options,
            );

            $customOptions = [
                [
                    'value' => 'text',
                    'label' => 'Text',
                    'disabled' => false,
                    'selected' => !$is_api_field && $field_obj->is_type('text'),
                ],
                [
                    'value' => 'textarea',
                    'label' => 'Textarea',
                    'disabled' => false,
                    'selected' => !$is_api_field && $field_obj->is_type('textarea'),
                ],
            ];

            Helper::render_markup_from_views('Admin/partials/select-for-field-settings.php', [
                'extra_class' => 'custom-width estatebud-accordion-select',
                'variable_name' => 'type',
                'options' => $selectOptions,
                'custom_options' => $customOptions,
            ]);
            ?>
        </div>
        <div class="estatebud-field-group search-exp-custom-name-group" style="<?php echo $is_custom_field ? 'display: flex' : 'display: none'; ?>">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Name',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                'value' => $field_obj->get_name(),
                'variable_name' => 'name',
            ]); ?>
        </div>
        <?php if ($selected_option): ?>
            <div class="estatebud-field-group search-exp-value-group">
                <div class="estatebud-field-label estatebud-width-120">
                    <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                        'field_label' => 'Value',
                    ]); ?>
                </div>

                <?php if ($selected_option['filter'] && $selected_option['filter']['range']): ?>
                    <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                        'value' => $field_obj->get_min_value(),
                        'variable_name' => 'minvalue',
                    ]); ?>
                    <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                        'value' => $field_obj->get_max_value(),
                        'variable_name' => 'maxvalue',
                    ]); ?>

                <?php elseif ($field_obj->is_type('select')): ?>
                    <?php if (
                        isset($selected_option['filter']) &&
                        $selected_option['filter'] &&
                        $selected_option['filter']['range']
                    ) {
                        $min_value = $field_obj->get_min_value();
                        $max_value = $field_obj->get_max_value();
                        
                        $options_for_select_min = array_map(
                            fn($option) => [
                                'value' => $option['value'],
                                'disabled' => false,
                                'selected' => (string) $option['value'] === (string) $min_value,
                                'label' => $option['label'],
                            ],
                            $selected_option['options'],
                        );

                        $options_for_select_max = array_map(
                            fn($option) => [
                                'value' => $option['value'],
                                'disabled' => false,
                                'selected' => (string) $option['value'] === (string) $max_value,
                                'label' => $option['label'],
                            ],
                            $selected_option['options'],
                        );

                        Helper::render_markup_from_views('Admin/partials/select-field.php', [
                            'variable_name' => 'minvalue',
                            'options' => $options_for_select_min,
                        ]);

                        Helper::render_markup_from_views('Admin/partials/select-field.php', [
                            'variable_name' => 'maxvalue',
                            'options' => $options_for_select_max,
                        ]);
                    } else {
                        $field_value = $field_obj->get_value();
                        
                        if ($selected_option['name'] === 'area') {
                            $options_for_select = [];
                            $index_of_selected_values = count($selected_option['options']) - 1;

                            foreach ($selected_option['options'] as $ind => $option) {
                                $is_selected = false;
                                if (is_array($field_value)) {
                                    $is_selected = in_array((string) $option['value'], array_map('strval', $field_value));
                                } elseif ($field_value !== null && $field_value !== '') {
                                    $is_selected = (string) $option['value'] === (string) $field_value;
                                }

                                $options_for_select[] = [
                                    'value' => $option['value'],
                                    'disabled' => false,
                                    'selected' => $is_selected,
                                    'label' => $option['label'],
                                ];
                            }
                        } else {
                            $options_for_select = array_map(function ($option) use ($field_value) {
                                $is_selected = false;
                                if (is_array($field_value)) {
                                    $is_selected = in_array((string) $option['value'], array_map('strval', $field_value));
                                } elseif ($field_value !== null && $field_value !== '') {
                                    $is_selected = (string) $option['value'] === (string) $field_value;
                                }
                                return [
                                    'value' => $option['value'],
                                    'disabled' => false,
                                    'selected' => $is_selected,
                                    'label' => $option['label'],
                                ];
                            }, $selected_option['options'] ?? []);
                        }

                        Helper::render_markup_from_views('Admin/partials/select-field.php', [
                            'extra_class' => 'multiselect',
                            'multiple' => true,
                            'variable_name' => 'value',
                            'options' => $options_for_select,
                        ]);
                    } ?>
                <?php else: ?>
                    <?php if ($is_custom_field && $field_obj->is_type('textarea')): ?>
                        <?php Helper::render_markup_from_views('Admin/partials/textarea-field.php', [
                            'textarea_content' => $field_obj->get_value() ?? '',
                            'variable_name' => 'value',
                            'rows' => 4,
                            'cols' => 67,
                             'extra_class' => 'width-100',
                        ]); ?>
                    <?php else: ?>
                        <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                            'value' => $field_obj->get_value() ?? '',
                            'variable_name' => 'value',
                            'extra_class' => 'width-100',
                        ]); ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        
    </div>
</div>