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

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

if (!isset($is_favorites)) {
    $is_favorites = false;
}

if (!isset($listings_type)) {
    $listings_type = 'property';
}

if (!isset($form)) {
    $form = '';
}

if (!isset($search_id)) {
    $search_id = '';
}

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

if (!isset($widget_mode)) {
    $widget_mode = 'false';
}

if (!isset($shortcode_id)) {
    $shortcode_id = '';
}
if (!isset($settings_data)) {
    $settings_data = [];
}

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

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

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

if (!isset($form_data)) {
    $form_data = null;
}

extract($settings_data);

if (!isset($icon_type)) {
    $icon_type = Icons::SHAPE_SHARP;
}

if (!isset($icon_style)) {
    $icon_style = Icons::STYLE_SOLID;
}

$icon_down_arrow = Icons::get_svg_icon('caret-down', Icons::SHAPE_SHARP, Icons::STYLE_SOLID, 8, 12, '#B8B8B8');
$icon_reset_button = Icons::get_svg_icon('arrow-rotate-left', $icon_type, $icon_style, 18, 18, '#6B6B6B');
$icon_map = Icons::get_svg_icon('map-location-dot', $icon_type, $icon_style, 18, 18, '#ffffff');

$search_exp_fields = $search_exp_data['fields'] ?? [];

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

$search_exp_from_link = [];

if ($query_from_link) {
    foreach ($query_from_link as $key => $value) {
        $parsed_key_array = explode('-', $key);

        if (strpos($parsed_key_array[0], 'area') !== false && count($parsed_key_array) === 2) {
            $key_of_query = 'area' . '[' . $parsed_key_array[1] . ']';
            $value_array = is_string($value) && strpos($value, '|') !== false 
                ? array_map('trim', explode('|', $value))
                : $value;
            $search_exp_from_link[] = [
                'type' => $key_of_query,
                'value' => $value_array,
            ];
        } elseif (count($parsed_key_array) === 2) {
            $key_of_query = $parsed_key_array[0];

            $filter_result = array_filter($search_exp_from_link, function ($ele) use ($key_of_query) {
                return $ele['type'] === $key_of_query;
            });

            if (count($filter_result)) {
                $ind = array_key_first($filter_result);
                $search_exp_from_link[$ind]['value'] = $value;
            } else {
                $search_exp_from_link[] = [
                    'type' => $key_of_query,
                    'value' => $value,
                ];
            }
        } else {
            $value_array = is_string($value) && strpos($value, '|') !== false 
                ? array_map('trim', explode('|', $value))
                : $value;
            $search_exp_from_link[] = [
                'type' => $parsed_key_array[0],
                'value' => $value_array,
            ];
        }
    }
}

if (is_array($search_exp_from_link) && is_array($search_exp_fields)) {
    $search_exp_fields = array_merge($search_exp_fields, $search_exp_from_link);
}

if (is_array($search_exp_fields)) {
    foreach ($search_exp_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'],
                        ];
                    }
                }

                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'],
                    ];
                }
            }

            foreach ($field_options as &$option) {
                if (isset($option['name'])) {
                    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;
                    }
                }
            }
        }
    }
}

foreach ($field_options as &$option) {
    if (isset($option['name'])) {
        if ($option['name'] === 'area[1]') {
            $option['options'] = $area_options_by_depth[0];
        }

        if ($option['name'] === 'area') {
            $option['options'] = $area_options_flattened;
        }
    }
}
$fields = $form_data['fields'] ?? [];
$normal_fields = [];
$advanced_fields = [];

$form_type = $form_data['type'] ?? '';
$space_consumption = 0;

foreach ($fields as &$field) {
    $field_obj = new Field($field);

    $matched_search_exp_field = array_values(
        array_filter($search_exp_fields, function ($search_exp) use ($field_obj) {
            $field_name = $field_obj->get_name();
            $search_exp_obj = new Field($search_exp);
            $search_exp_name = $search_exp_obj->get_name();
            
            return !empty($field_name) && !empty($search_exp_name) && $search_exp_name === $field_name;
        }),
    );

    if (!empty($matched_search_exp_field)) {
        $matched_search_exp_field_obj = new Field($matched_search_exp_field[0]);
        $filtered_options = array_values(
            array_filter($field_options, function ($option) use ($matched_search_exp_field_obj) {
                return isset($option['name']) && $option['name'] === $matched_search_exp_field_obj->get_name();
            }),
        );

        if (!empty($filtered_options)) {
            $matched_field_option = $filtered_options[0];
            $filter_data = $matched_field_option['filter'] ?? [];

            if (in_array($matched_field_option['type'], ['select'])) {
                if ($filter_data && $filter_data['range']) {
                    $field['minvalue'] = $matched_search_exp_field_obj->get_min_value();
                    $field['maxvalue'] = $matched_search_exp_field_obj->get_max_value();
                } else {
                    $field['value'] = $matched_search_exp_field_obj->get_value();
                }
            } elseif ($matched_field_option['type'] == 'number') {
                if ($filter_data && $filter_data['range']) {
                    $field['minvalue'] = $matched_search_exp_field_obj->get_min_value();
                    $field['maxvalue'] = $matched_search_exp_field_obj->get_max_value();
                } else {
                    $field['value'] = $matched_search_exp_field_obj->get_value();
                }
            } else {
                $field['value'] = $matched_search_exp_field_obj->get_value();
            }
        }
    }
    
    if ($field_obj->is_advanced()) {
        $advanced_fields[] = $field;
    } else {
        $normal_fields[] = $field;
    }
}
unset($field);

