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

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

$fields = $fields ?? [];
$advanced_fields = $advanced_fields ?? [];
$field_options = $field_options ?? [];
$shortcode_id = $shortcode_id ?? '';
$form_id = $form_id ?? '';
?>
<div class="estatebud-more-filters-form estatebud-hidden" id="search-more-filters-<?php echo esc_attr($shortcode_id); ?>">
  <?php $advanced_field_ids = array_filter(
      array_map(static function ($advanced_field) {
          return $advanced_field['id'] ?? null;
      }, $advanced_fields)
  ); ?>
  <?php foreach ($fields as $field): ?>
    <?php
    $field_obj = new Field($field);
    $field_id = $field_obj->get_id();
    $is_server_advanced = $field_id && in_array($field_id, $advanced_field_ids, true);
    $is_conditional = $field_obj->is_conditional();

    $wrapper_styles = [];
    if ($is_conditional) {
        $wrapper_styles[] = 'display: none;';
    }
    if (!$is_server_advanced) {
        $wrapper_styles[] = 'display: none;';
    }
    $style_attr = !empty($wrapper_styles) ? implode(' ', $wrapper_styles) : '';

    $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();
        }
    }
    ?>
    <div class="estatebud-advanced-field-wrapper<?php echo $is_conditional ? ' conditional-field' : ''; ?>"
         id="advanced-filter-<?php echo esc_attr($field_id . '-' . $shortcode_id); ?>"
         data-server-advanced="<?php echo $is_server_advanced ? 'true' : 'false'; ?>"
         data-field-id="<?php echo esc_attr($field_id); ?>"
         data-field-type="<?php echo esc_attr($field_type_for_attr); ?>"
         data-custom-advanced="false"
         <?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; ?>
        <?php echo $style_attr ? ' style="' . esc_attr(trim($style_attr)) . '"' : ''; ?>>
      <?php Helper::render_markup_from_views('Public/Form/fields/search-fields-group.php', [
          'form_id' => $form_id,
          'field' => $field,
          'field_options' => $field_options,
      ]); ?>
    </div>
  <?php endforeach; ?>
</div>
