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

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

$search_id = $search_id ?? '';
$query_from_link = $query_from_link ?? [];
$shortcode_id = $shortcode_id ?? '';
$settings_data = $settings_data ?? [];
$field_options = $field_options ?? [];
$location_options = $location_options ?? [];
$search_exp_data = $search_exp_data ?? [];
$form_data = $form_data ?? null;

$form_id = $form_id ?? '';

$icon_type = $settings_data['icon_type'] ?? Icons::SHAPE_SHARP;
$icon_style = $settings_data['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, fn($ele) => $ele['type'] === $key_of_query);
            if (count($filter_result)) {
                $search_exp_from_link[array_key_first($filter_result)]['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;
                    }
                }
            }
            unset($option);
        }
    }
}

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;
        }
    }
}
unset($option);

$fields = $form_data['fields'] ?? [];
$normal_fields = [];
$advanced_fields = [];

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);
            return !empty($field_name) && !empty($search_exp_obj->get_name()) && $search_exp_obj->get_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, fn($option) => isset($option['name']) && $option['name'] === $matched_search_exp_field_obj->get_name()),
        );
        if (!empty($filtered_options)) {
            $matched_field_option = $filtered_options[0];
            if (in_array($matched_field_option['type'], ['select'])) {
                if ($matched_search_exp_field_obj->is_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 ($matched_search_exp_field_obj->is_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);

$paired_with_search = !empty($search_id);
if (!$paired_with_search) {
    $button_icon = isset($form_data['button_icon_type']) && $form_data['button_icon_type']
        ? Icons::get_svg_icon($form_data['button_icon_type'], Icons::SHAPE_SHARP, Icons::STYLE_SOLID, 18, 18, '#ffffff')
        : '';
    $buttonDetail = [
        'icon' => $button_icon,
        'title' => Helper::term(sprintf('form.%s.button.label', $form_id)),
        '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'] ?? '';
    $buttonDetail = !empty($map_provider) ? [
        'icon' => $icon_map,
        'title' => Helper::term('listings.button.toggle_map'),
        'name' => 'toggle-map',
        'icon_position' => 'left',
        'destination_url' => '',
    ] : null;
}

$filter_hidden_class = !empty($search_id) ? ' estatebud-hidden' : '';
?>
<div class="estatebud-filter-group-wrapper<?php echo !count($fields) ? ' estatebud-hidden' : ''; ?>">
  <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, fn($opt) => isset($opt['name']) && $opt['name'] === $field_obj->get_name()));
          if (!empty($matching_api_field)) {
              $field_type_for_attr = $field_obj->get_name();
          }
      }
      $is_conditional = $field_obj->is_conditional();

      $label = null;

      if ($field_obj->get_label()) {
          $label = Helper::term(sprintf("form.%s.field.%s.label", $form_id, $field_obj->get_id()));
      }
      ?>
      <div class="estatebud-filter-field-wrapper<?php echo $filter_hidden_class; ?><?php echo $is_conditional ? ' conditional-field' : ''; ?>"
        id="<?php echo esc_attr(sprintf('filter-%s-%s', $shortcode_id, $field_obj->get_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($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', $shortcode_id, $field_obj->get_id())); ?>">
          <?php Helper::render_markup_from_views('Public/Form/fields/search-fields-group.php', [
              'form_id' => $form_id,
              'field' => $field,
              'field_options' => $field_options,
          ]); ?>
        </div>
      </div>
      <?php endforeach; ?>
      <div class="estatebud-dropdown<?php echo $filter_hidden_class; ?>">
        <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/Form/fields/more-filters-form.php', [
            'fields' => $fields,
            'advanced_fields' => $advanced_fields,
            'field_options' => $field_options,
            'form_id' => $form_id,
            'form_data' => $form_data,
            'shortcode_id' => $shortcode_id,
        ]); ?>
      </div>
      <div class="estatebud-filter-reset-button<?php echo $filter_hidden_class; ?>" 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/icon-button.php', $buttonDetail);
    } ?>
  </div>
</div>
