<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Renderer outputs composed form markup; field values are sanitized/escaped before output.
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
class WPEFB_Form_Renderer {

    protected $form_data;
    protected $is_multipage           = false;
    protected $has_file_field         = false;
    protected $form_meta              = array();
    protected $global_settings        = array();
    protected $show_asterisk          = true;
    protected $form_theme             = 'default';
    protected $form_layout            = 'label_top';
    protected $recaptcha_enabled      = false;
    protected $recaptcha_site_key     = '';
    protected $recaptcha_version      = 'v2';
    protected $allow_multiple_uploads = false;

    public function __construct( $form_data, $atts = array(), $settings = array() ) {
        $this->form_data              = $form_data;
        $this->is_multipage           = ( ! empty( $atts['type'] ) && $atts['type'] === 'multipage' );
        $this->has_file_field         = $this->detect_file_fields( $form_data );
        $this->form_meta              = ( ! empty( $settings['form_meta'] ) && is_array( $settings['form_meta'] ) ) ? $settings['form_meta'] : array();
        $this->global_settings        = ( ! empty( $settings['global'] ) && is_array( $settings['global'] ) ) ? $settings['global'] : array();
        $this->show_asterisk          = isset( $this->global_settings['wpefb_show_asterisk'] ) ? (bool) $this->global_settings['wpefb_show_asterisk'] : true;
        $this->form_theme             = ! empty( $this->global_settings['wpefb_form_theme'] ) ? sanitize_key( $this->global_settings['wpefb_form_theme'] ) : 'default';
        $this->form_layout            = ! empty( $this->global_settings['wpefb_form_layout'] ) ? sanitize_key( $this->global_settings['wpefb_form_layout'] ) : 'label_top';
        $this->recaptcha_enabled      = ! empty( $this->global_settings['wpefb_enable_recaptcha'] ) && ! empty( $this->global_settings['wpefb_recaptcha_site_key'] );
        $this->recaptcha_site_key     = ! empty( $this->global_settings['wpefb_recaptcha_site_key'] ) ? (string) $this->global_settings['wpefb_recaptcha_site_key'] : '';
        $this->recaptcha_version      = ! empty( $this->global_settings['wpefb_recaptcha_version'] ) ? sanitize_key( $this->global_settings['wpefb_recaptcha_version'] ) : 'v2';
        $this->allow_multiple_uploads = ! empty( $this->global_settings['wpefb_multiple_file_uploads'] );
    }


    private function build_field_input_name( $name, $multiple = false ) {
        $key = sanitize_key( (string) $name );
        if ( '' === $key ) {
            return $multiple ? 'wefb_fields[unknown][]' : 'wefb_fields[unknown]';
        }

        return $multiple ? 'wefb_fields[' . $key . '][]' : 'wefb_fields[' . $key . ']';
    }

