<?php

namespace WeDevs\Wpuf\Pro\Frontend;

use WeDevs\Wpuf\Admin\Forms\Form;
use WeDevs\Wpuf\Render_Form;
use WeDevs\Wpuf\Traits\FieldableTrait;
use WeDevs\Wpuf\WPUF_User;
use WeDevs\Wpuf\Pro\Fields\Field_Password;

/**
 *  Frontend Profile Form Manager Class
 *
 * @since 3.1.0
 **/
class Profile_Form extends Render_Form {

    use FieldableTrait;

    public function __construct() {
        // ajax requests
        add_action( 'init', array( $this, 'resend_activation_email' ) );
        add_action( 'wpuf_upload_file_init', array( $this, 'add_avatar_image_size' ), 10, 2 );
        add_action( 'init', [ $this, 'enqueue_preview_page_assets' ] );
    }

    /**
     * Add post shortcode handler
     *
     * @param array $atts
     *
     * @return string
     **/
    public function shortcode_handler( $atts ) {
        add_filter( 'wpuf_form_fields', array( $this, 'add_field_settings' ) );
        //phpcs:ignore
        extract(
            shortcode_atts(
                array(
                    'id' => 0,
                    'type' => 'registration',
                ), $atts
            )
        );

        //registration time redirect to subscription
        if ( $type === 'registration' ) {
            $is_fource_pack = wpuf_get_option( 'register_subscription', 'wpuf_payment' );

            if ( ( $is_fource_pack === 'on' && ! isset( $_GET['type'] ) ) || ( $is_fource_pack === 'on' && $_GET['type'] !== 'wpuf_sub' ) ) {
                $subscription_page_id = wpuf_get_option( 'subscription_page', 'wpuf_payment' );

                if ( wpuf_is_vendor_reg( $id ) && function_exists( 'dokan_get_option' ) ) {
                    $subscription_page_id = dokan_get_option( 'subscription_pack', 'dokan_product_subscription', 0 );
                }

                if ( empty( $subscription_page_id ) ) {
                    esc_attr_e( 'Please select subscription page', 'wpuf-pro' );

                    return '';
                } elseif ( ! is_admin() && ! defined( 'DOING_AJAX' ) && ! defined( 'REST_REQUEST' ) ) {
                    wp_redirect( get_permalink( $subscription_page_id ) );
                    exit;
                }
            }
        }

        $form          = new Form( $id );
        $form_fields   = $form->get_fields();
        $form_settings = $form->get_settings();

        // Conditionally enqueue template styles based on form settings
        $this->conditionally_enqueue_template_styles( $form_settings );

        if ( ! $form_fields ) {
            return '';
        }

        ob_start();

        if ( $type === 'profile' ) {
            if ( is_user_logged_in() ) {
                if ( isset( $_GET['msg'] ) && $_GET['msg'] === 'profile_update' ) {
                    echo '<div class="wpuf-success">';
                    echo $form_settings['update_message'];
                    echo '</div>';
                }

                $this->profile_edit( $id, $form_fields, $form_settings );
            } else {
                echo '<div class="wpuf-info">' . __( 'Please login to update your profile!', 'wpuf-pro' ) . '</div>';
            }
        } elseif ( $type === 'registration' ) {
            if ( is_user_logged_in() && ! is_admin() ) {
                echo '<div class="wpuf-info">' . __( 'You are already logged in!', 'wpuf-pro' ) . '</div>';
            } else {
                if ( is_multisite() ) {
                    $reg_enabled = get_site_option( 'registration' ) === 'user' ? true : false;
                } else {
                    $reg_enabled = intval( get_option( 'users_can_register' ) ) === 1 ? true : false;
                }
                if ( ! $reg_enabled ) {
                    echo '<div class="wpuf-info">';
                    esc_attr_e( 'User registration disabled, please contact the admin to enable.', 'wpuf-pro' );
                    echo '</div>';
                } else {
                    $this->profile_edit( $id, $form_fields, $form_settings );
                }
            }
        }

        $content = ob_get_contents();

        ob_end_clean();

        return $content;
    }

    public function user_register() {
        check_ajax_referer( 'wpuf_form_add' );
        add_filter( 'wpuf_form_fields', array( $this, 'add_field_settings' ) );

        @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );

        $form_id               = isset( $_POST['form_id'] ) ? intval( $_POST['form_id'] ) : 0;
        $form                  = new Form( $form_id );
        $form_settings         = $form->get_settings();
        $form_fields           = $form->get_fields();
        $wpuf_user_status      = isset( $form_settings['wpuf_user_status'] ) ? $form_settings['wpuf_user_status'] : '';
        $user_notification     = isset( $form_settings['user_notification'] ) ? $form_settings['user_notification'] : 'off';
        $attachments_to_delete = ! empty( $_POST['delete_attachments'] ) ? sanitize_text_field( wp_unslash( $_POST['delete_attachments'] ) ) : [];

        if ( ! empty( $attachments_to_delete) ) {
            foreach ( $attachments_to_delete as $attach_id ) {
                wp_delete_attachment( $attach_id, true );
            }
        }

        list( $user_vars, $taxonomy_vars, $meta_vars ) = $this->get_input_fields( $form_fields );
        $this->on_edit_no_check_recaptcha( $user_vars );

        $has_username_field = false;
        $username           = '';
        $user_email         = '';
        $firstname          = '';
        $lastname           = '';

        // don't let to be registered if no email address given
        if ( ! isset( $_POST['user_email'] ) || empty( $_POST['user_email'] ) ) {
            wp_send_json_error(
                [
                    'success' => false,
                    'error'   => __( 'An Email address is required', 'wpuf-pro' ),
                ]
            );
        }

        // if any username given, check if it exists
        if ( $this->search( $user_vars, 'name', 'user_login' ) ) {
            $has_username_field = true;
            $username = sanitize_user( trim( isset( $_POST['user_login'] ) ? sanitize_text_field( wp_unslash( $_POST['user_login'] ) ) : '' ) );

            if ( username_exists( $username ) ) {
                $username_error = __( 'Username already exists.', 'wpuf-pro' );
                wp_send_json_error(
                    [
                        'success' => false,
                        'error'   => apply_filters( 'wpuf_duplicate_username_error', $username_error, $form_settings ),
                    ]
                );
            }
        }

        // if any email address given, check if it exists
        if ( $this->search( $user_vars, 'name', 'user_email' ) ) {
            $user_email = trim( isset( $_POST['user_email'] ) ? sanitize_text_field( wp_unslash( $_POST['user_email'] ) ) : '' );
            if ( email_exists( $user_email ) ) {
                wp_send_json_error(
                    [
                        'success' => false,
                        'error'   => __( 'E-mail address already exists.', 'wpuf-pro' ),
                    ]
                );
            }
        }

