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

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

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

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

$field_obj = new Field($field);
$field_name = $field_obj->get_name();
$field_type = $field_obj->get_type();

$matching_api_field = null;
if (!empty($field_name)) {
    $matching_api_field = array_values(
        array_filter($field_options, function ($option) use ($field_name) {
            if (isset($option['name'])) {
                return $option['name'] === $field_name;
            }
            return false;
        }) ?? []
    )[0] ?? null;
}

if (!$matching_api_field && !empty($field_type)) {
    $matching_api_field = array_values(
        array_filter($field_options, function ($option) use ($field_type) {
            if (isset($option['name'])) {
                return $option['name'] === $field_type;
            }
            return false;
        }) ?? []
    )[0] ?? null;
}

if ($matching_api_field) {
    $field_data = $matching_api_field;
} elseif (!empty($field) && in_array($field_obj->get_type(), ['select', 'checkbox', 'radio']) && !empty($field_obj->get_raw_options())) {
    $options = $field_obj->get_options();
    $field_data = [
        'name' => $field_obj->get_name(),
        'label' => $field_obj->get_label(),
        'options' => $options,
        'filter' => [
            'range' => false
        ],
        'type' => $field_obj->get_type()
    ];
} else {
    $field_data = [
        'name' => $field_obj->get_name(),
        'label' => $field_obj->get_label(),
        'options' => [],
        'filter' => [
            'range' => false
        ],
        'type' => $field_obj->get_type() ?: 'text'
    ];
}

$field_name_for_input = $field_data['name'] ?? $field_obj->get_name();


$icon_check =
    $field_data['type'] !== 'radio'
        ? Icons::get_svg_icon('check', Icons::SHAPE_SHARP, Icons::STYLE_SOLID, 11, 10, '#FFF')
        : ''