    public function render_form( $form_id = null ) {
        ob_start();
        $form_json    = esc_attr( wp_json_encode( $this->form_data ) );
        $layout_class = in_array( $this->form_layout, array( 'label_left', 'label_top', 'two_columns' ), true ) ? $this->form_layout : 'label_top';
        $theme_class  = in_array( $this->form_theme, array( 'default', 'classic', 'matchmytheme' ), true ) ? $this->form_theme : 'default';
        echo '<div class="wefb-frontend-form-wrapper wefb-theme-' . esc_attr( $theme_class ) . ' wefb-layout-' . esc_attr( $layout_class ) . '" data-form="' . $form_json . '">';
        $enctype = $this->has_file_field ? ' enctype="multipart/form-data"' : '';
        echo '<form class="wefb-frontend-form" method="post" novalidate' . $enctype . ' data-form-id="' . esc_attr( $form_id ) . '">';

        if ( $form_id ) {
            echo '<input type="hidden" name="wefb_form_id" value="' . esc_attr( $form_id ) . '">';
        }

        echo '<input type="hidden" name="wefb_form_submit" value="1">';
        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_URI'] ) ) : '/';
        echo '<input type="hidden" name="wefb_current_url" value="' . esc_url( home_url( $request_uri ) ) . '">';
        if ( $form_id ) {
            echo wp_nonce_field( 'wefb_submit_form_' . $form_id, 'wefb_nonce', true, false );
        }

        /**
         * Render hooks for add-ons before standard field output.
         *
         * @param int|null $form_id Form identifier.
         * @param array    $form_data Form structure data.
         * @param array    $form_meta Form-level meta.
         * @param array    $global_settings Global plugin settings.
         */
        do_action( 'wpefb_before_form_render_fields', $form_id, $this->form_data, $this->form_meta, $this->global_settings );

        if ( $this->is_multipage ) {
            $this->render_multipage( $form_id );
        } else {
            foreach ( $this->form_data['sections'] as $section ) {
                // Skip divider fields in single-page mode
                if ( $this->section_contains_divider( $section ) ) {
                    continue;
                }
                $this->render_section( $section );
            }
        }

        /**
         * Render content that should appear immediately after normal field output.
         *
         * @param int|null $form_id Form identifier.
         * @param array    $form_data Form structure data.
         * @param array    $form_meta Form-level meta.
         * @param array    $global_settings Global plugin settings.
         * @param array    $context Rendering context.
         */
        do_action(
            'wpefb_after_form_render_fields',
            $form_id,
            $this->form_data,
            $this->form_meta,
            $this->global_settings,
            array(
				'is_multipage' => false,
				'is_last_page' => true,
            )
        );

        echo '<div class="wefb-form-actions">';
        if ( $this->recaptcha_enabled ) {
            $this->render_recaptcha();
        }
        /**
         * Render additional form action controls from add-ons.
         *
         * @param int|null $form_id Form identifier.
         * @param array    $form_data Form structure data.
         * @param array    $form_meta Form-level meta.
         * @param array    $global_settings Global plugin settings.
         */
        if ( ! $this->is_multipage ) {
            do_action( 'wpefb_render_form_actions', $form_id, $this->form_data, $this->form_meta, $this->global_settings );
            echo '<button type="submit">' . esc_html(
                apply_filters(
                    'wpefb_submit_button_label',
                    __( 'Submit', 'vedrixa-forms-registration-builder' ),
                    $form_id,
                    $this->form_data,
                    $this->form_meta,
                    $this->global_settings,
                    array(
						'is_multipage' => false,
						'is_last_page' => true,
                    )
                )
            ) . '</button>';
        }
        echo '</div>';

        echo '</form>';
        echo '</div>';
        return ob_get_clean();
    }

    protected function render_multipage( $form_id = null ) {
        $pages        = array();
        $current_page = array();

        foreach ( $this->form_data['sections'] as $section ) {
            $is_divider = $this->section_contains_divider( $section );

            if ( $is_divider && ! empty( $current_page ) ) {
                $pages[]      = $current_page;
                $current_page = array();
            } elseif ( ! $is_divider ) {
                $current_page[] = $section;
            }
        }

        if ( ! empty( $current_page ) ) {
            $pages[] = $current_page;
        }

        foreach ( $pages as $page_index => $sections ) {
            $is_first = ( $page_index === 0 );
            $is_last  = ( $page_index === count( $pages ) - 1 );

            echo '<div class="wefb-page" data-page-index="' . esc_attr( $page_index ) . '" style="' . ( $is_first ? '' : 'display:none;' ) . '">';

            foreach ( $sections as $section ) {
                $this->render_section( $section );
            }

            if ( $is_last ) {
                do_action(
                    'wpefb_after_form_render_fields',
                    $form_id,
                    $this->form_data,
                    $this->form_meta,
                    $this->global_settings,
                    array(
						'is_multipage' => true,
						'is_last_page' => true,
                    )
                );
            }

            echo '<div class="wefb-page-nav">';
            if ( ! $is_first ) {
                echo '<button type="button" class="wefb-prev">' . esc_html__( 'Previous', 'vedrixa-forms-registration-builder' ) . '</button>';
            }
            if ( ! $is_last ) {
                echo '<button type="button" class="wefb-next">' . esc_html__( 'Next', 'vedrixa-forms-registration-builder' ) . '</button>';
            }
            /**
             * Render additional form action controls from add-ons on multipage navigation rows.
             *
             * @param int|null $form_id Form identifier.
             * @param array    $form_data Form structure data.
             * @param array    $form_meta Form-level meta.
             * @param array    $global_settings Global plugin settings.
             */
            do_action( 'wpefb_render_form_actions', $form_id, $this->form_data, $this->form_meta, $this->global_settings );
            if ( $is_last ) {
                echo '<button type="submit">' . esc_html(
                    apply_filters(
                        'wpefb_submit_button_label',
                        __( 'Submit', 'vedrixa-forms-registration-builder' ),
                        $form_id,
                        $this->form_data,
                        $this->form_meta,
                        $this->global_settings,
                        array(
							'is_multipage' => true,
							'is_last_page' => true,
                        )
                    )
                ) . '</button>';
            }
            echo '</div>';

            echo '</div>';
        }
    }

