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

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

$icon_cross = Icons::get_svg_icon('xmark-large', Icons::SHAPE_SHARP, Icons::STYLE_SOLID, 16, 16, '#858585');

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

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

$field_obj = new Field($field);

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

if (isset($options) && !is_array($options)) {
    $options = array_values($options);
}

$accordion_title = $field_obj->get_display_name() ?: 'Untitled Field';
?>

<div class="estatebud-field-settings">
    <div class="estatebud-accordion-secondary-group" >
        <div class="estatebud-accordion-name-group">
            <p class="estatebud-accordion-name"><?php echo esc_html($accordion_title); ?></p>
        </div>
        <div class="estatebud-accordion-cross-group">
            <?php echo wp_kses($icon_cross, Icons::get_kses_ruleset()); ?>
        </div>
    </div>

    <div class="estatebud-accordion-group" style="display: none;">
        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Field',
                ]); ?>
            </div>
            <?php
            $selectOptions = array_map(
                function($option) use ($field_obj, $options) {
                    $isApiField = !empty($field_obj->get_name()) && $field_obj->get_name() === $option['name'];

                    $isTypeMatch = $field_obj->is_type($option['name']);
                    $isSelected = $isApiField || $isTypeMatch;
                    
                    return [
                        'value' => $option['name'],
                        'disabled' => false,
                        'selected' => $isSelected,
                        'label' => $option['label'],
                    ];
                },
                $options,
            );

            $defaultOptions = [
                ['value' => 'text', 'label' => 'Text'],
                ['value' => 'email', 'label' => 'Email'],
                ['value' => 'phone', 'label' => 'Phone'],
                ['value' => 'textarea', 'label' =>'Textarea'],
                ['value' => 'select', 'label' => 'Select'],
                ['value' => 'radio', 'label' => 'Radio'],
                ['value' => 'checkbox', 'label' => 'Checkbox'],
            ];

            if (isset($type) && $type === 'contact') {
                $defaultOptions[] = ['value' => 'heading', 'label' => 'Heading'];
            }

            $defaultOptions = array_map(
                fn($opt) => [
                    'value' => $opt['value'],
                    'disabled' => false,
                    'selected' => $field_obj->is_type($opt['value']),
                    'label' => $opt['label'],
                ],
                $defaultOptions,
            );

            Helper::render_markup_from_views('Admin/partials/select-for-field-settings.php', [
                'extra_class' => 'custom-width estatebud-accordion-select',
                'variable_name' => 'type',
                'options' => $selectOptions,
                'custom_options' => $defaultOptions,
            ]);
            ?>
        </div>

        <div class="estatebud-field-group" id="field-name-group" style="display: none;">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Name',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                'value' => $field_obj->get_name(),
                'variable_name' => 'name',
            ]); ?>
        </div>

        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Label',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                'value' => $field_obj->get_label(),
                'variable_name' => 'label',
            ]); ?>
        </div>
        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Placeholder',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                'value' => $field_obj->get_placeholder(),
                'variable_name' => 'placeholder',
            ]); ?>
        </div>
        <?php if (!empty($client_field_labels)): ?>
        <div class="estatebud-field-group crm-field-mapping-group" style="display: none;">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'CRM field',
                ]); ?>
            </div>
            <?php
            $crm_field_options = [
                [
                    'value' => '',
                    'disabled' => false,
                    'selected' => empty($field_obj->get_crm_field()),
                    'label' => 'None',
                ],
            ];

            foreach ($client_field_labels as $field_name => $field_label) {
                $crm_field_options[] = [
                    'value' => $field_name,
                    'disabled' => false,
                    'selected' => $field_obj->get_crm_field() === $field_name,
                    'label' => $field_label,
                ];
            }

            Helper::render_markup_from_views('Admin/partials/select-field.php', [
                'variable_name' => 'crm_field',
                'extra_class' => 'custom-width estatebud-accordion-select',
                'options' => $crm_field_options,
            ]);
            ?>
        </div>
        <?php endif; ?>
        <div class="estatebud-field-group" style="<?php echo in_array($field_obj->get_type(), ['select', 'checkbox', 'radio'])
            ? 'display: flex'
            : 'display: none'; ?>">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Options',
                ]); ?>
            </div>
            <div class="estatebud-custom-option">
                <?php Helper::render_markup_from_views('Admin/partials/textarea-field.php', [
                    'variable_name' => 'options',
                    'rows' => 5,
                    'cols' => 67,
                    'textarea_content' => $field_obj->get_raw_options(),
                    'extra_class' => 'custom-dropdown-options',
                ]); ?>
                <p class="estatebud-custom-option-guide">
                    Enter one option per line, separate values with <span class="estatebud-monosplace-tag">|</span>.
                </p>
            </div>
        </div>

        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Conditional field',
                ]); ?>
            </div>
            <?php
            $selectOptions[] = [
                'value' => '',
                'label' => 'None',
                'selected' => empty($field_obj->get_conditional_field()),
                'disabled' => false,
            ];

            if (!empty($options) && is_array($options)) {
                foreach ($options as $option) {
                    if (
                        isset($option['name']) &&
                        isset($option['label']) &&
                        isset($option['type']) &&
                        $option['type'] === 'select'
                    ) {
                        $selectOptions[] = [
                            'value' => $option['name'],
                            'label' => $option['label'],
                            'selected' => $field_obj->get_conditional_field() === $option['name'],
                            'disabled' => false,
                        ];
                    }
                }
            }

            if (!empty($fields) && is_array($fields)) {
                foreach ($fields as $fieldItem) {
                    $fieldItem_obj = new Field($fieldItem);
                    if (
                        in_array($fieldItem_obj->get_type(), ['select', 'checkbox', 'radio']) &&
                        $fieldItem_obj->get_id() !== $field_obj->get_id()
                    ) {
                        $label = !empty($fieldItem_obj->get_label()) ? $fieldItem_obj->get_label() : ucfirst($fieldItem_obj->get_type());
                        $selectOptions[] = [
                            'value' => $fieldItem_obj->get_type(),
                            'label' => $label,
                            'selected' => $field_obj->get_conditional_field() === $fieldItem_obj->get_type(),
                            'disabled' => false,
                        ];
                    }
                }
            }

            $default_class = 'estatebud-field-select custom-width estatebud-accordion-select';
            $id = 'estatebud-field-select';
            ?>
                <select class="<?php echo esc_attr($default_class); ?>" id="<?php echo esc_attr($id); ?>" name="conditional_field">
                    <?php foreach ($selectOptions as $option): ?>
                        <option value="<?php echo isset($option['value']) ? esc_attr($option['value']) : ''; ?>"
                            <?php echo isset($option['disabled']) && $option['disabled'] ? ' disabled="disabled"' : ''; ?>
                            <?php echo isset($option['selected']) && $option['selected'] ? ' selected' : ''; ?>
                        ><?php echo isset($option['label']) ? esc_html($option['label']) : ''; ?></option>
                    <?php endforeach; ?>
                </select>
                <?php  ?>
        </div>

        <div class="estatebud-field-group" style="<?php echo !empty($field_obj->get_conditional_field())
            ? 'display: flex'
            : 'display: none'; ?>">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Conditional value',
                ]); ?>
            </div>
            <?php
            $conditionalValueOptions = [];

            $rawConditionalValue = $field_obj->get_conditional_value();
            $normalizedConditionalValues = $field_obj->get_conditional_values();

            $conditionalValueOptions[] = [
                'value' => '',
                'label' => 'Any',
                'selected' => empty($rawConditionalValue),
                'disabled' => false,
            ];

            if (!empty($options) && is_array($options) && !empty($field_obj->get_conditional_field())) {
                foreach ($options as $option) {
                    if (
                        isset($option['name']) &&
                        $option['name'] === $field_obj->get_conditional_field() &&
                        isset($option['options']) &&
                        !empty($option['options'])
                    ) {
                        if (is_array($option['options'])) {
                            foreach ($option['options'] as $opt) {
                                if (!empty($opt) && isset($opt['value']) && isset($opt['label'])) {
                                    $isSelected = in_array($opt['value'], $normalizedConditionalValues, true);
                                    if (!$isSelected && $rawConditionalValue !== '') {
                                        $isSelected = trim((string) $rawConditionalValue) === (string) $opt['value'];
                                    }

                                    $conditionalValueOptions[] = [
                                        'value' => $opt['value'],
                                        'label' => $opt['label'],
                                        'selected' => $isSelected,
                                        'disabled' => false,
                                    ];
                                }
                            }
                        }
                        break;
                    }
                }
            }

            $default_class = 'estatebud-field-select custom-width estatebud-accordion-select';
            $id = 'estatebud-field-select';
            ?>
                <select class="<?php echo esc_attr($default_class); ?>" id="<?php echo esc_attr($id); ?>" name="conditional_value" multiple data-saved-values="<?php echo esc_attr(
    $field_obj->get_conditional_value(),
); ?>">
                    <?php foreach ($conditionalValueOptions as $option): ?>
                        <option value="<?php echo isset($option['value']) ? esc_attr($option['value']) : ''; ?>"
                            <?php echo isset($option['disabled']) && $option['disabled'] ? ' disabled="disabled"' : ''; ?>
                            <?php echo isset($option['selected']) && $option['selected'] ? ' selected' : ''; ?>
                        ><?php echo isset($option['label']) ? esc_html($option['label']) : ''; ?></option>
                    <?php endforeach; ?>
                </select>
                <?php  ?>
        </div>

        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Regex',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                'value' => $field_obj->get_regex(),
                'variable_name' => 'regex',
            ]); ?>
        </div>
        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Advanced',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/toggle-button.php', [
                'variable_name' => 'advanced',
                'default_checked' => false,
                'value' => $field_obj->is_advanced(),
            ]); ?>
        </div>

        <div class="estatebud-field-group" style="<?php echo isset($type) &&
        in_array($type, ['property-search', 'project-search'])
            ? 'display: none'
            : 'display: flex'; ?>">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Required',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/toggle-button.php', [
                'variable_name' => 'required',
                'default_checked' => true,
                'value' => $field_obj->is_required(),
            ]); ?>
        </div>
        <div class="estatebud-field-group" style="display:none;">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Multiple',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/toggle-button.php', [
                'variable_name' => 'multiple',
                'default_checked' => true,
                'value' => $field_obj->is_multiple(),
            ]); ?>
        </div>
        <div class="estatebud-field-group" style="display:none;">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Range',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/toggle-button.php', [
                'variable_name' => 'range',
                'default_checked' => true,
                'value' => $field_obj->is_range(),
            ]); ?>
        </div>

        <div class="estatebud-field-group" style="<?php echo isset($type) && $type == 'contact'
            ? 'display: flex'
            : 'display: none'; ?>">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Column width',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/select-field.php', [
                'extra_class' => 'custom-width column-width-select',
                'variable_name' => 'width',
                'options' => [
                    [
                        'value' => '',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() === null,
                        'label' => 'Auto',
                    ],
                    [
                        'value' => '20',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 20,
                        'label' => '20%',
                    ],
                    [
                        'value' => '25',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 25,
                        'label' => '25%',
                    ],
                    [
                        'value' => '30',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 30,
                        'label' => '30%',
                    ],
                    [
                        'value' => '33',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 33,
                        'label' => '33%',
                    ],
                    [
                        'value' => '40',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 40,
                        'label' => '40%',
                    ],
                    [
                        'value' => '50',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 50,
                        'label' => '50%',
                    ],
                    [
                        'value' => '60',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 60,
                        'label' => '60%',
                    ],
                    [
                        'value' => '66',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 66,
                        'label' => '66%',
                    ],
                    [
                        'value' => '70',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 70,
                        'label' => '70%',
                    ],
                    [
                        'value' => '75',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 75,
                        'label' => '75%',
                    ],
                    [
                        'value' => '80',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 80,
                        'label' => '80%',
                    ],
                    [
                        'value' => '100',
                        'disabled' => false,
                        'selected' => $field_obj->get_width() == 100,
                        'label' => '100%',
                    ],
                ],
            ]); ?>
        </div>
        <div class="estatebud-field-group">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'Shortcode',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                'extra_class' => 'shortcode-class',
                'value' => $field_obj->get_shortcode(),
                'variable_name' => 'shortcode',
                'placeholder' => '{{ field.f9b8c7e }}',
                'readonly' => true,
            ]); ?>
        </div>

        <div style="display:none">
            <div class="estatebud-field-label estatebud-width-120">
                <?php Helper::render_markup_from_views('Admin/partials/field-label.php', [
                    'field_label' => 'ID',
                ]); ?>
            </div>
            <?php Helper::render_markup_from_views('Admin/partials/text-field.php', [
                'value' => $field_obj->get_id(),
                'variable_name' => 'id',
            ]); ?>
        </div>
    </div>
</div>
