<?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 );

        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 ); ?>">
             <?php
             if( !empty($field_settings['label'])) {
                ?>
                <p style="margin: 0 0 0 10px;"><?php echo esc_html( $field_settings['label'] ); ?></p>
                <hr style="margin-left: 10px;">
                <?php
             }
             ?>
            <?php
            // Wrap the repeat instances in proper structure
            $this->render_repeat_instances_wrapped( $inner_fields, $values, $form_id, $type, $post_id, $field_name, 1 );
            ?>

            <?php $this->help_text( $field_settings ); ?>
        </div>
        <script>
            ( function ( $ ) {
                'use strict';
                $( document ).ready( function () {
                    initRepeatField();

                    function initRepeatField() {
                        $( '.wpuf-repeat-container' ).each( function () {
                            var $container = $( this );
                            var fieldName = $container.data( 'field-name' );
                            var maxRepeats = parseInt( $container.data( 'max-repeats' ) ) || -1;
                            updateRepeatButtons( $container );
                            $container.on( 'click', '.wpuf-add-repeat', function () {
                                addRepeatInstance( $container, fieldName, maxRepeats );
                            } );
                            $container.on( 'click', '.wpuf-remove-repeat', function () {
                                removeRepeatInstance( $( this ).closest( '.wpuf-repeat-instance' ), $container );
                            } );
                        } );
                    }

                    function addRepeatInstance( $container, fieldName, maxRepeats ) {
                        var $instances = $container.find( '.wpuf-repeat-instance' );
                        var currentInstances = $instances.length;
                        if (maxRepeats !== -1 && currentInstances >= maxRepeats) {
                            return;
                        }
                        var $firstInstance = $instances.first();

                        // Clean up any existing JavaScript initializations in the first instance before cloning
                        if (typeof WPUF_Field_Initializer !== 'undefined') {
                            console.log('Cleaning up first instance before cloning...');
                            WPUF_Field_Initializer.cleanupInitializedFields($firstInstance);
                        }

                        var $newInstance = $firstInstance.clone();
                        var newInstanceIndex = currentInstances;
                        $newInstance.attr( 'data-instance', newInstanceIndex );

                        // Clean up any existing JavaScript initializations in the cloned instance
                        if (typeof WPUF_Field_Initializer !== 'undefined') {
                            console.log('Cleaning up cloned instance before adding...');
                            WPUF_Field_Initializer.cleanupInitializedFields($newInstance);
                        }

                        $newInstance.find( 'input, textarea, select' ).each( function () {
                            var $input = $( this );
                            var originalName = $input.attr( 'name' );
                            if (originalName && originalName.includes( '[' )) {
                                var newName = originalName.replace( /\[\d+\]/, '[' + newInstanceIndex + ']' );
                                $input.attr( 'name', newName );
                            }
                            if ($input.attr( 'type' ) === 'checkbox' || $input.attr( 'type' ) === 'radio') {
                                $input.prop( 'checked', false );
                            } else {
                                $input.val( '' );
                            }
                        } );
                        $newInstance.find( '[name], [id], [for]' ).each( function () {
                            var $element = $( this );
                            var originalName = $element.attr( 'name' );
                            var originalId = $element.attr( 'id' );
                            var originalFor = $element.attr( 'for' );
                            if (originalName && originalName.includes( '[' )) {
                                var newName = originalName.replace( /\[\d+\]/, '[' + newInstanceIndex + ']' );
                                $element.attr( 'name', newName );
                            }
                            if (originalId && originalId.includes( '[' )) {
                                var newId = originalId.replace( /\[\d+\]/, '[' + newInstanceIndex + ']' );
                                $element.attr( 'id', newId );
                            }
                            if (originalFor && originalFor.includes( '[' )) {
                                var newFor = originalFor.replace( /\[\d+\]/, '[' + newInstanceIndex + ']' );
                                $element.attr( 'for', newFor );
                            }
                        } );
                        $newInstance.find( 'input, textarea, select' ).val( '' );
                        $container.append( $newInstance );
                        reindexInstances( $container, fieldName );
                        updateRepeatButtons( $container );

                        console.log('New repeat instance added, triggering initialization event...');
                        // Trigger event for field initialization
                        $( document ).trigger( 'wpuf-repeat-instance-added', [ $newInstance ] );

                        if (typeof wpuf_conditional_logic !== 'undefined') {
                            wpuf_conditional_logic.init();
                        }
                    }

                    function removeRepeatInstance( $instance, $container ) {
                        var fieldName = $container.data( 'field-name' );
                        $instance.remove();
                        reindexInstances( $container, fieldName );
                        updateRepeatButtons( $container );
                        if (typeof wpuf_conditional_logic !== 'undefined') {
                            wpuf_conditional_logic.init();
                        }
                    }

                    function reindexInstances( $container, fieldName ) {
                        $container.find( '.wpuf-repeat-instance' ).each( function ( index ) {
                            var $instance = $( this );
                            $instance.attr( 'data-instance', index );
                            $instance.find( '[name], [id], [for]' ).each( function () {
                                var $element = $( this );
                                var originalName = $element.attr( 'name' );
                                var originalId = $element.attr( 'id' );
                                var originalFor = $element.attr( 'for' );
                                if (originalName && originalName.includes( '[' )) {
                                    var newName = originalName.replace( /\[\d+\]/, '[' + index + ']' );
                                    $element.attr( 'name', newName );
                                }
                                if (originalId && originalId.includes( '[' )) {
                                    var newId = originalId.replace( /\[\d+\]/, '[' + index + ']' );
                                    $element.attr( 'id', newId );
                                }
                                if (originalFor && originalFor.includes( '[' )) {
                                    var newFor = originalFor.replace( /\[\d+\]/, '[' + index + ']' );
                                    $element.attr( 'for', newFor );
                                }
                            } );
                        } );
                    }

                    function updateRepeatButtons( $container ) {
                        var $instances = $container.find( '.wpuf-repeat-instance' );
                        var count = $instances.length;
                        $instances.each( function ( i ) {
                            var $controls = $( this ).find( '.wpuf-repeat-controls' );
                            var isLast = i === count - 1;
                            var isOnlyOne = count === 1;

                            // Show add button only on the last instance
                            $controls.find( '.wpuf-add-repeat' ).toggle( isLast );

                            // Show remove button on all instances except when there's only one instance
                            $controls.find( '.wpuf-remove-repeat' ).toggle( !isOnlyOne );
                        } );
                    }
                } );
            } )( jQuery );
        </script>
        <style>
            .wpuf-fields.wpuf-repeat-container li {
                margin-bottom: 0 !important;
                padding-bottom: 0 !important;
            }
            .wpuf-repeat-instance li {
                margin-bottom: 0 !important;
            }
            .wpuf-repeat-controls {
                margin-left: 5px;
                margin-top: 10px;
            }
            .wpuf-repeat-controls:last-child {
                margin-bottom: 1rem;
            }
            .wpuf-repeat-controls button {
                border: 1px solid #ccc !important;
                background: #fff;
                padding: 2px 8px;
                margin-left: 5px;
                border-radius: 3px;
                cursor: pointer;
                font-size: 1rem;
                line-height: 1.4;
            }
            .wpuf-repeat-controls button:hover {
                background: #f0f0f0;
                cursor: pointer;
            }
        </style>
        <?php
    }

    /**
     * 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;
        }
        foreach ( $normalized_values as $instance_index => $instance_values ) {
            echo '<div class="wpuf-repeat-instance" 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;
                    }
                }
            }

            echo '<div class="wpuf-repeat-controls">';
            echo '<button type="button" class="wpuf-add-repeat button">+</button>';
            echo '<button type="button" class="wpuf-remove-repeat button">-</button>';
            echo '</div>';
            echo '</div>'; // Close
            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 ) {
                    $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 ) {
            echo '<div class="wpuf-repeat-instance" data-instance="' . esc_attr( $instance_index ) . '">';

            // 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
            echo '<div class="wpuf-repeat-controls">';
            echo '<button type="button" class="wpuf-add-repeat button">+</button>';
            echo '<button type="button" class="wpuf-remove-repeat button">-</button>';
            echo '</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
            echo '<div class="wpuf-repeat-controls">';
            echo '<button type="button" class="wpuf-add-repeat button">+</button>';
            echo '<button type="button" class="wpuf-remove-repeat button">-</button>';
            echo '</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_to_name[ $field['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 ( $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'      => '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',
            '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;
    }
}
