<?php

namespace WeDevs\Wpuf\Pro\Fields;

use WeDevs\Wpuf\Fields\Form_Field_Post_Trait;

/**
 * Repeat Field Class
 *
 * @since 3.1.0
 **/
class Field_Repeat extends Pro_Field_Contract {

    use Form_Field_Post_Trait;

    public function __construct() {
        $this->name       = __( 'Repeat Field', 'wpuf-pro' );
        $this->input_type = 'repeat_field';
        $this->icon       = 'rectangle-stack';
    }

    /**
     * Render the Repeat field in the frontend
     *
     * @since 4.1.9   Simplified repeat field rendering
     *
     * @param array  $field_settings
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     *
     * @return void
     */
    public function render( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        $inner_fields = ! empty( $field_settings['inner_fields'] ) ? $field_settings['inner_fields'] : [];
        $max_repeats  = ! empty( $field_settings['max_repeats'] ) ? $field_settings['max_repeats'] : - 1;
        $field_name   = ! empty( $field_settings['name'] ) ? $field_settings['name'] : '';
        $id           = ! empty( $field_settings['id'] ) ? $field_settings['id'] : 0;
        $input_type   = 'repeat_field';
        $values       = [];
        $class_names  = ! empty( $field_settings['css'] ) ? ' ' . $field_settings['css'] : '';
        $class_names  .= ' wpuf_' . $input_type . '_' . $id . '_' . esc_attr( $form_id );

        // Get the display option - default to 'blocks' for backward compatibility
        $display_option = ! empty( $field_settings['repeat_display'] ) ? $field_settings['repeat_display'] : 'blocks';
        $class_names .= ' wpuf-repeat-display-' . esc_attr( $display_option );

        if ( isset( $post_id ) && $post_id != '0' ) {
            if ( $this->is_meta( $field_settings ) ) {
                $values = $this->get_meta( $post_id, $field_settings['name'], $type );
            }
        } else {
            $values = $field_settings['default'] ?? [];
        }

        ?>
        <div class="wpuf-fields wpuf-repeat-container <?php echo esc_attr( $class_names ); ?>" data-field-name="<?php echo esc_attr( $field_name ); ?>"
             data-max-repeats="<?php echo esc_attr( $max_repeats ); ?>" data-display-option="<?php echo esc_attr( $display_option ); ?>">
             <?php
             if( !empty($field_settings['label'])) {
                ?>
                <p style="margin: 0;"><?php echo esc_html( $field_settings['label'] ); ?></p>
                <hr style="margin-bottom: 10px;">
                <?php
             }
             ?>
            <?php
            // Choose rendering method based on display option
            if ( 'rows' === $display_option ) {
                $this->render_repeat_instances_rows( $inner_fields, $values, $form_id, $type, $post_id, $field_name, 1 );
            } else {
                // Default to blocks rendering for backward compatibility
                $this->render_repeat_instances_wrapped( $inner_fields, $values, $form_id, $type, $post_id, $field_name, 1 );
            }
            ?>

            <?php $this->help_text( $field_settings ); ?>
        </div>

        <?php
        wp_enqueue_style( 'wpuf-repeat-field' );
        wp_enqueue_script( 'wpuf-repeat-field' );
    }