        // if there isn't any username field in the form, lets guess a username
        if ( ! $has_username_field ) {
            $username = $this->guess_username( $user_email );
        }

        if ( ! validate_username( $username ) ) {
            wp_send_json_error(
                [
                    'success' => false,
                    'error'   => __( 'Username is not valid', 'wpuf-pro' ),
                ]
            );
        }

        // verify password
        $pass_element = $this->search( $user_vars, 'name', 'password' );
        if ( $pass_element ) {
            $pass_element    = current( $pass_element );
            $password        = isset( $_POST['pass1'] ) ? trim( $_POST['pass1'] ) : false;
            $password_repeat = isset( $_POST['pass2'] ) ? trim( $_POST['pass2'] ) : false;

            // min length check
            if ( strlen( $password ) < intval( $pass_element['min_length'] ) ) {
                wp_send_json_error(
                    [
                        'success' => false,
                        'error'   => sprintf(
                            // translators: %s: pass length
                            __( 'Password must be %s character long', 'wpuf-pro' ),
                            $pass_element['min_length']
                        ),
                    ]
                );
            }

            // Validate password requirements
            $password_validation_error = $this->validate_password_requirements( $password, $pass_element );
            if ( $password_validation_error ) {
                wp_send_json_error(
                    [
                        'success' => false,
                        'error'   => $password_validation_error,
                    ]
                );
            }

            // repeat password check
            if ( ( $password !== $password_repeat ) && $password_repeat !== false ) {
                wp_send_json_error(
                    [
                        'success' => false,
                        'error'   => __( 'Password didn\'t match', 'wpuf-pro' ),
                    ]
                );
            }
        } else {
            $password = wp_generate_password();
        }

        // default WP registration hook
        $errors = new \WP_Error();
        do_action( 'register_post', $username, $user_email, $errors );

        $errors = apply_filters( 'registration_errors', $errors, $username, $user_email );

        if ( $errors->get_error_code() ) {
            wp_send_json_error(
                [
                    'success' => false,
                    'error'   => $errors->get_error_message(),
                ]
            );
        }

        // seems like we don't have any error. Lets register the user
        $user_id = wp_create_user( $username, $password, $user_email );

        if ( is_wp_error( $user_id ) ) {
            wp_send_json_error(
                [
                    'success' => false,
                    'error'   => $user_id->get_error_message(),
                ]
            );
        } else {
            $userdata = array(
                'ID'          => $user_id,
                'first_name'  => $this->search( $user_vars, 'name', 'first_name' ) && isset( $_POST['first_name'] ) ? strip_shortcodes( sanitize_text_field( wp_unslash( $_POST['first_name'] ) ) ) : '',
                'last_name'   => $this->search( $user_vars, 'name', 'last_name' ) && isset( $_POST['last_name'] ) ? strip_shortcodes( sanitize_text_field( wp_unslash( $_POST['last_name'] ) ) ) : '',
                'display_name' => isset( $_POST['display_name'] ) ? strip_shortcodes( sanitize_text_field( wp_unslash( $_POST['display_name'] ) ) ) : '',
                'nickname'    => $this->search( $user_vars, 'name', 'nickname' ) && isset( $_POST['nickname'] ) ? strip_shortcodes( sanitize_text_field( wp_unslash( $_POST['nickname'] ) ) ) : '',
                'user_url'    => $this->search( $user_vars, 'name', 'user_url' ) && isset( $_POST['user_url'] ) ? strip_shortcodes( esc_url_raw( wp_unslash( $_POST['user_url'] ) ) ) : '',
                'description' => $this->search( $user_vars, 'name', 'description' ) && isset( $_POST['description'] ) ? strip_shortcodes( sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) ) : '',
                'role'        => $form_settings['role'],
            );

            $user_id = wp_update_user( apply_filters( 'wpuf_register_user_args', $userdata ) );