if (empty($search_id)) {
    $button_icon = '';
    if (isset($form_data) && isset($form_data['button_icon_type']) && $form_data['button_icon_type']) {
        $button_icon = Icons::get_svg_icon(
            $form_data['button_icon_type'],
            Icons::SHAPE_SHARP,
            Icons::STYLE_SOLID,
            18,
            18,
            '#ffffff',
        );
    }

    $buttonDetail = [
        'icon' => $button_icon,
        'title' => $form_data['button_label'] ?? '',
        'name' => 'form-button',
        'icon_position' => $form_data['button_icon_position'] ?? 'left',
        'destination_url' => get_page_link($form_data['button_destination_page'] ?? ''),
    ];
} else {
    $map_provider = $settings_data['map_provider'] ?? '';

    if (!empty($map_provider)) {
        $buttonDetail = [
            'icon' => $icon_map,
            'title' => Helper::term('listings.button.toggle_map'),
            'name' => 'toggle-map',
            'icon_position' => 'left',
            'destination_url' => '',
        ];
    } else {
        $buttonDetail = null;
    }
}
?>
<div class="estatebud-filter-group-wrapper" style="<?php echo $widget_mode === 'true' || !count($fields)
    ? 'display: none'
    : ''; ?>" data-shortcode-id="<?php echo esc_attr($shortcode_id); ?>">
  <div class="estatebud-filter-group-container">
    <div class="estatebud-filter-group">
      <?php foreach ($normal_fields as $field): ?>
      <?php
      $field_obj = new Field($field);
      $field_type_for_attr = $field_obj->get_type();
      if ($field_obj->get_name() && !empty($field_options)) {
          $matching_api_field = array_values(
              array_filter($field_options, function ($option) use ($field_obj) {
                  return isset($option['name']) && $option['name'] === $field_obj->get_name();
              })
          );
          if (!empty($matching_api_field)) {
              $field_type_for_attr = $field_obj->get_name();
          }
      }
      $is_conditional = $field_obj->is_conditional();
      ?>
      <div class="estatebud-filter-field-wrapper<?php echo $is_conditional ? ' conditional-field' : ''; ?>"
        id="<?php echo esc_attr(sprintf('filter-%s-%s', $field_obj->get_id(), $shortcode_id)); ?>"
        data-shortcode-id="<?php echo esc_attr($shortcode_id); ?>"
        data-field-id="<?php echo esc_attr($field_obj->get_id()); ?>"
        data-field-type="<?php echo esc_attr($field_type_for_attr); ?>"
        <?php if ($is_conditional): ?>
        data-conditional-field="<?php echo esc_attr($field_obj->get_conditional_field()); ?>"
        data-conditional-value="<?php echo esc_attr($field_obj->get_conditional_value()); ?>"
        <?php endif; ?>>
        <label class="estatebud-filter-field-label"><?php echo esc_html($field_obj->get_label()); ?></label>
        <label class="estatebud-filter-field-icon"><?php echo wp_kses($icon_down_arrow, Icons::get_kses_ruleset()); ?></label>
        <div class="estatebud-more-filters-form estatebud-hidden" id="<?php echo esc_attr(sprintf('dropdown-%s-%s,', $field_obj->get_id(), $shortcode_id)); ?>">
          <?php Helper::render_markup_from_views('Public/partials/components/search-fields-group.php', [
              'field' => $field,
              'field_options' => $field_options,
              'shortcode_id' => $shortcode_id,
          ]); ?>
        </div>
      </div>
      <?php endforeach; ?>
      <div class="estatebud-dropdown<?php echo count($advanced_fields) > 0 ? '' : ' estatebud-hidden'; ?>">
        <div class="estatebud-dropdown-button"><?php echo esc_html(Helper::term('listings.button.filters')); ?><span class="estatebud-advanced-filter-count"></span></div>
        <?php Helper::render_markup_from_views('Public/partials/filters/more-filters-form.php', [
            'fields' => $fields,
            'advanced_fields' => $advanced_fields,
            'field_options' => $field_options,
            'shortcode_id' => $shortcode_id,
        ]); ?>
      </div>
      <div class="estatebud-filter-reset-button" id="<?php echo esc_attr('estatebud-filter-reset-button-' . $shortcode_id); ?>">
        <?php echo wp_kses($icon_reset_button, Icons::get_kses_ruleset()); ?>
      </div>
    </div>
    <?php if (!empty($buttonDetail)) {
        Helper::render_markup_from_views('Public/partials/components/icon-button.php', $buttonDetail);
    } ?>
  </div>
</div>