    /**
     * Render the Repeat field in admin metabox
     *
     * @since 4.1.9
     *
     * @param array  $field_settings
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     *
     * @return void
     */
    public function render_admin_metabox( $field_settings, $form_id, $type = 'post', $post_id = null ) {
        $inner_fields = ! empty( $field_settings['inner_fields'] ) ? $field_settings['inner_fields'] : [];
        $max_repeats  = ! empty( $field_settings['max_repeats'] ) ? $field_settings['max_repeats'] : - 1;
        $field_name   = ! empty( $field_settings['name'] ) ? $field_settings['name'] : '';
        $id           = ! empty( $field_settings['id'] ) ? $field_settings['id'] : 0;
        $input_type   = 'repeat_field';
        $values       = [];
        $class_names  = ! empty( $field_settings['css'] ) ? ' ' . $field_settings['css'] : '';
        $class_names  .= ' wpuf_' . $input_type . '_' . $id . '_' . esc_attr( $form_id );

        if ( isset( $post_id ) && $post_id != '0' ) {
            if ( $this->is_meta( $field_settings ) ) {
                $values = $this->get_meta( $post_id, $field_settings['name'], $type );
            }
        } else {
            $values = $field_settings['default'] ?? [];
        }

        // Output a single table row for the repeat field and all its instances
        ob_start();
        ?>
        <tr class="wpuf-el <?php echo esc_attr( $field_name ); ?> field-size-large" data-label="<?php echo esc_attr( $field_settings['label'] ); ?>">
            <th><strong><?php echo esc_html( $field_settings['label'] ); ?></strong></th>
            <td>
                <div class="wpuf-fields wpuf-repeat-container <?php echo esc_attr( $class_names ); ?>" data-field-name="<?php echo esc_attr( $field_name ); ?>" data-max-repeats="<?php echo esc_attr( $max_repeats ); ?>">
                    <?php $this->render_repeat_instances_admin_inline( $inner_fields, $values, $form_id, $type, $post_id, $field_name, 1 ); ?>
                </div>
                <?php $this->help_text( $field_settings ); ?>
            </td>
        </tr>
        <style>
            .ui-datepicker-calendar {
                background: #fff;
            }
        </style>
        <?php
        $output = ob_get_clean();
        echo $output;
    }