    protected function section_contains_divider( $section ) {
        if ( ! empty( $section['fields'] ) && is_array( $section['fields'] ) ) {
            foreach ( $section['fields'] as $field ) {
                if ( isset( $field['type'] ) && $field['type'] === 'divider' ) {
                    return true;
                }
            }
        }
        return false;
    }

    protected function render_section( $section ) {
        $columns          = ! empty( $section['columns'] ) ? intval( $section['columns'] ) : 1;
        $conditional_data = '';
        $style            = '';
        if ( isset( $section['conditional_logic'] ) && ( is_array( $section['conditional_logic'] ) || is_object( $section['conditional_logic'] ) ) ) {
            $conditional_data = esc_attr( wp_json_encode( $section['conditional_logic'] ) );
            if ( ( is_array( $section['conditional_logic'] ) && ! empty( $section['conditional_logic']['enabled'] ) )
                || ( is_object( $section['conditional_logic'] ) && ! empty( $section['conditional_logic']->enabled ) ) ) {
                $style = ' style="display:none;"';
            }
        }

        echo '<div class="wefb-section columns-' . esc_attr( $columns ) . '" data-conditional="' . $conditional_data . '"' . $style . '>';

        if ( ! empty( $section['fields'] ) && is_array( $section['fields'] ) ) {
            foreach ( $section['fields'] as $field ) {
                if ( isset( $field['type'] ) && $field['type'] === 'divider' ) {
                    continue; // skip rendering divider as a field
                }
                $this->render_field( $field );
            }
        }

        echo '</div>';
    }

    protected function render_recaptcha() {
        $version  = in_array( $this->recaptcha_version, array( 'v2', 'v3' ), true ) ? $this->recaptcha_version : 'v2';
        $site_key = esc_attr( $this->recaptcha_site_key );
        echo '<div class="wefb-recaptcha wefb-recaptcha-' . esc_attr( $version ) . '">';
        if ( 'v3' === $version ) {
            echo '<input type="hidden" name="wefb_recaptcha_token" class="wefb-recaptcha-token" value="" />';
        } else {
            echo '<div class="g-recaptcha" data-sitekey="' . $site_key . '"></div>';
        }
        echo '</div>';
    }

    protected function required_marker( $required ) {
        if ( ! $required || ! $this->show_asterisk ) {
            return '';
        }
        return ' <span class="wefb-required-marker">*</span>';
    }

