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

use EstatebudConnect\Utilities\Helper;
use EstatebudConnect\Configs\Icons;
use EstatebudConnect\Core\Cache;
use EstatebudConnect\Models\Field;
use EstatebudConnect\Services\Estatebud;

$icon_plus = Icons::get_svg_icon('plus', Icons::SHAPE_SHARP, Icons::STYLE_SOLID, 14, 14, '#6B6B6B');

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

$fields = $fields ?? [];
$id = $id ?? '';
$name = $name ?? '';
$type = $type ?? '';

$location_options = Estatebud::instance()->cache(Cache::TTL_5M)->get_property_areas();

$area_options_by_depth = Helper::extract_areas_by_depth($location_options);
$area_options_flattened = Helper::flatten_areas($location_options);

if (is_string($fields)) {
    $fields = json_decode(stripslashes($fields), true);
}

if (is_array($fields)) {
    foreach ($fields as $saved_search_exp_field) {
        $saved_field_obj = new Field($saved_search_exp_field);
        $saved_field_type = $saved_field_obj->get_type();
        $saved_field_name = $saved_field_obj->get_name();
        $is_area_field = ($saved_field_type === 'select') && in_array($saved_field_name, ['area[1]', 'area[2]', 'area[3]', 'area[4]', 'country']);
        
        if ($is_area_field) {
            $field_identifier = ($saved_field_name === 'country') ? 'area[1]' : $saved_field_name;
            preg_match('/\[(.*?)\]/', $field_identifier, $matches);
            $option_depth = isset($matches[1]) ? (int) $matches[1] : 0;
            $field_value = $saved_field_obj->get_value();
            $selected_area_option_value = is_array($field_value) ? $field_value : (($field_value !== null && $field_value !== '') ? [(string) $field_value] : []);

            $available_options = [];
            $index_of_parent = count($area_options_flattened) - 1;

            foreach ($area_options_flattened as $ind => $option) {
                if (in_array($option['value'], $selected_area_option_value)) {
                    $index_of_parent = $ind;

                    if (count($selected_area_option_value) > 1) {
                        $available_options[] = [
                            'value' => $option['value'],
                            'label' => $option['label'],
                            'depth' => 1,
                            'group_count' => count($selected_area_option_value) ?? 0
                        ];
                    }
                }

                if (
                    $ind > $index_of_parent &&
                    $area_options_flattened[$index_of_parent]['depth'] === $option['depth']
                ) {
                    $index_of_parent = count($area_options_flattened) - 1;
                }

                if (
                    $ind > $index_of_parent &&
                    $area_options_flattened[$index_of_parent]['depth'] === $option['depth'] - 1
                ) {
                    $available_options[] = [
                        'value' => $option['value'],
                        'label' => $option['label'],
                        'depth' => 2,
                        'group_count' => count($selected_area_option_value) ?? 0
                    ];
                }
            }

            foreach ($options as &$option) {
                if (!isset($option['name'])) {
                    continue;
                }
                if ($option['name'] === 'area[' . ($option_depth + 1) . ']') {
                    $option['options'] = $available_options;
                }

                if ($option['name'] === 'area[1]') {
                    $option['options'] = $area_options_by_depth[0];
                }

                if ($option['name'] === 'area') {
                    $option['options'] = $area_options_flattened;
                }
            }
            unset($option);
        }
    }
}
?>

<div class="estatebud-modal-wrapper">
    <form class="estatebud-modal estatebud-modal-general-form search-exp-modal-form" name="search-exp-modal-form">
        <?php Helper::render_markup_from_views('Admin/modal/modal-header.php', [
            'modal_title' => $id ? 'Update search experience' : 'Create search experience'
        ]); ?>
        <div class="etatebude-modal-content">
            <div class="estatebud-modal-content-panel">
                <?php Helper::render_markup_from_views('Admin/modal/partials/modal-content-panel-title.php', [
                    'panel_title' => 'Settings'
                ]); ?>
                <div class="estatebud-modal-content-panel">
                    <div class="estatebud-field-group">
                        <div class="estatebud-field-label">
                            <?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' => $name ?? '',
                            'variable_name' => 'name'
                        ]); ?>
                    </div>
                    <div class="estatebud-field-group">
                        <div class="estatebud-field-label">
                            <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                                'field_label' => 'Module'
                            ]); ?>
                        </div>
                        <?php Helper::render_markup_from_views('Admin/partials/select-field.php', [
                            'extra_class' => 'module-field-forms-tab form-type-selector',
                            'variable_name' => 'type',
                            'options' => [
                                [
                                    'value' => 'property-search',
                                    'disabled' => false,
                                    'selected' => $type == 'property-search',
                                    'label' => 'Property search'
                                ],
                                [
                                    'value' => 'project-search',
                                    'disabled' => false,
                                    'selected' => $type == 'project-search',
                                    'label' => 'Project search'
                                ]
                            ]
                        ]); ?>
                    </div>
                </div>
                <div class="sep"></div>
            </div>

            <div class="estatebud-modal-content-panel estatebud-modal-form-group-property">
                <?php Helper::render_markup_from_views('Admin/modal/partials/modal-content-panel-title.php', [
                    'panel_title' => 'Filters'
                ]); ?>
                <div class="estatebud-modal-field-group-wrapper">
                <?php if (is_array($fields)):
                    foreach ($fields as $index => $field):
                        ?>
                        <div class="estatebud-search-exp-field-group" draggable="true" name="draggable" id="draggable-<?php echo esc_attr($index); ?>">
                            <?php
                            Helper::render_markup_from_views('Admin/partials/search-exp-field-settings.php', [
                                'field' => $field,
                                'options' => $options,
                                'type' => $type
                            ]); ?>
                        </div>
                    <?php endforeach;
                else:
                    echo 'Invalid fields data.';
                endif; ?>
                </div>
                <button class="estatebud-modal-button-variation-2" id="add-search-exp-field-group-button">
                    <?php echo wp_kses($icon_plus, Icons::get_kses_ruleset()); ?>
                    <div class="estatebud-button-title">Add item</div>
                </button>
            </div>

            <div style="display: none;">
                <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                    'value' => $id,
                    'variable_name' => 'id'
                ]); ?>
            </div>
            <div class="sep"></div>
        </div>
        <?php Helper::render_markup_from_views('Admin/modal/modal-footer.php'); ?>
    </form>
</div>