    // New method: render repeat instances as inline inputs for admin metabox
    private function render_repeat_instances_admin_inline( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }


        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );
        // Ensure $values is a flat array of instances, not nested/appended
        if ( empty( $values ) || ! is_array( $values ) ) {
            $values = [];
        }
        // If no values provided, create at least min_instances empty instances
        $instance_count = max(count($values), $min_instances);
        $normalized_values = [];
        for ( $i = 0; $i < $instance_count; $i++ ) {
            $instance = [];
            foreach ( $fields as $field ) {
                $instance[ $field['name'] ] = isset($values[$i][$field['name']]) ? $values[$i][$field['name']] : '';
            }
            $normalized_values[] = $instance;
        }
        // Calculate total instances for dynamic z-index (first row gets highest z-index)
        $total_instances = count( $normalized_values );
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            $z_index = $total_instances - $instance_index;
            echo '<div class="wpuf-repeat-instance" style="position: relative; z-index: ' . esc_attr( $z_index ) . ';" data-instance="' . esc_attr( $instance_index ) . '">';
            foreach ( $fields as $field ) {
                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                        echo wp_kses_post( '<h4 style="color: red;"><em>' . $field['template'] . '</em> field not found.</h4>' );
                    }
                    continue;
                }
                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        $original_name = $field_with_value['name'];
                        if ( ! empty( $field_name ) ) {
                            $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $original_name . ']';
                        }
                        // Render label and input inline

                        ob_start();
                        ?>
                            <div style="margin-bottom:8px">
                                <label style="display:block;font-weight:600;margin-bottom:2px"><?php echo esc_html( $field_with_value['label'] ); ?></label>
                                <?php
                                    $field_object->render( $field_with_value, $form_id, $type, null );
                                ?>
                            </div>
                        <?php
                        $input_html = ob_get_clean();
                        // Remove any <tr>...</tr> wrappers if present
                        $input_html = preg_replace('/<tr[^>]*>|<\/tr>/i', '', $input_html);
                        $input_html = preg_replace('/<th[^>]*>.*?<\/th>/is', '', $input_html);
                        $input_html = preg_replace('/<td[^>]*>|<\/td>/i', '', $input_html);

                        echo $input_html;
                    }
                }
            }

            // Add placeholder for buttons - JavaScript will add the actual buttons
            echo '<div class="wpuf-repeat-controls"></div>';
            echo '</div>'; // Close wpuf-repeat-instance
        }
    }

    /**
     * Render repeat instances with proper wrapper structure for frontend
     *
     * @param array  $fields
     * @param array  $values
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     * @param string $field_name
     * @param int    $min_instances
     *
     * @return void
     */
    private function render_repeat_instances_wrapped( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }

        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );

        // If no values provided, create at least min_instances empty instances
        if ( empty( $values ) ) {
            $values = [];
            for ( $i = 0; $i < $min_instances; $i++ ) {
                $empty_instance = [];
                foreach ( $fields as $field ) {
                    $name = ! empty( $field['name'] ) ? $field['name'] : '';
                    $empty_instance[ $name ] = '';
                }
                $values[] = $empty_instance;
            }
        }

        // Normalize values to match field names
        $normalized_values = $this->normalize_values_for_fields( $fields, $values );

        // Calculate total instances for dynamic z-index (first row gets highest z-index)
        $total_instances = count( $normalized_values );
        // Loop through each instance
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            $z_index = $total_instances - $instance_index;
            echo '<div class="wpuf-repeat-instance" style="position: relative; z-index: ' . esc_attr( $z_index ) . ';" data-instance="' . esc_attr( $instance_index ) . '">';

            // Render each field with its corresponding value
            foreach ( $fields as $field ) {
                if ( empty( $field['template'] ) ) {
                    continue;
                }
                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                        echo wp_kses_post( '<h4 style="color: red;"><em>' . $field['template'] . '</em> field not found.</h4>' );
                    }
                    continue;
                }

                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        // Get the value for this specific field in this instance
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';

                        // Create a copy of the field settings and set the value
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        // Modify the field name to be indexed for repeat field structure
                        // Format: repeat_field_name[instance_index][inner_field_name]
                        $original_name = $field_with_value['name'];
                        if ( ! empty( $field_name ) ) {
                            $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $original_name . ']';
                        }

                        // Force post_id to null so that the field uses the default value
                        $render_post_id = null;

                        // Render the field with the current value
                        $field_object->render( $field_with_value, $form_id, $type, $render_post_id );
                        $field_object->conditional_logic( $field_with_value, $form_id );
                    }
                }
            }

            // Add repeat controls
            // Add placeholder for buttons - JavaScript will add the actual buttons
            echo '<div class="wpuf-repeat-controls"></div>';
            echo '</div>'; // Close wpuf-repeat-instance
        }
    }

    /**
     * Render repeat instances with or without values
     *
     * @param array  $fields
     * @param array  $values
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     * @param string $field_name
     * @param int    $min_instances
     *
     * @return void
     */
    private function render_repeat_instances( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }

        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );

        // If no values provided, create at least min_instances empty instances
        if ( empty( $values ) ) {
            $values = [];
            for ( $i = 0; $i < $min_instances; $i++ ) {
                $empty_instance = [];
                foreach ( $fields as $field ) {
                    $empty_instance[ $field['name'] ] = '';
                }
                $values[] = $empty_instance;
            }
        }

        // Normalize values to match field names
        $normalized_values = $this->normalize_values_for_fields( $fields, $values );

        // Loop through each instance
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            // Render each field with its corresponding value
            foreach ( $fields as $field ) {
                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                        echo wp_kses_post( '<h4 style="color: red;"><em>' . $field['template'] . '</em> field not found.</h4>' );
                    }
                    continue;
                }

                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        // Get the value for this specific field in this instance
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';

                        // Create a copy of the field settings and set the value
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        // Modify the field name to be indexed for repeat field structure
                        // Format: repeat_field_name[instance_index][inner_field_name]
                        $original_name = $field_with_value['name'];
                        if ( ! empty( $field_name ) ) {
                            $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $original_name . ']';
                        }

                        // Force post_id to null so that the field uses the default value
                        $render_post_id = null;

                        // Render the field with the current value
                        $field_object->render( $field_with_value, $form_id, $type, $render_post_id );
                        $field_object->conditional_logic( $field_with_value, $form_id );
                    }
                }
            }

            // Add repeat controls
            // Add placeholder for buttons - JavaScript will add the actual buttons
            echo '<div class="wpuf-repeat-controls"></div>';
        }
    }

    /**
     * Normalize values array to match field names
     *
     * @param array $fields
     * @param array $values
     *
     * @return array
     */
    private function normalize_values_for_fields( $fields, $values ) {
        $normalized_values = [];

        // Create a mapping of field templates to field names
        $template_to_name = [];
        foreach ( $fields as $field ) {
            $template = ! empty( $field['template'] ) ? $field['template'] : '';
            if ( ! empty( $template ) ) {
                $template_to_name[ $template ] = $field['name'];
            }
        }

        // Normalize each instance
        foreach ( $values as $instance_index => $instance_values ) {
            $normalized_instance = [];

            foreach ( $instance_values as $key => $value ) {
                // Try to find the correct field name by matching template or name
                $found_field_name = null;

                // First, try exact name match
                foreach ( $fields as $field ) {
                    if ( empty( $field['name'] ) ) {
                        continue;
                    }

                    if ( $field['name'] === $key ) {
                        $found_field_name = $field['name'];
                        break;
                    }
                }

                // If not found, try to match by template type
                if ( ! $found_field_name ) {
                    // Extract template type from the key (e.g., 'text_3357845579' -> 'text_field')
                    $key_parts = explode( '_', $key );
                    if ( count( $key_parts ) >= 2 ) {
                        $template_type = $key_parts[0] . '_field';

                        // Look for matching template
                        foreach ( $fields as $field ) {
                            if ( $field['template'] === $template_type ) {
                                $found_field_name = $field['name'];
                                break;
                            }
                        }
                    }
                }

                // If still not found, use the original key
                if ( ! $found_field_name ) {
                    $found_field_name = $key;
                }

                $normalized_instance[ $found_field_name ] = $value;
            }

            $normalized_values[ $instance_index ] = $normalized_instance;
        }

        return $normalized_values;
    }

    /**
     * It's not a full width block
     *
     * @return bool
     */
    public function is_full_width() {
        return true;
    }

    /**
     * Get field options setting
     *
     * @return array
     */
    public function get_options_settings() {
        $default_options = $this->get_default_option_settings( true, [ 'read_only', 'show_icon', 'field_icon', 'icon_position' ] );

        $settings = [
            [
                'name'      => 'repeat_display',
                'title'     => __( 'Display', 'wpuf-pro' ),
                'type'      => 'radio',
                'section'   => 'basic',
                'priority'  => 10,
                'default'   => 'blocks',
                'options'   => [
                    'blocks' => __( 'Blocks', 'wpuf-pro' ),
                    'rows'   => __( 'Rows', 'wpuf-pro' ),
                ],
                'help_text' => __( 'Choose how the repeat fields should be displayed', 'wpuf-pro' ),
            ],
            [
                'name'      => 'max_repeats',
                'title'     => __( 'Maximum Repeats', 'wpuf-pro' ),
                'type'      => 'text',
                'variation' => 'number',
                'section'   => 'advanced',
                'priority'  => 23,
                'default'   => -1,
                'help_text' => __( 'Maximum number of repeatable instances (-1 for unlimited)', 'wpuf-pro' ),
            ],
        ];

        $all_settings = array_merge( $default_options, $settings );

        /**
         * Filter: 'wpuf_repeat_field_option_settings' - Allows filtering of all the repeat field settings.
         *
         * @param array $all_settings The current settings array
         */
        return apply_filters( 'wpuf_repeat_field_option_settings', $all_settings );
    }

    /**
     * Get the field props
     *
     * @return array
     */
    public function get_field_props() {
        $defaults     = $this->default_attributes();

        $props = [
            'input_type'       => 'repeat',
            'is_meta'          => 'yes',
            'width'            => 'large',
            'size'             => '40',
            'id'               => 0,
            'is_new'           => true,
            'show_in_post'     => 'yes',
            'repeat_display'   => 'blocks',
            'hide_field_label' => 'no',
            'max_repeats'      => - 1,
            'inner_fields'     => [],
        ];

        $all_props = array_merge( $defaults, $props );

        /**
         * Filter: 'wpuf_repeat_field_props' - Allows filtering of all the repeat field props.
         *
         * @param array $all_props The current props array
         */
        return apply_filters( 'wpuf_repeat_field_props', $all_props );
    }

    /**
     * Prepare entry
     *
     * @param $field
     *
     * @return mixed
     */
    public function prepare_entry( $field ) {
        $entry_value = [];


        // Process repeat field data with indexed field names
        if ( isset( $_POST[$field['name']] ) && is_array( $_POST[$field['name']] ) ) {
            foreach ( $_POST[$field['name']] as $instance_index => $instance_data ) {
                if ( is_array( $instance_data ) ) {
                    $instance_meta = [];
                    foreach ( $instance_data as $field_name => $field_value ) {
                        // Handle different field types
                        if ( is_array( $field_value ) ) {
                            // For fields like checkboxes that can have multiple values
                            $instance_meta[$field_name] = array_map( function( $item ) { return strip_shortcodes( sanitize_text_field( $item ) ); }, $field_value );
                        } else {
                            $instance_meta[$field_name] = strip_shortcodes( sanitize_text_field( $field_value ) );
                        }
                    }
                    $entry_value[] = $instance_meta;
                }
            }
        }
        return $entry_value;
    }

    /**
     * Render repeat instances in rows format (table-like display)
     *
     * @param array  $fields
     * @param array  $values
     * @param int    $form_id
     * @param string $type
     * @param int    $post_id
     * @param string $field_name
     * @param int    $min_instances
     */
    private function render_repeat_instances_rows( $fields, $values, $form_id, $type = 'post', $post_id = null, $field_name = '', $min_instances = 1 ) {
        if ( ! $fields ) {
            return;
        }

        $fields = apply_filters( 'wpuf_render_fields', $fields, $form_id );

        // If no values provided, create at least min_instances empty instances
        if ( empty( $values ) ) {
            $values = [];
            for ( $i = 0; $i < $min_instances; $i++ ) {
                $empty_instance = [];
                foreach ( $fields as $field ) {
                    $empty_instance[ $field['name'] ] = '';
                }
                $values[] = $empty_instance;
            }
        }

        // Normalize values to match field names
        $normalized_values = $this->normalize_values_for_fields( $fields, $values );

        echo '<table class="wpuf-repeat-table" style="padding-left: 10px;">';

        // Render table header
        echo '<thead><tr>';
        foreach ( $fields as $field ) {
            echo '<th style="text-align: left">' . esc_html( $field['label'] ) . '</th>';
        }
        echo '<th></th>';
        echo '</tr></thead>';

        echo '<tbody>';

        // Calculate total instances for dynamic z-index (first row gets highest z-index)
        $total_instances = count( $normalized_values );
        // Loop through each instance
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            $z_index = $total_instances - $instance_index;
            echo '<tr class="wpuf-repeat-instance" style="position: relative; z-index: ' . esc_attr( $z_index ) . ';" data-instance="' . esc_attr( $instance_index ) . '">';

            // Render each field as a table cell
            foreach ( $fields as $field ) {
                echo '<td>';

                if ( ! $field_object = wpuf()->fields->field_exists( $field['template'] ) ) {
                    echo '</td>';
                    continue;
                }

                if ( wpuf()->fields->check_field_visibility( $field ) ) {
                    if ( is_object( $field_object ) ) {
                        // Get the value for this specific field in this instance
                        $field_value = isset( $instance_values[ $field['name'] ] ) ? $instance_values[ $field['name'] ] : '';

                        // Create a copy of the field settings and set the value
                        $field_with_value = $field;

                        // Set the appropriate property based on field type
                        if ( in_array( $field['template'], [ 'dropdown_field', 'radio_field', 'checkbox_field', 'multiple_select' ] ) ) {
                            $field_with_value['selected'] = $field_value;
                        } elseif ( $field['template'] === 'country_list_field' ) {
                            // For country list fields, set the country_list.name property
                            if ( ! isset( $field_with_value['country_list'] ) ) {
                                $field_with_value['country_list'] = [];
                            }
                            $field_with_value['country_list']['name'] = $field_value;
                        } else {
                            $field_with_value['default'] = $field_value;
                        }

                        // Modify the field name to be indexed for repeat field structure
                        // Format: repeat_field_name[instance_index][inner_field_name]
                        $field_with_value['name'] = $field_name . '[' . $instance_index . '][' . $field['name'] . ']';
                        $field_with_value['id'] = $field['id'] . '_' . $instance_index;

                        // Force post_id to null so that the field uses the pre-processed value
                        $render_post_id = null;

                        // Render the field
                        $field_object->render( $field_with_value, $form_id, $type, $render_post_id );
                    }
                }

                echo '</td>';
            }

            // Actions column
            echo '<td>';
            echo '<div class="wpuf-repeat-controls">';
            // Show add button only on the last instance, remove button on all instances (except when there's only 1)
            $is_last_instance = ($instance_index === count($normalized_values) - 1);
            $is_only_instance = (count($normalized_values) === 1);
            echo '<button type="button" class="wpuf-add-repeat" style="' . ($is_last_instance ? '' : 'display: none;') . '">+</button>';
            echo '<button type="button" class="wpuf-remove-repeat" style="' . ($is_only_instance ? 'display: none;' : '') . '">−</button>';
            echo '</div>';
            echo '</td>';

            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }
}