    protected function render_field( $field ) {
        $field_id        = ! empty( $field['id'] ) ? sanitize_html_class( $field['id'] ) : uniqid( 'field_' );
        $name            = ! empty( $field['name'] ) ? sanitize_key( $field['name'] ) : $field_id;
        $label           = ! empty( $field['label'] ) ? esc_html( $field['label'] ) : '';
        $placeholder     = ! empty( $field['placeholder'] ) ? esc_attr( $field['placeholder'] ) : '';
        $required        = ! empty( $field['required'] ) ? 'required' : '';
        $max_length_attr = '';
        if ( isset( $field['max_length'] ) && '' !== (string) $field['max_length'] && null !== $field['max_length'] ) {
            $max_length = absint( $field['max_length'] );
            if ( $max_length > 0 ) {
                $max_length_attr = ' maxlength="' . esc_attr( $max_length ) . '"';
            }
        }

        $conditional_data = '';
        $style            = '';
        if ( isset( $field['conditional_logic'] ) && ( is_array( $field['conditional_logic'] ) || is_object( $field['conditional_logic'] ) ) ) {
            $conditional_data = esc_attr( wp_json_encode( $field['conditional_logic'] ) );

            if ( ( is_array( $field['conditional_logic'] ) && ! empty( $field['conditional_logic']['enabled'] ) )
                || ( is_object( $field['conditional_logic'] ) && ! empty( $field['conditional_logic']->enabled ) ) ) {
                $style = 'style="display:none;"';
            }
        }

        $data_type = isset( $field['type'] ) ? sanitize_key( $field['type'] ) : 'text';
        if ( class_exists( 'WPEFB_Features' ) && ! WPEFB_Features::is_field_type_available( $data_type ) ) {
            return;
        }
        $css_class        = ! empty( $field['css_class'] ) ? sanitize_html_class( $field['css_class'] ) : '';
        $additional_class = '';
        if ( ! empty( $css_class ) ) {
            $additional_class = ' ' . esc_attr( $css_class );
        }

        $type_class = ' wefb-field-type-' . sanitize_html_class( $data_type );
        echo '<div class="wefb-field' . $type_class . $additional_class . '" data-id="' . esc_attr( $field_id ) . '" data-name="' . esc_attr( $name ) . '" data-type="' . esc_attr( $data_type ) . '" data-conditional="' . $conditional_data . '" ' . $style . '>';

        $type          = strtolower( $field['type'] ?? 'text' );
        $default_value = '';
        if ( array_key_exists( 'default_value', $field ) ) {
            $default_value = (string) $field['default_value'];
        } elseif ( array_key_exists( 'defaultValue', $field ) ) {
            $default_value = (string) $field['defaultValue'];
        } elseif ( ! empty( $field['options'] ) && is_array( $field['options'] ) ) {
            foreach ( $field['options'] as $opt ) {
                if ( ( isset( $opt['default'] ) && $opt['default'] )
                    || ( isset( $opt['selected'] ) && $opt['selected'] )
                    || ( isset( $opt['is_default'] ) && $opt['is_default'] ) ) {
                    $default_value = isset( $opt['value'] ) ? (string) $opt['value'] : '';
                    break;
                }
            }
        }

        $custom_field_context = array(
            'field'                => $field,
            'field_id'             => $field_id,
            'name'                 => $name,
            'label'                => $label,
            'placeholder'          => $placeholder,
            'required_attr'        => $required,
            'required_marker'      => $this->required_marker( $required ),
            'max_length_attr'      => $max_length_attr,
            'default_value'        => $default_value,
            'input_name'           => $this->build_field_input_name( $name ),
            'input_name_multiple'  => $this->build_field_input_name( $name, true ),
            'allow_multiple_files' => $this->allow_multiple_uploads,
            'global_settings'      => $this->global_settings,
        );

        $custom_field_html = apply_filters( 'wpefb_render_custom_field_html', null, $type, $custom_field_context, $this );
        if ( null !== $custom_field_html ) {
            echo $custom_field_html;
            echo '</div>';
            return;
        }

        switch ( $type ) {
            case 'heading':
                $tag  = ! empty( $field['heading_tag'] ) ? tag_escape( $field['heading_tag'] ) : 'h3';
                $text = ! empty( $field['heading_text'] ) ? $field['heading_text'] : $label;
                echo '<' . $tag . ' class="wefb-heading">' . esc_html( $text ) . '</' . $tag . '>';
                break;

            case 'paragraph':
                $text = ! empty( $field['paragraph_text'] ) ? $field['paragraph_text'] : $placeholder;
                echo '<p class="wefb-paragraph">' . esc_html( $text ) . '</p>';
                break;

            case 'divider':
                echo '<hr class="wefb-divider" />';
                break;

            case 'spacing':
                $height = isset( $field['height'] ) ? (int) $field['height'] : 16;
                echo '<div class="wefb-spacing" style="height:' . esc_attr( $height ) . 'px"></div>';
                break;

            case 'textarea':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $rows = isset( $field['rows'] ) ? (int) $field['rows'] : 4;
                $cols = isset( $field['columns'] ) ? (int) $field['columns'] : 50;
                echo '<textarea id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" rows="' . esc_attr( $rows ) . '" cols="' . esc_attr( $cols ) . '" placeholder="' . $placeholder . '" ' . $required . $max_length_attr . '>' . esc_textarea( $default_value ) . '</textarea>';
                break;

            case 'select':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                echo '<select id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" ' . $required . '>';
                $prompt_option = '';
                if ( ! empty( $field['placeholder'] ) ) {
                    $prompt_option = (string) $field['placeholder'];
                } elseif ( ! empty( $field['first_option'] ) ) {
                    $prompt_option = (string) $field['first_option'];
                }
                if ( '' !== $prompt_option ) {
                    $selected_prompt = ( '' === $default_value ) ? ' selected' : '';
                    echo '<option value=""' . $selected_prompt . '>' . esc_html( $prompt_option ) . '</option>';
                }
                if ( ! empty( $field['options'] ) && is_array( $field['options'] ) ) {
                    foreach ( $field['options'] as $opt ) {
                        if ( !isset( $opt['value'] ) || !isset( $opt['label'] ) ) {
                            continue;
                        }
                        if ( $default_value !== '' && (string) $opt['value'] === $default_value ) {
                            echo '<option value="' . esc_attr( $opt['value'] ) . '" selected>' . esc_html( $opt['label'] ) . '</option>';
                            continue;
                        }
                        echo '<option value="' . esc_attr( $opt['value'] ) . '">' . esc_html( $opt['label'] ) . '</option>';
                    }
                }
                echo '</select>';
                break;

            case 'radio':
                if ( $label ) {
                    echo '<span class="wefb-label">' . esc_html( $label ) . $this->required_marker( $required ) . '</span>';
                }
                echo '<div class="wefb-choice-group" role="group" aria-label="' . esc_attr( wp_strip_all_tags( $label ) ) . '">';
                if ( ! empty( $field['options'] ) && is_array( $field['options'] ) ) {
                    foreach ( $field['options'] as $opt ) {
                        if ( !isset( $opt['value'] ) || !isset( $opt['label'] ) ) {
                            continue;
                        }
                        $option_id = esc_attr( $field_id . '_' . sanitize_html_class( $opt['value'] ) );
                        $checked   = ( $default_value !== '' && (string) $opt['value'] === $default_value ) ? ' checked' : '';
                        echo '<label class="wefb-inline wefb-choice" for="' . $option_id . '"><input type="radio" id="' . $option_id . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" value="' . esc_attr( $opt['value'] ) . '" ' . $required . $checked . '> ' . esc_html( $opt['label'] ) . '</label>';
                    }
                }
                echo '</div>';
                break;

            case 'checkbox':
                if ( ! empty( $field['options'] ) && is_array( $field['options'] ) ) {
                    if ( $label ) {
                        echo '<span class="wefb-label">' . esc_html( $label ) . $this->required_marker( $required ) . '</span>';
                    }
                    $selected_values = array();
                    if ( is_array( $default_value ) ) {
                        $selected_values = array_map( 'strval', $default_value );
                    } elseif ( is_string( $default_value ) && '' !== trim( $default_value ) ) {
                        $selected_values = array_map( 'trim', explode( ',', $default_value ) );
                    }
                    echo '<div class="wefb-choice-group" role="group" aria-label="' . esc_attr( wp_strip_all_tags( $label ) ) . '">';
                    $index = 0;
                    foreach ( $field['options'] as $opt ) {
                        if ( ! isset( $opt['value'] ) || ! isset( $opt['label'] ) ) {
                            continue;
                        }
                        $option_id     = esc_attr( $field_id . '_' . sanitize_html_class( $opt['value'] ) );
                        $checked       = in_array( (string) $opt['value'], $selected_values, true ) ? ' checked' : '';
                        $required_once = ( 0 === $index && ! empty( $required ) ) ? ' required' : '';
                        echo '<label class="wefb-inline wefb-choice" for="' . $option_id . '"><input type="checkbox" id="' . $option_id . '" name="' . esc_attr( $this->build_field_input_name( $name, true ) ) . '" value="' . esc_attr( $opt['value'] ) . '"' . $required_once . $checked . '> ' . esc_html( $opt['label'] ) . '</label>';
                        $index++;
                    }
                    echo '</div>';
                } else {
                    $checked = ( $default_value === '1' || $default_value === 'true' || $default_value === 'yes' ) ? ' checked' : '';
                    echo '<label class="wefb-inline wefb-choice"><input type="checkbox" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" value="1" ' . $required . $checked . '> ' . esc_html( $label ) . '</label>';
                }
                break;

            case 'gender':
                $gender_options = ! empty( $field['options'] ) ? $field['options'] : array(
                    array(
                        'value' => 'male',
                        'label' => __( 'Male', 'vedrixa-forms-registration-builder' ),
                    ),
                    array(
                        'value' => 'female',
                        'label' => __( 'Female', 'vedrixa-forms-registration-builder' ),
                    ),
                    array(
                        'value' => 'other',
                        'label' => __( 'Other', 'vedrixa-forms-registration-builder' ),
                    ),
                );
                if ( $label ) {
                    echo '<span class="wefb-label">' . esc_html( $label ) . $this->required_marker( $required ) . '</span>';
                }
                echo '<div class="wefb-choice-group" role="group" aria-label="' . esc_attr( wp_strip_all_tags( $label ) ) . '">';
                foreach ( $gender_options as $opt ) {
                    $option_id = esc_attr( $field_id . '_' . sanitize_html_class( $opt['value'] ) );
                    $checked   = ( $default_value !== '' && (string) $opt['value'] === $default_value ) ? ' checked' : '';
                    echo '<label class="wefb-inline wefb-choice" for="' . $option_id . '"><input type="radio" id="' . $option_id . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" value="' . esc_attr( $opt['value'] ) . '" ' . $required . $checked . '> ' . esc_html( $opt['label'] ) . '</label>';
                }
                echo '</div>';
                break;

            case 'language':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $language_options = ! empty( $field['options'] ) && is_array( $field['options'] ) ? $field['options'] : array(
                    array(
						'value' => 'en',
						'label' => __( 'English', 'vedrixa-forms-registration-builder' ),
					),
                    array(
						'value' => 'es',
						'label' => __( 'Spanish', 'vedrixa-forms-registration-builder' ),
					),
                    array(
						'value' => 'fr',
						'label' => __( 'French', 'vedrixa-forms-registration-builder' ),
					),
                    array(
						'value' => 'de',
						'label' => __( 'German', 'vedrixa-forms-registration-builder' ),
					),
                    array(
						'value' => 'hi',
						'label' => __( 'Hindi', 'vedrixa-forms-registration-builder' ),
					),
                );
                echo '<select id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" ' . $required . '>';
                $prompt = ! empty( $placeholder ) ? $placeholder : __( 'Select language', 'vedrixa-forms-registration-builder' );
                echo '<option value=""' . ( '' === $default_value ? ' selected' : '' ) . '>' . esc_html( $prompt ) . '</option>';
                foreach ( $language_options as $opt ) {
                    if ( ! isset( $opt['value'] ) || ! isset( $opt['label'] ) ) {
                        continue;
                    }
                    $selected = ( $default_value !== '' && (string) $opt['value'] === (string) $default_value ) ? ' selected' : '';
                    echo '<option value="' . esc_attr( $opt['value'] ) . '"' . $selected . '>' . esc_html( $opt['label'] ) . '</option>';
                }
                echo '</select>';
                break;

            case 'country':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                echo '<select id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" ' . $required . '>';
                $prompt = ! empty( $placeholder ) ? $placeholder : __( 'Select country', 'vedrixa-forms-registration-builder' );
                echo '<option value=""' . ( '' === $default_value ? ' selected' : '' ) . '>' . esc_html( $prompt ) . '</option>';
                foreach ( $this->get_countries() as $code => $country_name ) {
                    $selected = ( $default_value !== '' && (string) $code === (string) $default_value ) ? ' selected' : '';
                    echo '<option value="' . esc_attr( $code ) . '"' . $selected . '>' . esc_html( $country_name ) . '</option>';
                }
                echo '</select>';
                break;

            case 'timezone':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                echo '<select id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" ' . $required . '>';
                $prompt = ! empty( $placeholder ) ? $placeholder : __( 'Select timezone', 'vedrixa-forms-registration-builder' );
                echo '<option value=""' . ( '' === $default_value ? ' selected' : '' ) . '>' . esc_html( $prompt ) . '</option>';
                foreach ( timezone_identifiers_list() as $tz ) {
                    $selected = ( $default_value !== '' && (string) $tz === (string) $default_value ) ? ' selected' : '';
                    echo '<option value="' . esc_attr( $tz ) . '"' . $selected . '>' . esc_html( $tz ) . '</option>';
                }
                echo '</select>';
                break;

            case 'datepicker':
            case 'date':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $value = $default_value !== '' ? ' value="' . esc_attr( $default_value ) . '"' : '';
                echo '<input type="date" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '"' . $value . ' ' . $required . ' />';
                break;

            case 'email':
            case 'user_email':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $value = $default_value !== '' ? ' value="' . esc_attr( $default_value ) . '"' : '';
                echo '<input type="email" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" placeholder="' . $placeholder . '"' . $value . ' ' . $required . $max_length_attr . ' />';
                break;

            case 'number':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $min   = isset( $field['min'] ) ? ' min="' . esc_attr( $field['min'] ) . '"' : '';
                $max   = isset( $field['max'] ) ? ' max="' . esc_attr( $field['max'] ) . '"' : '';
                $value = $default_value !== '' ? ' value="' . esc_attr( $default_value ) . '"' : '';
                echo '<input type="number" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" placeholder="' . $placeholder . '"' . $value . ' ' . $required . $min . $max . ' />';
                break;

            case 'url':
            case 'website':
            case 'facebook':
            case 'twitter':
            case 'google':
            case 'linked_in':
            case 'youtube':
            case 'mixcloud':
            case 'soundcloud':
            case 'instagram':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $placeholder_url = ! empty( $placeholder ) ? $placeholder : __( 'https://example.com', 'vedrixa-forms-registration-builder' );
                $value           = $default_value !== '' ? ' value="' . esc_attr( $default_value ) . '"' : '';
                echo '<input type="url" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" placeholder="' . esc_attr( $placeholder_url ) . '"' . $value . ' ' . $required . $max_length_attr . ' />';
                break;

            case 'user_pass':
            case 'confirm_pass':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $value               = $default_value !== '' ? ' value="' . esc_attr( $default_value ) . '"' : '';
                $min_password_length = isset( $field['password_min_length'] ) ? absint( $field['password_min_length'] ) : 8;
                $min_password_length = $min_password_length > 0 ? $min_password_length : 8;
                $require_uppercase   = ! empty( $field['password_require_uppercase'] ) ? '1' : '0';
                $require_lowercase   = array_key_exists( 'password_require_lowercase', $field ) ? ( ! empty( $field['password_require_lowercase'] ) ? '1' : '0' ) : '1';
                $require_number      = ! empty( $field['password_require_number'] ) ? '1' : '0';
                $require_special     = ! empty( $field['password_require_special'] ) ? '1' : '0';
                $show_strength       = array_key_exists( 'password_show_strength', $field ) ? ( ! empty( $field['password_show_strength'] ) ? '1' : '0' ) : '1';
                $is_confirm          = ( 'confirm_pass' === $type ) ? '1' : '0';
                echo '<div class="wefb-password-wrap">';
                echo '<input type="password" class="wefb-password-input" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" placeholder="' . $placeholder . '"' . $value . ' ' . $required . $max_length_attr . ' data-password-role="' . esc_attr( $type ) . '" data-password-min-length="' . esc_attr( $min_password_length ) . '" data-password-require-uppercase="' . esc_attr( $require_uppercase ) . '" data-password-require-lowercase="' . esc_attr( $require_lowercase ) . '" data-password-require-number="' . esc_attr( $require_number ) . '" data-password-require-special="' . esc_attr( $require_special ) . '" data-password-show-strength="' . esc_attr( $show_strength ) . '" data-password-confirm="' . esc_attr( $is_confirm ) . '" />';
                echo '<button type="button" class="wefb-password-toggle" data-target="' . esc_attr( $field_id ) . '">' . esc_html__( 'Show', 'vedrixa-forms-registration-builder' ) . '</button>';
                echo '</div>';
                if ( 'user_pass' === $type && '1' === $show_strength ) {
                    echo '<div class="wefb-password-strength" data-for="' . esc_attr( $field_id ) . '">';
                    echo '<span class="wefb-password-strength-label">' . esc_html__( 'Password strength: ', 'vedrixa-forms-registration-builder' ) . '</span>';
                    echo '<span class="wefb-password-strength-value">' . esc_html__( 'Weak', 'vedrixa-forms-registration-builder' ) . '</span>';
                    echo '</div>';
                }
                break;

            case 'description':
                if ( $label ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $rows = isset( $field['rows'] ) ? (int) $field['rows'] : 4;
                echo '<textarea id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" rows="' . esc_attr( $rows ) . '" placeholder="' . $placeholder . '" ' . $required . $max_length_attr . '>' . esc_textarea( $default_value ) . '</textarea>';
                break;

            default:
                if ( $label && ! in_array( $type, array( 'hidden' ), true ) ) {
                    echo '<label for="' . esc_attr( $field_id ) . '">' . $label . $this->required_marker( $required ) . '</label>';
                }
                $type_attr = in_array( $type, array( 'hidden', 'text', 'first_name', 'last_name', 'user_name', 'nickname', 'phone_number', 'mobile_number', 'description' ), true ) ? 'text' : $type;
                $value     = isset( $field['default_value'] ) ? ' value="' . esc_attr( $field['default_value'] ) . '"' : '';
                echo '<input type="' . esc_attr( $type_attr ) . '" id="' . esc_attr( $field_id ) . '" name="' . esc_attr( $this->build_field_input_name( $name ) ) . '" placeholder="' . $placeholder . '"' . $value . ' ' . $required . $max_length_attr . ' />';
                break;
        }

        echo '</div>';
    }

    /**
     * Check if form data contains any file upload field.
     *
     * @param array $form_data Form configuration.
     * @return bool
     */
    protected function detect_file_fields( $form_data ) {
        $file_types = (array) apply_filters( 'wpefb_file_field_types', array() );
        $file_types = array_filter( array_map( 'sanitize_key', $file_types ) );

        if ( empty( $file_types ) ) {
            return false;
        }

        if ( empty( $form_data['sections'] ) || ! is_array( $form_data['sections'] ) ) {
            return false;
        }

        foreach ( $form_data['sections'] as $section ) {
            if ( empty( $section['fields'] ) || ! is_array( $section['fields'] ) ) {
                continue;
            }
            foreach ( $section['fields'] as $field ) {
                $type = isset( $field['type'] ) ? sanitize_key( $field['type'] ) : '';
                if ( in_array( $type, $file_types, true ) ) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Provide a basic list of countries for the country field type.
     *
     * @return array
     */
    protected function get_countries() {
        return array(
            'US' => __( 'United States', 'vedrixa-forms-registration-builder' ),
            'CA' => __( 'Canada', 'vedrixa-forms-registration-builder' ),
            'GB' => __( 'United Kingdom', 'vedrixa-forms-registration-builder' ),
            'AU' => __( 'Australia', 'vedrixa-forms-registration-builder' ),
            'IN' => __( 'India', 'vedrixa-forms-registration-builder' ),
            'DE' => __( 'Germany', 'vedrixa-forms-registration-builder' ),
            'FR' => __( 'France', 'vedrixa-forms-registration-builder' ),
            'ES' => __( 'Spain', 'vedrixa-forms-registration-builder' ),
            'IT' => __( 'Italy', 'vedrixa-forms-registration-builder' ),
            'BR' => __( 'Brazil', 'vedrixa-forms-registration-builder' ),
            'MX' => __( 'Mexico', 'vedrixa-forms-registration-builder' ),
            'JP' => __( 'Japan', 'vedrixa-forms-registration-builder' ),
            'CN' => __( 'China', 'vedrixa-forms-registration-builder' ),
            'ZA' => __( 'South Africa', 'vedrixa-forms-registration-builder' ),
        );
    }
}
// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped

if ( ! class_exists( 'WEFB_Form_Renderer' ) ) {
	class_alias( 'WPEFB_Form_Renderer', 'WEFB_Form_Renderer' );
}
