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

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

if (!isset($form_id)) {
    $form_id = '';
}
if (!isset($settings_data)) {
    $settings_data = [];
}
if (!isset($form_data)) {
    $form_data = [];
}
if (!isset($field_options)) {
    $field_options = [];
}

$setting = $settings_data;
extract($setting);
$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);
    
    $normalize_api_type = function ($raw_type) {
        $type = strtolower(trim($raw_type ?? ''));
        switch ($type) {
            case 'heading':
                return 'heading';
            case 'select':
                return 'select';
            case 'checkbox':
                return 'checkbox';
            case 'radio':
                return 'radio';
            case 'textarea':
                return 'textarea';
            case 'number':
            case 'integer':
            case 'decimal':
            case 'float':
            case 'text':
            case 'string':
                return 'text';
            default:
                return $type ?: 'text';
        }
    };

    if ($field_obj->is_type('heading')) {
        $fieldData = ['type' => 'heading'];
    } elseif ($field_obj->is_type('textarea')) {
        $fieldData = ['type' => 'textarea'];
    } elseif ($field_obj->is_type('text')) {
        $fieldData = ['type' => 'text'];
    } elseif ($field_obj->is_type('email')) {
        $fieldData = ['type' => 'email'];
    } elseif ($field_obj->is_type('select')) {
        $options = $field_obj->get_options();
        $fieldData = [
            'type' => 'select',
            'options' => $options
        ];
    } elseif ($field_obj->is_type('phone')) {
        $fieldData = ['type' => 'phone'];
    } elseif ($field_obj->is_type('radio')) {
        $fieldData = ['type' => 'radio'];
    } elseif ($field_obj->is_type('checkbox')) {
        $fieldData = ['type' => 'checkbox'];
    } else {
        $original_type = $field_obj->get_type();
        $filtered_options = array_filter($field_options, function ($option) use ($original_type) {
            return $option['name'] === $original_type;
        });
        if (!empty($filtered_options)) {
            $api_field = array_values($filtered_options)[0];

            if (isset($api_field['options']) && !empty($api_field['options']) && is_array($api_field['options'])) {
                $fieldData = [
                    'type' => 'select',
                    'options' => $api_field['options']
                ];
            } else {
                $normalized_type = $normalize_api_type($api_field['type'] ?? 'text');
                $fieldData = $api_field;
                $fieldData['type'] = $normalized_type;
            }
        } else {
            $fieldData = ['type' => 'text'];
        }
    }
    
    $is_multiple_select = $field_obj->is_multiple() && $fieldData['type'] == 'select';
    $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'): ?>
                <div class="estatebud-field-range-wrapper">
                    <?php Helper::render_markup_from_views('Public/partials/components/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/components/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 (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' => 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/components/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/components/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/components/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/components/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/components/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/components/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; ?>