            if ( $user_id ) {
                if (
                    isset( $form_settings['notification_type'] )
                    && 'email_verification' === $form_settings['notification_type']
                ) {
                    update_user_meta( $user_id, 'wpuf_user_status', 'pending' );
                    $wpuf_user_status = 'pending';
                }

                $status             = isset( $form_settings['wpuf_user_status'] ) ? $form_settings['wpuf_user_status'] : 'pending';

                // update meta fields
                $this->update_user_meta( $meta_vars, $user_id );

                // send user notification or email verification
                if ( isset( $form_settings['user_notification'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['user_notification'] ) ) {
                    $this->send_user_notification(
                        $user_id,
                        $user_email,
                        $form_settings['notification_type'],
                        $form_id
                    );
                }

                // send user email if admin approval required
                if ( 'pending' === $status ) {
                    $this->user_status_update_notification( $status, $user_id );
                }

                // send admin notification
                if ( ! empty( $form_settings['admin_notification'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['admin_notification'] ) ) {
                    $this->admin_email_notification( $status, $user_id, $form_id, $form_settings );
                }

                /**
                 * Fires after a user successfully registers through a registration form.
                 *
                 * @since 2.9.0
                 *
                 * @since 4.2.6 Added $user_vars, $taxonomy_vars, and $meta_vars parameters.
                 *
                 * @param int    $user_id        The newly registered user ID.
                 * @param int    $form_id        The registration form ID.
                 * @param array  $form_settings  The form settings array.
                 * @param array  $user_vars      Array of user field variables from the form.
                 * @param array  $taxonomy_vars  Array of taxonomy field variables from the form.
                 * @param array  $meta_vars      Array of meta field variables from the form.
                 */
                do_action( 'wpuf_after_register', $user_id, $form_id, $form_settings, $user_vars, $taxonomy_vars, $meta_vars );

                //redirect URL
                $show_message = false;
                $redirect_to = '';

                if ( ! empty( $form_settings['reg_redirect_to'] ) ) {
                    switch ( $form_settings['reg_redirect_to'] ) {
                        case 'page':
                            $redirect_to = get_permalink( $form_settings['reg_page_id'] );
                            break;
                        case 'url':
                            $redirect_to = $form_settings['registration_url'];
                            break;
                        case 'same':
                            $show_message = true;
                            $redirect_to = add_query_arg( [ 'msg' => 'profile_update' ], wp_get_referer() );
                            break;
                    }
                }

                if ( 'pending' === $wpuf_user_status &&
                     wpuf_is_checkbox_or_toggle_on( $user_notification ) &&
                     isset( $form_settings['notification_type'] ) &&
                     'email_verification' === $form_settings['notification_type'] ) {
                    $success_message = __( 'Please check your email for activation link', 'wpuf-pro' );
                } elseif ( isset( $form_settings['message'] ) && ! empty( $form_settings['message'] ) ) {
                    $success_message = $form_settings['message'];
                } elseif ( 'pending' === $wpuf_user_status ) {
                    $success_message = __( 'Registration successful. Please wait for admin approval', 'wpuf-pro' );
                } else {
                    $success_message = __( 'Registration successful', 'wpuf-pro' );
                }

                // send the response
                $response = array(
                    'success'      => true,
                    'post_id'      => $user_id,
                    'redirect_to'  => $redirect_to,
                    'show_message' => $show_message,
                    'message'      => $success_message,
                );

                $autologin_after_registration = wpuf_get_option( 'autologin_after_registration', 'wpuf_profile', 'on' );

                if (
                    wpuf_is_checkbox_or_toggle_on( $autologin_after_registration )
                    && isset( $wpuf_user_status )
                    && 'approved' === $wpuf_user_status
                ) {
                    wp_set_current_user( $user_id );
                    wp_set_auth_cookie( $user_id );
                }

                if ( wpuf_is_checkbox_or_toggle_on( $autologin_after_registration ) ) {
                    $action  = ! empty( $_REQUEST['action'] ) && $_REQUEST['action'] === 'wpuf_submit_register' ? true : false;
                    $sub     = ! empty( $_REQUEST['wpuf_sub'] ) && $_REQUEST['wpuf_sub'] === 'yes' ? true : false;
                    $type    = ! empty( $_REQUEST['type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['type'] ) ) : '';
                    $pack_id = ! empty( $_REQUEST['pack_id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['pack_id'] ) ) : '';

                    if ( $action && $sub && $pack_id && $form_settings['notification_type'] !== 'email_verification' ) {
                        $response ['show_message'] = false;
                        $response['redirect_to']   = add_query_arg(
                            [
                                'action'  => 'wpuf_pay',
                                'type'    => $type,
                                'pack_id' => $pack_id,
                            ], get_permalink( wpuf_get_option( 'payment_page', 'wpuf_payment' ) )
                        );
                    }
                }
                if ( wpuf_is_vendor_reg( $form_id ) && $form_settings['reg_redirect_to'] !== 'url' ) {
                    $response ['show_message'] = false;
                    $response['redirect_to']   = wpuf_get_dokan_redirect_url();
                }

                wpuf_clear_buffer();
                echo json_encode( $response );

                exit;
            } // endif
        }

        wpuf_clear_buffer();

        echo json_encode(
            array(
                'success' => false,
                'error' => __( 'Something went wrong', 'wpuf-pro' ),
            )
        );

        exit;
    }

    public function update_profile() {
        check_ajax_referer( 'wpuf_form_add' );

        add_filter( 'wpuf-form-builder-field-settings', array( $this, 'add_field_settings' ) );
        @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );

        $postdata = wp_unslash( $_POST );

        $form_id       = isset( $postdata['form_id'] ) ? intval( $postdata['form_id'] ) : 0;
        $form          = new Form( $form_id );
        $form_settings = $form->get_settings();
        $form_fields   = $form->get_fields();

        list( $user_vars, $taxonomy_vars, $meta_vars ) = $this->get_input_fields( $form_fields );
        $user_id  = get_current_user_id();
        $userdata = array( 'ID' => $user_id );
        $userinfo = get_userdata( $user_id );

        if ( $this->search( $user_vars, 'name', 'first_name' ) ) {
            $userdata['first_name'] = strip_shortcodes( sanitize_text_field( $postdata['first_name'] ) );
        }

        if ( $this->search( $user_vars, 'name', 'last_name' ) ) {
            $userdata['last_name'] = strip_shortcodes( sanitize_text_field( $postdata['last_name'] ) );
        }

        if ( $this->search( $user_vars, 'name', 'display_name' ) ) {
            $userdata['display_name'] = strip_shortcodes( sanitize_text_field( $postdata['display_name'] ) );
        }

        if ( $this->search( $user_vars, 'name', 'nickname' ) ) {
            $userdata['nickname'] = strip_shortcodes( sanitize_text_field( $postdata['nickname'] ) );
        }

        if ( $this->search( $user_vars, 'name', 'user_url' ) ) {
            $userdata['user_url'] = strip_shortcodes( esc_url_raw( $postdata['user_url'] ) );
        }

        if ( $this->search( $user_vars, 'name', 'user_email' ) ) {
            $userdata['user_email'] = sanitize_email( $postdata['user_email'] );
        }

        if ( $this->search( $user_vars, 'name', 'description' ) ) {
            $userdata['description'] = strip_shortcodes( sanitize_textarea_field( $postdata['description'] ) );
        }

        // check if Email filled out
        // verify Email
        if ( isset( $postdata['user_email'] ) && $userinfo->user_email !== trim( $postdata['user_email'] ) ) {
            if ( email_exists( trim( $postdata['user_email'] ) ) ) {
                wp_send_json_error(
                    [
                        'success' => false,
                        'error'   => __( 'That E-mail already exists', 'wpuf-pro' ),
                    ]
                );
            }
        }

        // check if password filled out
        // verify password
        $pass_element = $this->search( $user_vars, 'name', 'password' );
        if ( $pass_element ) {
            $pass_element    = current( $pass_element );
            $password        = isset( $postdata['pass1'] ) ? $postdata['pass1'] : '';
            $password_repeat = isset( $postdata['pass2'] ) ? $postdata['pass2'] : '';

            // check only if it's filled
            $pass_length = strlen( $password );
            if ( $pass_length ) {

                // min length check
                if ( $pass_length < intval( $pass_element['min_length'] ) ) {
                    wp_send_json_error(
                        [
                            'success' => false,
                            'error'   => sprintf(
                                // translators: %s: pass length
                                __( 'Password must be %s character long', 'wpuf-pro' ), $pass_element['min_length']
                            ),
                        ]
                    );

                }

                // Validate password requirements
                $password_validation_error = $this->validate_password_requirements( $password, $pass_element );
                if ( $password_validation_error ) {
                    wp_send_json_error(
                        [
                            'success' => false,
                            'error'   => $password_validation_error,
                        ]
                    );
                }

                // repeat password check
                if ( 'yes' === $pass_element['repeat_pass'] && $password !== $password_repeat ) {
                    wp_send_json_error(
                        [
                            'success' => false,
                            'error'   => __( 'Password didn\'t match', 'wpuf-pro' ),
                        ]
                    );
                }

                // seems like he want to change the password
                $userdata['user_pass'] = $password;
            }
        }

        $userdata = apply_filters( 'wpuf_update_profile_vars', $userdata, $form_id, $form_settings );

        $user_id = wp_update_user( $userdata );

        if ( $user_id ) {
            // update meta fields
            $this->update_user_meta( $meta_vars, $user_id );
            do_action( 'wpuf_update_profile', $user_id, $form_id, $form_settings, $meta_vars );
        }

        // redirect URL
        $show_message       = false;
        // The referer is request supplied, so keep the fallback on this host.
        // Admin configured redirect targets below may legitimately be external.
        $referer            = wp_get_referer();
        $redirect_to        = $referer ? wp_validate_redirect( $referer, home_url( '/' ) ) : home_url( '/' );
        $profile_redirect   = isset( $form_settings['profile_redirect_to'] ) ? $form_settings['profile_redirect_to'] : '';
        $profile_page_id    = isset( $form_settings['profile_page_id'] ) ? absint( $form_settings['profile_page_id'] ) : 0;
        $profile_url        = isset( $form_settings['profile_url'] ) ? $form_settings['profile_url'] : '';

        if ( 'page' === $profile_redirect && $profile_page_id ) {
            $page_link = get_permalink( $profile_page_id );

            if ( $page_link ) {
                $redirect_to = $page_link;
            }
        } elseif ( 'url' === $profile_redirect && ! empty( $profile_url ) ) {
            $redirect_to = $profile_url;
        } elseif ( 'same' === $profile_redirect ) {
            $show_message = true;

            if ( $profile_page_id ) {
                $page_link = get_permalink( $profile_page_id );

                if ( $page_link ) {
                    $redirect_to = add_query_arg( [ 'msg' => 'profile_update' ], $page_link );
                }
            }
        }

        /**
         * Fires after update user profile data
         *
         * @since 3.3.0
         *
         * @param int   $user_id
         * @param array $postdata
         * @param int $form_id
         * @param array $form_settings
         */
        do_action( 'wpuf_pro_frontend_form_update_profile', $user_id, $postdata, $form_id, $form_settings );

        // send the response
        $response = array(
            'success'      => true,
            'redirect_to'  => $redirect_to,
            'show_message' => $show_message,
            'message'      => $form_settings['update_message'],
        );

        $response = apply_filters( 'wpuf_update_profile_resp', $response, $user_id, $form_id, $form_settings );

        wpuf_clear_buffer();

        echo json_encode( $response );

        exit;
    }


    /**
     * Add action links for registration form
     *
     * @since 2.9.0
     **/
    public function action_links() {
        if ( is_user_logged_in() ) {
            return;
        }

        $output = '';

        $output .= '<li>';
        $output .= wpuf()->frontend->registration->get_action_links( array( 'register' => false ) );
        $output .= '</li>';

        echo $output;
    }

    public function profile_edit( $form_id, $form_vars, $form_settings ) {
        $label_position = isset( $form_settings['label_position'] ) ? $form_settings['label_position'] : 'left';
        $layout         = isset( $form_settings['profile_form_layout'] ) ? $form_settings['profile_form_layout'] : 'layout1';
        $theme_css      = isset( $form_settings['use_theme_css'] ) ? $form_settings['use_theme_css'] : 'wpuf-style';
        $style_class    = ( $layout === 'layout1' ) ? $theme_css : 'wpuf-style';

        if ( ! empty( $layout ) ) {
            wp_enqueue_style( 'wpuf-' . $layout );
        }
        ?>

        <!-- Wrapper card (styled per template in reg-template-*.css — dark
             templates draw their own card and suppress this one) -->
        <div class="wpuf-reg-form-card wpuf-reg-form-card-<?php echo esc_attr( $layout ); ?>">
        <?php
        echo '<form class="wpuf-form-add wpuf-form-' . $layout . ' ' . $style_class . '" action="" method="post">'; ?>

            <ul class="wpuf-form form-label-<?php echo $label_position; ?>">

                <script type="text/javascript">
                    if ( typeof wpuf_conditional_items === 'undefined' ) {
                        wpuf_conditional_items = [];
                    }

                    if ( typeof wpuf_plupload_items === 'undefined' ) {
                        wpuf_plupload_items = [];
                    }

                    if ( typeof wpuf_map_items === 'undefined' ) {
                        wpuf_map_items = [];
                    }
                </script>

                <?php

                    $form = new Form( $form_id );

                    do_action( 'wpuf_form_fields_top', $form, $form_vars );

                    $atts = array();
                    wpuf()->fields->render_fields( $form_vars, $form_id, $atts, $type = 'user', get_current_user_id() );

                    $this->submit_button( $form_id, $form_settings );
                    $this->action_links();

                    do_action( 'wpuf_add_profile_form_bottom', $form_id, $form_settings );

                echo '</ul>';
                echo '</form>';
        ?>
        </div><!-- Close wrapper container with border -->
        <?php
    }


    public function submit_button( $form_id, $form_settings, $post_id = 0 ) {
        // lets guess its a registration form
        // give the chance to fire action for default register form
        if ( ! is_user_logged_in() ) {
            do_action( 'register_form' );
        }

        $type = isset( $_GET['type'] ) ? sanitize_text_field( wp_unslash( $_GET['type'] ) ) : '';
        $pack_id = isset( $_GET['pack_id'] ) ? intval( wp_unslash( $_GET['pack_id'] ) ) : 0;
        ?>

        <li class="wpuf-submit">

            <?php wp_nonce_field( 'wpuf_form_add' ); ?>
                <input type="hidden" name="form_id" value="<?php echo $form_id; ?>">
                <input type="hidden" name="page_id" value="<?php echo get_the_ID(); ?>">
                <input type="hidden" id="del_attach" name="delete_attachments[]">

            <?php if ( is_user_logged_in() ) { ?>
                <input type="hidden" name="action" value="wpuf_update_profile">
                <input type="submit" class="wpuf-submit-button" name="submit" value="<?php echo $form_settings['update_text']; ?>" />
            <?php } else { ?>
                <input type="hidden" name="action" value="wpuf_submit_register">
                <?php if ( 'wpuf_sub' === $type && ! empty( $pack_id ) ) { ?>
                    <input type="hidden" name="wpuf_sub" value="yes" />
                    <input type="hidden" name="pack_id" value="<?php echo esc_attr( $pack_id ); ?>" />
                    <input type="hidden" name="type" value="<?php echo esc_attr( $type ); ?>" />
                <?php } ?>
                <input type="submit" class="wpuf-submit-button" name="submit" value="<?php echo $form_settings['submit_text']; ?>" />
                <br><br>
                <?php
                    /* translators: %1$s: login URL, %2$s: login text */
                    printf(
                        wp_kses_post( __( 'Already have an account? <a href="%1$s">%2$s</a>', 'wpuf-pro' ) ),
                        esc_url( $this->login_url() ),
                        esc_html( __( 'Login', 'wpuf-pro' ) )
                    );
                ?>
            <?php } ?>
        </li>

        <?php
    }


    public function login_url() {
        $override          = wpuf_get_option( 'register_link_override', 'wpuf_profile', 'off' );
        $default_login_url = site_url( 'wp-login.php', 'login' );

        if ( $override !== 'on' ) {
            return $default_login_url;
        }

        $login_page_id = wpuf_get_option( 'login_page', 'wpuf_profile', false );

        if ( ! $login_page_id ) {
            return $default_login_url;
        }

        return home_url( basename( get_permalink( $login_page_id ) ), 'login' );
    }

    public static function meta_filter_checkbox( $meta_vars ) {
        $filteredmeta = array_reduce(
            $meta_vars, function ( $result, $item ) {
                if ( $item['template'] === 'checkbox_field' ) {
                     $result[ $item['name'] ] = '';
                }
                return $result;
            }, array()
        );

        return $filteredmeta;
    }
    /**
     * Update user meta based on form inputs
     *
     * @param array $meta_vars
     * @param int $user_id
     */
    public static function update_user_meta( $meta_vars, $user_id ) {
        //phpcs:ignore
        $postdata = wp_unslash( $_POST );

        // prepare meta fields
        list( $meta_key_value, $multi_repeated, $files ) = self::prepare_meta_fields( $meta_vars );
        $meta_checkbox = self::meta_filter_checkbox( $meta_vars );
        $meta_key_value = array_merge( $meta_checkbox, $meta_key_value );
        //attach user id for files, images
        if ( ! empty( $postdata['wpuf_files'] ) ) {
            $attach_ids = [];

            array_map(
                function ( $attach_id ) use ( &$attach_ids ) {
                    $attach_ids = array_merge( $attach_ids, $attach_id );
                }, $postdata['wpuf_files']
            );

            foreach ( get_posts(
                [
                    'post__in' => $attach_ids,
                    'post_type' => 'attachment',
                ]
            ) as $post ) {
                wp_update_post(
                    [
                        'ID' => $post->ID,
                        'post_author' => $user_id,
                    ]
                );
            }
        }
        // set featured image if there's any
        if ( isset( $postdata['wpuf_files']['avatar'] ) ) {
            $attachment_id = absint( $postdata['wpuf_files']['avatar'][0] );

            // Use the unified profile photo processing function with avatar settings
            $result = wpuf_process_profile_photo_attachment( $attachment_id, $user_id, 'user_avatar', 5 * 1024 * 1024 ); // 5MB for avatar
        }

        // set profile picture if there's any
        if ( isset( $postdata['wpuf_files']['wpuf_profile_photo'] ) ) {
            $attachment_id = absint( $postdata['wpuf_files']['wpuf_profile_photo'][0] );

            // Use the unified profile photo processing function
            $result = wpuf_process_profile_photo_attachment( $attachment_id, $user_id, 'wpuf_profile_photo' );
        }

        // set cover photo if there's any
        \WeDevs\Wpuf\Pro\Fields\Field_Cover_Photo::process_upload( $postdata, $user_id );

        // Process signature field if present
        // Find signature field in meta_vars to get its field name
        $signature_field_name = null;
        $signature_meta_key = 'wpuf_signature'; // Default meta key
        
        foreach ( $meta_vars as $field ) {
            if ( isset( $field['template'] ) && 'signature_field' === $field['template'] ) {
                $signature_field_name = isset( $field['name'] ) ? $field['name'] : null;
                $signature_meta_key = isset( $field['meta_key'] ) ? $field['meta_key'] : 'wpuf_signature';
                break;
            }
        }
        
        // Check for signature data using field name (meta_key_value uses field name as key)
        if ( $signature_field_name && isset( $meta_key_value[ $signature_field_name ] ) && ! empty( $meta_key_value[ $signature_field_name ] ) ) {
            $svg_string = $meta_key_value[ $signature_field_name ];
            $form_id = isset( $postdata['form_id'] ) ? intval( $postdata['form_id'] ) : 0;

            // Upload and save signature file
            $signature_path = \WeDevs\Wpuf\Pro\Fields\Field_Signature::upload_signature( $svg_string, $user_id, $form_id );

            if ( is_wp_error( $signature_path ) ) {
                // Remove from meta_key_value so it doesn't get saved as raw SVG
                unset( $meta_key_value[ $signature_field_name ] );
            } else {
                // Remove the field name entry and add with correct meta_key
                unset( $meta_key_value[ $signature_field_name ] );
                // Save with the correct meta_key (wpuf_signature)
                $meta_key_value[ $signature_meta_key ] = $signature_path;

                // Delete old signature if it exists
                $old_signature = get_user_meta( $user_id, $signature_meta_key, true );
                if ( ! empty( $old_signature ) && $old_signature !== $signature_path ) {
                    $upload_dir = wp_upload_dir();
                    $old_file_path = $upload_dir['basedir'] . '/' . $old_signature;
                    if ( file_exists( $old_file_path ) ) {
                        wp_delete_file( $old_file_path );
                    }
                }
            }
        }

        // save all custom fields
        foreach ( $meta_key_value as $meta_key => $meta_value ) {
            update_user_meta( $user_id, $meta_key, $meta_value );
        }

        // save any multicolumn repeatable fields
        foreach ( $multi_repeated as $repeat_key => $repeat_value ) {
            // first, delete any previous repeatable fields
            delete_user_meta( $user_id, $repeat_key );

            // now add them
            foreach ( $repeat_value as $repeat_field ) {
                add_user_meta( $user_id, $repeat_key, $repeat_field );
            }
        } //foreach

        // save any files attached
        foreach ( $files as $file_input ) {
            // delete any previous value
            delete_user_meta( $user_id, $file_input['name'] );

            //to track how many files are being uploaded
            $file_numbers = 0;

            foreach ( $file_input['value'] as $attachment_id ) {

                //if file numbers are greated than allowed number, prevent it from being uploaded
                if ( $file_numbers >= $file_input['count'] ) {
                    wp_delete_attachment( $attachment_id );
                    continue;
                }

                add_user_meta( $user_id, $file_input['name'], $attachment_id );

                $file_numbers++;
            }
        }

        /**
         * Fires after update user profile data
         *
         * @since 3.3.0
         *
         * @param int   $user_id
         * @param array $postdata
         */
        do_action( 'wpuf_pro_frontend_form_update_user_meta', $user_id, $postdata );
    }

    /**
     * Resend activation email to user
     *
     * @since 2.8.2
     **/
    public function resend_activation_email() {
        if ( ! isset( $_GET['resend_activation'] ) ) {
            return;
        }

        $user_id = is_numeric( $_GET['resend_activation'] ) ? sanitize_text_field( wp_unslash( $_GET['resend_activation'] ) ) : -1;
        $user    = new WPUF_User( $user_id );

        if ( ! $user->id ) {
            wpuf()->frontend->simple_login->add_error( __( 'User not found', 'wpuf-pro' ) );
            return;
        }
        //check if activated
        if ( $user->is_verified() ) {
            wpuf()->frontend->simple_login->add_message( __( 'User is verified already', 'wpuf-pro' ) );
            return;
        }

        $this->send_verification_mail( $user->id, $user->user->user_email );

        wpuf()->frontend->simple_login->add_message( __( 'Email Activation link is sent, please check your email.', 'wpuf-pro' ) );
    }

    /**
     * Send email verification link
     *
     * @param int|\WP_Error $user_id
     *
     * @param string $user_email
     *
     * @param null $form_id
     *
     * @return void
     **/
    public function send_verification_mail( $user_id, $user_email, $form_id = null ) {
        $user     = get_user_by( 'id', $user_id );
        $code     = sha1( $user_id . $user_email . time() );
        $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );

        add_filter( 'login_url', array( $this, 'login_url' ) );

        $activation_link = add_query_arg(
            array(
                'wpuf_registration_activation' => $code,
                'id' => $user_id,
            ),
            wp_login_url()
        );

        // add wpuf_password_info_email query arguement with activation link if password field exist in the registration form
        if ( ! is_null( $form_id ) ) {
            $fields         = wpuf_get_form_fields( $form_id );
            $form_settings  = wpuf_get_form_settings( $form_id );
            $password_field = false;

            if ( isset( $form_settings['notification_type'] ) && 'email_verification' === $form_settings['notification_type'] && 'on' === wpuf_get_option( 'register_subscription', 'wpuf_payment' ) ) {
                $action  = ! empty( $_REQUEST['action'] ) && $_REQUEST['action'] === 'wpuf_submit_register' ? true : false;
                $sub     = ! empty( $_REQUEST['wpuf_sub'] ) && $_REQUEST['wpuf_sub'] === 'yes' ? true : false;
                $type    = ! empty( $_REQUEST['type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['type'] ) ) : '';
                $pack_id = ! empty( $_REQUEST['pack_id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['pack_id'] ) ) : '';

                    $activation_link = add_query_arg(
                        [
                            'type'    => $type,
                            'pack_id' => $pack_id,
                            'wpuf_registration_activation' => $code,
                            'id' => $user_id,
                        ], wp_login_url()
                    );
            }

            foreach ( $fields as $key => $field ) {
                if ( $field['template'] === 'password' ) {
                    $password_field = true;
                }
            }

            if ( ! $password_field ) {
                $activation_link = add_query_arg(
                    array(
                        'wpuf_registration_activation' => $code,
                        'id' => $user_id,
                        'wpuf_password_info_email' => true,
                    ),
                    wp_login_url()
                );
            }
        }

        // resend verification email when user request
        /* translators: %s: site name */
        $subject = sprintf( __( '[%s] Account Activation', 'wpuf-pro' ), $blogname );
        /* translators: %s: site name */
        $message  = sprintf( __( 'Congrats! You are Successfully registered to %s:', 'wpuf-pro' ), $blogname ) . "\r\n\r\n";
        $message .= __( 'To activate your account, please click the link below', 'wpuf-pro' ) . "\r\n\r\n";
        $message .= '<a href="' . $activation_link . '">' . __( 'Activation Link', 'wpuf-pro' ) . '</a>' . "\r\n";

        // send verification email after user registration
        if ( ! is_null( $form_id ) ) {
            $form_settings = wpuf_get_form_settings( $form_id );
            $subject = isset( $form_settings['notification']['verification_subject'] ) ? $form_settings['notification']['verification_subject'] : $subject;
            $message = isset( $form_settings['notification']['verification_body'] ) ? $form_settings['notification']['verification_body'] : $message;
        }

        // resend verification email when user request & HTML Email Templates module is active
        if ( is_null( $form_id ) && wpuf_pro_is_module_active( 'email-templates/email-templates.php' ) ) {
            $subject = wpuf_get_option( 'confirmation_mail_subject', 'wpuf_mails', $subject );
            $message = wpuf_get_option( 'confirmation_mail_body', 'wpuf_mails', $message );
        }

        $field_search = array( '{username}', '{blogname}', '{activation_link}' );

        $field_replace = array(
            $user->display_name,
            $blogname,
            '<a href="' . $activation_link . '">' . __( 'Activation Link', 'wpuf-pro' ) . '</a>',
        );

        $message = str_replace( $field_search, $field_replace, $message );
        $message = self::prepare_meta_key( $message, $user_id );
        $message = get_formatted_mail_body( $message, $subject );

        $wpuf_user = new WPUF_User( $user_id );
        $wpuf_user->set_activation_key( $code );
        $wpuf_user->mark_unverified();
        $headers = array( 'Content-Type: text/html; charset=UTF-8' );

        wp_mail( $user_email, $subject, $message, $headers );
    }


    /**
     * Prepare email body
     *
     * @since 2.8
     *
     * @return string $message
     */
    public static function prepare_mail_body( $message, $user_status, $user_id ) {
        $user = get_user_by( 'id', $user_id );

        $pending_users  = admin_url() . 'users.php?s&new_role&wpuf_user_approve_filter-top=pending&paged=1&action2=-1&new_role2';
        $approved_users = admin_url() . 'users.php?s&new_role&wpuf_user_approve_filter-top=approved&paged=1&action2=-1&new_role2';
        $denied_users   = admin_url() . 'users.php?s&new_role&wpuf_user_approve_filter-top=denied&paged=1&action2=-1&new_role2';

        $user_field_search = [ '{username}', '{user_email}', '{display_name}', '{user_status}', '{pending_users}', '{approved_users}', '{denied_users}' ];

        $user_field_replace = [
            $user->user_login,
            $user->user_email,
            $user->display_name,
            $user_status,
            $pending_users,
            $approved_users,
            $denied_users,
        ];

        $message = str_replace( $user_field_search, $user_field_replace, $message );

        // replace line breaks with proper html tags
        $message = str_replace( [ "\r\n", "\n", "\r" ], '<br />', $message );

        return self::prepare_meta_key( $message, $user_id );
    }


    /**
     * Send email notification to admine
     *
     * @since 2.8
     *
     * @param string $user_status
     *
     * @param int $user_email
     *
     * @param null $form_id
     *
     * @return void
     **/
    public static function admin_email_notification( $user_status, $user_id, $form_id = null, $form_settings = [] ) {
        $to         = get_option( 'admin_email' );
        $subject    = '';
        $message    = '';

        if ( ! is_null( $form_id ) ) {
            $form_settings  = wpuf_get_form_settings( $form_id );
            $user_status    = isset( $form_settings['wpuf_user_status'] ) ? $form_settings['wpuf_user_status'] : 'approved';

            $default_message       = "Username: {username} ({user_email}) has requested a username.\r\n\r\n";
            $default_message      .= "To approve or deny this user access go to {pending_users}\r\n\r\n";
            $default_message      .= 'Thanks';

            $subject = isset( $form_settings['admin_email_subject'] ) ? $form_settings['admin_email_subject'] : 'New user registered on your site';
            $message = isset( $form_settings['admin_email_body'] ) ? $form_settings['admin_email_body'] : $default_message;

            if ( $user_status === 'approved' ) {
                $default_message       = "Username: {username} ({user_email}) has requested a username.\r\n\r\n";
                $default_message      .= "To pending or deny this user access go to {approved_users}\r\n\r\n";
                $default_message      .= 'Thanks';

                $message = isset( $form_settings['admin_email_body'] ) ? $form_settings['admin_email_body'] : $default_message;
            }
        }

        $message = self::prepare_mail_body( $message, $user_status, $user_id );
        $message = get_formatted_mail_body( $message, $subject );
        $headers = array( 'Content-Type: text/html; charset=UTF-8' );
        wp_mail( $to, $subject, $message, $headers );
    }

    /**
     * Send email notification to admine
     *
     * @since 2.8
     *
     * @param string $user_status
     *
     * @param int $user_email
     *
     * @param null $form_id
     *
     * @return void
     **/
    public static function user_status_update_notification( $user_status, $user_id ) {
        $user       = get_user_by( 'id', $user_id );
        $user_email = $user->user_email;
        $to         = $user_email;
        $subject    = '';
        $message    = '';

        // Map user status to email type
        $email_type_map = [
            'pending'  => 'pending_user_email',
            'approved' => 'approved_user_email',
            'denied'   => 'denied_user_email',
        ];

        $email_type = isset( $email_type_map[ $user_status ] ) ? $email_type_map[ $user_status ] : '';

        // Check if email templates module is active and has required methods
        $email_templates_active = class_exists( 'WPUF_Email_Templates' ) && method_exists( 'WPUF_Email_Templates', 'get_template_for_user' );

        // Check for role-based template first (from HTML Email Templates module)
        $role_template = null;

        if ( $email_templates_active ) {
            $role_template = \WPUF_Email_Templates::get_template_for_user( $email_type, $user_id );
        }

        if ( $role_template && ! empty( $role_template['subject'] ) && ! empty( $role_template['body'] ) ) {
            // Use role-based template
            $subject = $role_template['subject'];
            $message = wpautop( $role_template['body'] );
        } else {
            // Check if user should receive default email based on their role
            // Only check if email templates module is active (otherwise send to all)
            if ( $email_templates_active && method_exists( 'WPUF_Email_Templates', 'should_user_receive_default_email' ) ) {
                $should_receive = \WPUF_Email_Templates::should_user_receive_default_email( $email_type, $user_id );

                if ( ! $should_receive ) {
                    /**
                     * Fires when a status-change email is suppressed because the
                     * user's role is not in the default roles list.
                     *
                     * @since 4.2.12
                     *
                     * @param string $email_type  Email type identifier.
                     * @param int    $user_id     User ID whose email was suppressed.
                     * @param string $user_status The status that triggered the email.
                     */
                    do_action( 'wpuf_email_suppressed_by_role', $email_type, $user_id, $user_status );

                    return;
                }
            }

            // Fall back to default templates
            if ( $user_status === 'pending' && 'on' === wpuf_get_option( 'enable_pending_user_email_notification', 'wpuf_mails', 'on' ) ) {
                $body  = "Hi {username},\r\n\r\n";
                $body .= "Your account status has been changed to pending by an administrator.\r\n\r\n";
                $body .= 'Thanks';

                $subject = wpuf_get_option( 'pending_user_email_subject', 'wpuf_mails', 'Status has been changed to pending' );
                $message = wpautop( wpuf_get_option( 'pending_user_email_body', 'wpuf_mails', $body ) );
            } elseif ( $user_status === 'approved' && 'on' === wpuf_get_option( 'enable_approved_user_email_notification', 'wpuf_mails', 'on' ) ) {
                $body  = "Hi {username},\r\n\r\n";
                $body .= "Your account has been approved by an administrator.\r\n\r\n";
                $body .= 'Thanks';

                $subject = wpuf_get_option( 'approved_user_email_subject', 'wpuf_mails', 'Approved your request' );
                $message = wpautop( wpuf_get_option( 'approved_user_email_body', 'wpuf_mails', $body ) );
            } elseif ( $user_status === 'denied' && 'on' === wpuf_get_option( 'enable_denied_user_email_notification', 'wpuf_mails', 'on' ) ) {
                $body  = "Hi {username},\r\n\r\n";
                $body .= "Your account has been denied by an administrator, please contact admin to approve your account.\r\n\r\n";
                $body .= 'Thanks';

                $subject = wpuf_get_option( 'denied_user_email_subject', 'wpuf_mails', 'Denied your request' );
                $message = wpautop( wpuf_get_option( 'denied_user_email_body', 'wpuf_mails', $body ) );
            }
        }

        if ( '' === $subject || '' === $message ) {
            return;
        }

        $message = self::prepare_mail_body( $message, $user_status, $user_id );
        $message = get_formatted_mail_body( $message, $subject );
        $headers = [ 'Content-Type: text/html; charset=UTF-8' ];
        wp_mail( $to, $subject, $message, $headers );
    }

    /**
     * Add avatar image size during image upload
     *
     * @since 3.3.0
     *
     * @param int  $form_id
     * @param string $field_type
     *
     * @return void
     */
    public function add_avatar_image_size( $form_id, $field_type ) {
        if ( 'avatar' !== $field_type ) {
            return;
        }

        wpuf_avatar_add_image_size();

        add_filter( 'intermediate_image_sizes', array( $this, 'remove_intermediate_image_sizes' ) );
        add_filter( 'wpuf_upload_response_image_size', array( $this, 'upload_response_image_size' ) );
        add_filter( 'wpuf_upload_response_image_class_names', array( $this, 'upload_response_image_class_names' ) );
    }

    /**
     * Remove images sizes except avatar size
     *
     * @since 3.3.0
     *
     * @return array
     */
    public function remove_intermediate_image_sizes() {
        return [ 'wpuf_avatar_image_size' ];
    }

    /**
     * Filter image size for WPUF attachment uploader response
     *
     * @since 3.3.0
     *
     * @return string
     */
    public function upload_response_image_size() {
        return 'wpuf_avatar_image_size';
    }

    /**
     * Filter image size for WPUF attachment uploader response
     *
     * @since 3.3.0
     *
     * @param array $class_names
     *
     * @return array
     */
    public function upload_response_image_class_names( $class_names ) {
        $class_names[] = 'avatar';
        return $class_names;
    }

    /**
     * Send user notification
     *
     * @since 3.4.7
     *
     * @param integer $user_id
     * @param string $user_email
     * @param string $notification_type
     * @param integer $form_id
     *
     * @return void
     */
    public function send_user_notification( $user_id, $user_email, $notification_type, $form_id ) {
        if ( 'welcome_email' === $notification_type ) {
            $this->send_welcome_email( $user_id, $form_id );
        }

        if ( 'email_verification' === $notification_type ) {
            $this->send_verification_mail( $user_id, $user_email, $form_id );
        }
    }

    /**
     * Send welcome email for the newly registered user
     *
     * @since 3.4.7
     *
     * @param integer $user_id
     * @param integer $form_id
     *
     * @return void
     */
    public function send_welcome_email( $user_id, $form_id ) {
        $user       = get_user_by( 'id', $user_id );
        $user_email = $user->user_email;
        $to         = $user_email;
        $subject    = '';
        $message    = '';

        $blogname        = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
        $form_settings   = wpuf_get_form_settings( $form_id );

        $body  = "Hi {username},\r\n\r\nCongrats!";
        $body .= "You are Successfully registered to {$blogname}.\r\n\r\nThank you very much.";

        $body    = apply_filters( 'wpuf_pro_user_email_notification_welcome_email_body_default', $body );
        $subject = isset( $form_settings['notification']['welcome_email_subject'] ) ? $form_settings['notification']['welcome_email_subject'] : __( 'Thank you for registering', 'wpuf-pro' );
        $message = isset( $form_settings['notification']['welcome_email_body'] ) ? $form_settings['notification']['welcome_email_body'] : $body;

        $message = self::prepare_mail_body( $message, '', $user_id );
        $message = get_formatted_mail_body( $message, $subject );
        $headers = array( 'Content-Type: text/html; charset=UTF-8' );
        wp_mail( $to, $subject, $message, $headers );
    }

    /**
    * Replace meta key for user email notification
    * @param $message
    * @param $user_id
    *
    * @return string|string[]
    */
    private static function prepare_meta_key( $message, $user_id ) {
        preg_match_all( '/{.*?}/', $message, $matches );

        if ( empty( $matches[0] ) ) {
            return $message;
        }

        $key_in_message = $matches[0];
        $meta_keys      = str_replace( [ '{', '}' ], '', $key_in_message );
        $user_meta      = get_user_meta( $user_id );

        $meta_value = [];

        foreach ( $user_meta as $key => $item ) {
            if ( in_array( $key, $meta_keys, true ) ) {
                $value = maybe_unserialize( ! empty( $item[0] ) ? $item[0] : '' );
                $meta_value[] = is_array( $value ) ? implode( ' | ', $value ) : $value;
            }
        }

        return str_replace( $key_in_message, $meta_value, $message );
    }

    /**
     * Conditionally enqueue template styles based on form settings
     *
     * @since 4.2.15
     *
     * @param array $form_settings
     *
     * @return void
     */
    private function conditionally_enqueue_template_styles( $form_settings ) {
        // Check if Use Theme CSS is enabled - if so, don't enqueue plugin styles
        $use_theme_css = isset( $form_settings['use_theme_css'] ) ? $form_settings['use_theme_css'] : '';

        if ( 'on' === $use_theme_css ) {
            return;
        }

        // Get the form layout template
        $form_template = isset( $form_settings['profile_form_layout'] ) ? $form_settings['profile_form_layout'] : 'layout1';

        // Always enqueue the base template style
        wp_enqueue_style( 'wpuf-reg-template-base' );
        wp_enqueue_style( 'wpuf-custom-multiselect' );

        // Map layout1, layout2, etc. to reg-template-1, reg-template-2, etc.
        if ( ! empty( $form_template ) && preg_match( '/^layout(\d+)$/', $form_template, $matches ) ) {
            $template_number = $matches[1];
            $template_handle = 'wpuf-reg-template-' . $template_number;
            wp_enqueue_style( $template_handle );
        }
    }

    /**
    * Enqueue preview page assets
    *
    * @since 4.2.15
    *
    * @return void
    **/
    public function enqueue_preview_page_assets() {
        if ( ! isset( $_GET['wpuf_preview'] ) && empty( $_GET['wpuf'] ) ) {
            return;
        }

        $form_id = isset( $_GET['form_id'] ) ? absint( wp_unslash( $_GET['form_id'] ) ) : 0;
        $form    = new Form( $form_id );
        $form_settings = $form->get_settings();

        $this->conditionally_enqueue_template_styles( $form_settings );
    }

    /**
     * Validate password requirements
     *
     * Validates password against configured requirements (uppercase, lowercase, number, special character, common passwords).
     *
     * @since 4.2.11
     *
     * @param string $password The password to validate.
     * @param array  $pass_element The password field element settings.
     *
     * @return string|false Error message if validation fails, false if validation passes.
     */
    private function validate_password_requirements( $password, $pass_element ) {
        // Check minimum length requirement
        if ( ! empty( $pass_element['min_length'] ) ) {
            $min_length = intval( $pass_element['min_length'] );

            if ( $min_length > 0 && strlen( $password ) < $min_length ) {
                /* translators: %d: minimum password length */
                return sprintf( __( 'Password must be at least %d characters long', 'wpuf-pro' ), $min_length );
            }
        }

        // Check uppercase requirement
        if ( ! empty( $pass_element['require_uppercase'] ) && 'yes' === $pass_element['require_uppercase'] ) {
            if ( ! preg_match( '/[A-Z]/', $password ) ) {
                return __( 'Password must contain at least one uppercase letter', 'wpuf-pro' );
            }
        }

        // Check lowercase requirement
        if ( ! empty( $pass_element['require_lowercase'] ) && 'yes' === $pass_element['require_lowercase'] ) {
            if ( ! preg_match( '/[a-z]/', $password ) ) {
                return __( 'Password must contain at least one lowercase letter', 'wpuf-pro' );
            }
        }

        // Check number requirement
        if ( ! empty( $pass_element['require_number'] ) && 'yes' === $pass_element['require_number'] ) {
            if ( ! preg_match( '/[0-9]/', $password ) ) {
                return __( 'Password must contain at least one number', 'wpuf-pro' );
            }
        }

        // Check special character requirement
        if ( ! empty( $pass_element['require_special_char'] ) && 'yes' === $pass_element['require_special_char'] ) {
            if ( ! preg_match( '/[^A-Za-z0-9]/', $password ) ) {
                return __( 'Password must contain at least one special character', 'wpuf-pro' );
            }
        }

        // Check common passwords requirement
        if ( ! empty( $pass_element['disallow_common_passwords'] ) && 'yes' === $pass_element['disallow_common_passwords'] ) {
            // Check for repeated patterns first (handled via regex)
            if ( Field_Password::has_repeated_patterns( $password ) ) {
                return __( 'This password contains repeated patterns and is too weak. Please choose a different password.', 'wpuf-pro' );
            }

            // Check against common passwords list
            $common_passwords = Field_Password::get_common_passwords();
            $password_lower   = strtolower( $password );
            $common_lower     = array_map( 'strtolower', $common_passwords );

            if ( in_array( $password_lower, $common_lower, true ) ) {
                return __( 'This password is too common. Please choose a different password.', 'wpuf-pro' );
            }
        }

        return false;
    }
}
