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

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

if (!isset($fields) || !is_array($fields)) {
    $fields = [];
}

if (!isset($advanced_fields) || !is_array($advanced_fields)) {
    $advanced_fields = [];
}

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

if (!isset($shortcode_id)) {
    $shortcode_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-shortcode-id="<?php echo esc_attr($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/partials/components/search-fields-group.php', [
          'field' => $field,
          'field_options' => $field_options,
          'shortcode_id' => $shortcode_id
      ]); ?>
    </div>
  <?php endforeach; ?>
</div>