?>
<div class="estatebud-field-group">
    <label class="estatebud-field-heading"><?php echo esc_html($field_obj->get_label()); ?></label>

    <?php if ($field_data['filter'] && $field_data['filter']['range'] && empty($field_data['options'])): ?>
        <div class="estatebud-field-range-wrapper">
            <?php Helper::render_markup_from_views('Public/partials/components/fields/input.php', [
                'type' => 'text',
                'value' => $field_obj->get_min_value(),
                'variable_name' => $field_name_for_input . '-min',
                'placeholder' => Helper::term('filters.min'),
            ]); ?>
            <?php Helper::render_markup_from_views('Public/partials/components/fields/input.php', [
                'type' => 'text',
                'value' => $field_obj->get_max_value(),
                'variable_name' => $field_name_for_input . '-max',
                'placeholder' => Helper::term('filters.max')
            ]); ?>
        </div>

    <?php elseif (in_array($field_data['type'] ?? '', ['checkbox', 'radio'])): ?>
        <?php
        $field_value = $field_obj->get_value();
        ?>

        <?php if (!empty($field_data['options'])): ?>
            <div class="flex-row">
                <?php foreach ($field_data['options'] as $option): ?>
                    <?php
                    $is_checked = false;
                    if (is_array($field_value)) {
                        $is_checked = in_array((string) $option['value'], array_map('strval', $field_value));
                    } elseif ($field_value !== null && $field_value !== '') {
                        $is_checked = (string) $option['value'] === (string) $field_value;
                    }
                    ?>
                    <label class="estatebud-custom-checkbox <?php echo esc_attr($field_data['type']); ?>">
                        <?php Helper::render_markup_from_views('Public/partials/components/fields/input.php', [
                            'type' => $field_data['type'] === 'radio' ? 'radio' : 'checkbox',
                            'name' => $field_name_for_input . ($field_data['type'] === 'checkbox' ? '[]' : ''),
                            'value' => $option['value'],
                            'checked' => $is_checked
                        ]); ?>
                        <span class="estatebud-checkbox-mark"><?php echo wp_kses($icon_check, Icons::get_kses_ruleset()); ?></span>
                        <span class="estatebud-option-label"><?php echo esc_html($option['label']); ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    <?php elseif (in_array($field_data['type'] ?? '', ['select']) || !empty($field_data['options'])): ?>
        <?php if ($field_data['filter'] && $field_data['filter']['range']): ?>
            <?php
            $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']
                ],
                $field_data['options']
            );

            $options_for_select_max = array_map(
                fn($option) => [
                    'value' => $option['value'],
                    'disabled' => false,
                    'selected' => (string) $option['value'] === (string) $max_value,
                    'label' => $option['label']
                ],
                $field_data['options']
            );
            ?>
            <div class="estatebud-field-range-wrapper">
                <?php
                Helper::render_markup_from_views('Public/partials/components/fields/select.php', [
                    'variable_name' => $field_name_for_input . '-min',
                    'placeholder' => Helper::term('filters.min'),
                    'options' => $options_for_select_min,
                    'multiple' => false
                ]);

                Helper::render_markup_from_views('Public/partials/components/fields/select.php', [
                    'variable_name' => $field_name_for_input . '-max',
                    'placeholder' => Helper::term('filters.max'),
                    'options' => $options_for_select_max,
                    'multiple' => false
                ]);
                ?>
            </div>
        <?php else: ?>
            <?php
            if ($field_obj->is_type('select') && $field_obj->get_name() === 'area') {
                $field_value = $field_obj->get_value();
                $options_for_select = [];
                $index_of_selected_values = count($field_data['options']) - 1;

                foreach ($field_data['options'] as $ind => $option) {
                    $depth = $option['depth'] ?? 0;
                    $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;
                    }
                    $is_higher_depth =
                        $ind > $index_of_selected_values &&
                        $depth > ($field_data['options'][$index_of_selected_values]['depth'] ?? 0);
                    $is_same_depth =
                        $ind > $index_of_selected_values &&
                        $depth === ($field_data['options'][$index_of_selected_values]['depth'] ?? 0);

                    if ($is_selected) {
                        if ($depth < ($field_data['options'][$index_of_selected_values]['depth'] ?? PHP_INT_MAX)) {
                            $index_of_selected_values = $ind;
                        }
                    } elseif ($is_higher_depth) {
                        $options_for_select[] = Helper::build_option($option, true, false, $depth);
                        continue;
                    } elseif ($is_same_depth) {
                        $index_of_selected_values = count($field_data['options']) - 1;
                    }

                    $options_for_select[] = Helper::build_option($option, false, $is_selected, $depth);
                }
            } else {
                $field_value = $field_obj->get_value();
                $is_area_field = $field_obj->is_type('select') && in_array($field_name_for_input, ['area[1]', 'area[2]', 'area[3]', 'area[4]', 'country']);
                
                $options_for_select = array_map(
                    function($option) use ($field_value, $is_area_field) {
                        $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 Helper::build_option(
                            $option,
                            $is_area_field && ($option['depth'] ?? 0) == 1,
                            $is_selected,
                            $option['depth'] ?? 0,
                            $option['group_count'] ?? 0
                        );
                    },
                    $field_data['options']
                );
            }

            $isMultiple = $field_obj->is_multiple();

            Helper::render_markup_from_views('Public/partials/components/fields/select.php', [
                'extra_class' => $isMultiple ? 'multiselect' : '',
                'multiple' => $isMultiple,
                'variable_name' => $field_name_for_input,
                'options' => $options_for_select,
                'placeholder' => $field_obj->get_placeholder()
            ]);
            ?>

        <?php endif; ?>
    <?php else: ?>
        <?php Helper::render_markup_from_views('Public/partials/components/fields/input.php', [
            'type' => 'text',
            'value' => $field_obj->get_value() ?? '',
            'variable_name' => $field_obj->get_name(),
            'extra_class' => 'width-100 estatebud-text-field',
            'placeholder' => $field_obj->get_placeholder()
        ]); ?>
    <?php endif; ?>
</div>