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

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

$form_id = $form_id ?? '';
$settings_data = $settings_data ?? [];
$form_data = $form_data ?? [];
$field_options = $field_options ?? [];
$fields = $form_data['fields'] ?? [];

$icon_check = Icons::get_svg_icon('check', Icons::SHAPE_SHARP, Icons::STYLE_SOLID, 11, 10, '#FFF');
?>
<?php foreach ($fields as $field): ?>
    <?php
    $field_obj = new Field($field);

    $field_name = $field_obj->get_name();
    $has_custom_options = !empty($field_obj->get_raw_options());

    $matching_api_field = null;
    foreach ($field_options as $option) {
        if (isset($option['name']) && $option['name'] === $field_name) {
            $matching_api_field = $option;
            break;
        }
    }

    if ($matching_api_field && !$has_custom_options) {
        $fieldData = $matching_api_field;
    } elseif (!empty($field) && in_array($field_obj->get_type(), ['select', 'checkbox', 'radio']) && !empty($field_obj->get_raw_options())) {
        $options = $field_obj->get_options();
        $fieldData = [
            'name' => $field_obj->get_name(),
            'label' => $field_obj->get_label(),
            'options' => $options,
            'filter' => [
                'range' => false
            ],
            'type' => $field_obj->get_type()
        ];
    } else {
        $fieldData = [
            'name' => $field_obj->get_name(),
            'label' => $field_obj->get_label(),
            'options' => [],
            'filter' => [
                'range' => false
            ],
            'type' => $field_obj->get_type() ?: 'text'
        ];
    }
    
    $original_field_type = strtolower(trim($field_obj->get_type()));
    $is_number_range =
        in_array($original_field_type, ['number', 'integer', 'decimal', 'float']) && $field_obj->is_range();
    if ($is_number_range) {
        $fieldData['type'] = 'number';
    }
    
    $width_class = $field_obj->get_width_class();

    $field_style = $field_obj->get_display_style();

    $field_id = $field_obj->get_id();

    $label = null;
    $placeholder = null;

    if ($field_obj->get_label()) {
        $label = Helper::term(sprintf("form.%s.field.%s.label", $form_id, $field_id));
    }

    if ($field_obj->get_placeholder()) {
        $placeholder = Helper::term(sprintf("form.%s.field.%s.placeholder", $form_id, $field_id));
    }
    ?>
    <?php if ($fieldData['type'] == 'heading'): ?>
        <div class="estatebud-form-field-container">
            <div class="estatebud-form-title">
                <?php echo isset($label) ? esc_html($label) : ''; ?>
            </div>
        </div>
    <?php else: ?>
        <div class="estatebud-form-field-container<?php echo ($field_obj->is_conditional() ? ' conditional-field' : '') . esc_attr($width_class); ?>"
            id="<?php echo esc_attr('contact-' . $field_id); ?>"
            <?php if (!empty($field_style)): ?>
            style="<?php echo esc_attr($field_style); ?>"
            <?php endif; ?>
            <?php if ($field_obj->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 if (isset($label)): ?>
            <label for="" class="estatebud-form-field-label">
                <?php echo esc_html($label); ?>
                <?php if ($field_obj->is_required()): ?>
                    <span class="estatebud-form-field-label-required">*<span>
                <?php endif; ?>
            </label>
            <?php endif; ?>

            <?php if ($fieldData['type'] == 'number' && $is_number_range): ?>
                <div class="estatebud-field-range-wrapper">
                    <?php Helper::render_markup_from_views('Public/partials/fields/input.php', [
                        'value' => $field_obj->get_min_value(),
                        'variable_name' => $field_obj->get_name() . '-min',
                        'placeholder' => Helper::term('filters.min'),
                        'required' => $field_obj->is_required(),
                        'settings_data' => $settings_data
                    ]); ?>
                    <?php Helper::render_markup_from_views('Public/partials/fields/input.php', [
                        'value' => $field_obj->get_max_value(),
                        'variable_name' => $field_obj->get_name() . '-max',
                        'placeholder' => Helper::term('filters.max'),
                        'required' => $field_obj->is_required(),
                        'settings_data' => $settings_data
                    ]); ?>
                </div>
            <?php elseif ($fieldData['type'] == 'number'): ?>
                <?php Helper::render_markup_from_views('Public/partials/fields/input.php', [
                    'type' => 'text',
                    'value' => $field_obj->get_value(),
                    'variable_name' => $field_obj->get_name(),
                    'placeholder' => $placeholder ?? '',
                    'required' => $field_obj->is_required(),
                    'settings_data' => $settings_data,
                    'extra_class' => 'estatebud-number-input'
                ]); ?>
            <?php elseif (in_array($fieldData['type'], ['select', 'area'])): ?>
                <?php
                $isMultiple = $field_obj->is_multiple();

                $options_for_select = array_map(
                    fn($option) => [
                        'value' => $option['value'],
                        'disabled' => false,
                        'selected' => empty($option['value']),
                        'label' => $matching_api_field ? $option['label'] : Helper::term(sprintf("form.%s.field.%s.option.%s.label", $form_id, $field_id, hash('xxh32', $option['label'])))
                    ],
                    $fieldData['options']
                );
                
                Helper::render_markup_from_views('Public/partials/fields/select.php', [
                    'extra_class' => $isMultiple ? 'multiselect' : '',
                    'placeholder' => $placeholder ?? '',
                    'multiple' => $isMultiple,
                    'variable_name' => $field_obj->get_name(),
                    'options' => $options_for_select,
                    'required' => $field_obj->is_required()
                ]); ?>
            <?php elseif ($fieldData['type'] == 'phone'): ?>
                <?php Helper::render_markup_from_views('Public/partials/fields/input.php', [
                    'value' => $field_obj->get_value(),
                    'variable_name' => $field_obj->get_name(),
                    'extra_class' => 'estatebud-phone-input',
                    'placeholder' => $placeholder ?? '',
                    'required' => $field_obj->is_required(),
                    'settings_data' => $settings_data
                ]); ?>
            <?php elseif ($fieldData['type'] == 'email'): ?>
                <?php Helper::render_markup_from_views('Public/partials/fields/input.php', [
                    'type' => 'email',
                    'value' => $field_obj->get_value(),
                    'variable_name' => $field_obj->get_name(),
                    'placeholder' => $placeholder ?? '',
                    'required' => $field_obj->is_required(),
                    'settings_data' => $settings_data
                ]); ?>
            <?php elseif ($fieldData['type'] == 'textarea'): ?>
                <?php Helper::render_markup_from_views('Public/partials/fields/textarea.php', [
                    'value' => $field_obj->get_value(),
                    'variable_name' => $field_obj->get_name(),
                    'placeholder' => $placeholder ?? '',
                    'required' => $field_obj->is_required(),
                    'settings_data' => $settings_data
                ]); ?>
            <?php elseif ($fieldData['type'] == 'radio' || $fieldData['type'] == 'checkbox'): ?>
                <?php
                $options = $field_obj->get_options();

                $field_name = $field_obj->get_name();
                ?>
                <?php if (!empty($options)): ?>
                    <div class="flex-row">
                        <?php foreach ($options as $option): ?>
                            <label class="estatebud-custom-checkbox <?php echo esc_attr($fieldData['type']); ?>">
                                <?php Helper::render_markup_from_views('Public/partials/fields/input.php', [
                                    'type' => $fieldData['type'] === 'radio' ? 'radio' : 'checkbox',
                                    'name' => $field_name . ($fieldData['type'] === 'checkbox' ? '[]' : ''),
                                    'value' => $option['value'],
                                    'required' => $field_obj->is_required()
                                ]); ?>
                                <span class="estatebud-checkbox-mark"><?php echo $fieldData['type'] !== 'radio' ? wp_kses($icon_check, Icons::get_kses_ruleset()) : ''; ?></span>
                                <span class="estatebud-option-label"><?php echo esc_html($option['label']); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <?php Helper::render_markup_from_views('Public/partials/fields/input.php', [
                    'value' => $field_obj->get_value(),
                    'variable_name' => $field_obj->get_name(),
                    'placeholder' => $placeholder ?? '',
                    'required' => $field_obj->is_required(),
                    'settings_data' => $settings_data
                ]); ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>
<?php endforeach; ?>
