<?php
/**
 * Login Form Settings
 *
 * Manages login and registration form layouts with customizable styling options.
 *
 * @package WP User Frontend Pro
 * @subpackage Admin
 * @since 1.0.0
 */

namespace WeDevs\Wpuf\Pro\Admin;

/**
 * Login Form Settings Class
 *
 * Handles login form layout selection, color customization, and frontend styling.
 */
class Login_Form_Settings {

    /**
     * Supported layouts
     *
     * @var array
     */
    const SUPPORTED_LAYOUTS = [ 'layout1', 'layout2', 'layout3', 'layout4', 'layout5', 'layout6', 'layout7' ];

    /**
     * Settings option name
     *
     * @var string
     */
    const SETTINGS_KEY = 'wpuf_profile';

    /**
     * Constructor - Register hooks
     *
     * @since 4.2.5
     */
    public function __construct() {
        $this->register_hooks();
    }

    /**
     * Register WordPress hooks
     *
     * @since 4.2.5
     *
     * @return void
     */
    private function register_hooks() {
        add_filter( 'wpuf_settings_fields', [ $this, 'add_login_form_settings' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_styles' ] );
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_frontend_styles' ], 20 );
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_frontend_scripts' ], 20 );
        add_action( 'login_message', [ $this, 'add_login_form_heading' ], 5 );
    }

    /**
     * Get current selected layout
     *
     * @since 4.2.5
     *
     * @return string
     */
    private function get_current_layout() {
        $settings = get_option( self::SETTINGS_KEY, [] );
        $layout   = $settings['wpuf_login_form_layout'] ?? 'layout1';

        return in_array( $layout, self::SUPPORTED_LAYOUTS, true ) ? $layout : 'layout1';
    }

    /**
     * Add heading to login form
     *
     * @since 4.2.5
     *
     * @param string $message Existing login message.
     * @return string Modified message with heading.
     */
    public function add_login_form_heading( $message ) {
        $texts = $this->get_all_texts();

        $heading_html = sprintf(
            '<div class="wpuf-login-header">
                <h2 class="wpuf-login-title">%s</h2>
                <p class="wpuf-login-subtitle">%s</p>
            </div>',
            esc_html( $texts['form_title'] ),
            esc_html( $texts['form_subtitle'] )
        );

        return $message . $heading_html;
    }

    /**
     * Enqueue frontend scripts
     *
     * @since 4.2.5
     *
     * @return void
     */
    public function enqueue_frontend_scripts() {
        $layout = $this->get_current_layout();
        $texts  = $this->get_all_texts();

        wp_enqueue_script( 'wpuf-login-form' );

        // Pass layout and custom texts to JS
        wp_localize_script(
            'wpuf-login-form',
            'wpufLoginForm',
            [
                'layout' => $layout,
                'texts'  => [
                    'usernameLabel'       => $texts['username_label'],
                    'usernamePlaceholder' => $texts['username_placeholder'],
                    'usernameHelp'        => $texts['username_help'],
                    'passwordLabel'       => $texts['password_label'],
                    'passwordPlaceholder' => $texts['password_placeholder'],
                    'passwordHelp'        => $texts['password_help'],
                    'rememberMe'          => $texts['remember_me_text'],
                    'lostPassword'        => $texts['lost_password_text'],
                    'buttonText'          => $texts['button_text'],
                ],
            ]
        );
    }

    /**
     * Get layout default settings
     *
     * @since 4.2.5
     *
     * @param string $layout Layout name.
     * @return array Layout defaults.
     */
    public function get_layout_defaults( $layout = 'layout1' ) {
        $defaults = $this->get_all_layout_defaults();
        return $defaults[ $layout ] ?? $defaults['layout1'];
    }

    /**
     * Get all layout defaults
     *
     * @since 4.2.5
     *
     * @return array All layout defaults.
     */
    private function get_all_layout_defaults() {
        $base_defaults = [
            'form_align'          => 'center',
            'form_bg_color'       => 'transparent',
            'form_border_color'   => 'transparent',
            'field_border_color'  => '#D1D5DB',
            'field_bg_color'      => 'transparent',
            'placeholder_color'   => '#9CA3AF',
            'input_text_color'    => '#111827',
            'help_text_color'     => '#6B7280',
            'button_bg_color'     => '#3B82F6',
            'button_border_color' => '',
            'button_text_color'   => '#ffffff',
        ];

        return [
            'layout1' => array_merge( $base_defaults, [
                'form_width'       => '400px',
                'label_text_color' => '#333333',
            ] ),
            'layout2' => array_merge( $base_defaults, [
                'form_width'       => '400px',
                'form_bg_color'    => '#000000',
                'label_text_color' => '#ffffff',
                'input_text_color' => '#ffffff',
                'help_text_color'  => '#D1D5DB',
            ] ),
            'layout3' => array_merge( $base_defaults, [
                'form_width'       => '653px',
                'label_text_color' => '#000824',
            ] ),
            'layout4' => array_merge( $base_defaults, [
                'form_width'       => '793px',
                'label_text_color' => '#4B5563',
            ] ),
            'layout5' => array_merge( $base_defaults, [
                'form_width'       => '713px',
                'label_text_color' => '#000824',
            ] ),
            'layout6' => array_merge( $base_defaults, [
                'form_width'        => '713px',
                'field_border_color' => '#E3E5E8',
                'label_text_color'  => '#000824',
            ] ),
            'layout7' => array_merge( $base_defaults, [
                'form_width'       => '713px',
                'label_text_color' => '#000824',
            ] ),
        ];
    }

    /**
     * Get text fields configuration with labels and defaults
     *
     * @since 4.2.10
     *
     * @return array Text fields configuration.
     */
    private function get_text_fields_config() {
        return [
            'wpuf_login_form_title'            => [
                'label'   => __( 'Login Form Header', 'wpuf-pro' ),
                'default' => __( 'Login Form', 'wpuf-pro' ),
            ],
            'wpuf_login_form_subtitle'         => [
                'label'   => __( 'Login Form Description Text', 'wpuf-pro' ),
                'default' => __( 'Please complete all information below', 'wpuf-pro' ),
            ],
            'wpuf_login_username_label'        => [
                'label'   => __( 'Username Label', 'wpuf-pro' ),
                'default' => __( 'Username or Email', 'wpuf-pro' ),
            ],
            'wpuf_login_username_placeholder'  => [
                'label'   => __( 'Username Placeholder', 'wpuf-pro' ),
                'default' => __( 'Enter Username or Email', 'wpuf-pro' ),
            ],
            'wpuf_login_username_help'         => [
                'label'   => __( 'Username Help Text', 'wpuf-pro' ),
                'default' => __( 'Please enter your username or email address', 'wpuf-pro' ),
            ],
            'wpuf_login_password_label'        => [
                'label'   => __( 'Password Label', 'wpuf-pro' ),
                'default' => __( 'Password', 'wpuf-pro' ),
            ],
            'wpuf_login_password_placeholder'  => [
                'label'   => __( 'Password Placeholder', 'wpuf-pro' ),
                'default' => __( 'Enter Password', 'wpuf-pro' ),
            ],
            'wpuf_login_password_help'         => [
                'label'   => __( 'Password Help Text', 'wpuf-pro' ),
                'default' => __( 'Please enter your password', 'wpuf-pro' ),
            ],
            'wpuf_login_remember_me_text'      => [
                'label'   => __( 'Remember Me Text', 'wpuf-pro' ),
                'default' => __( 'Remember Me', 'wpuf-pro' ),
            ],
            'wpuf_login_lost_password_text'    => [
                'label'   => __( 'Lost Password Text', 'wpuf-pro' ),
                'default' => __( 'Lost Password', 'wpuf-pro' ),
            ],
            'wpuf_login_button_text'           => [
                'label'   => __( 'Login Button Text', 'wpuf-pro' ),
                'default' => __( 'Log In', 'wpuf-pro' ),
            ],
        ];
    }

    /**
     * Get custom text value from settings
     *
     * @since 4.2.10
     *
     * @param string $key Text field key.
     * @return string Text value.
     */
    public function get_text( $key ) {
        $settings     = get_option( self::SETTINGS_KEY, [] );
        $text_fields  = $this->get_text_fields_config();
        $setting_name = 'wpuf_login_' . $key;

        if ( isset( $text_fields[ $setting_name ] ) ) {
            return ! empty( $settings[ $setting_name ] ) ? sanitize_text_field( $settings[ $setting_name ] ) : $text_fields[ $setting_name ]['default'];
        }

        return '';
    }

    /**
     * Get all custom texts
     *
     * @since 4.2.5
     *
     * @return array All text values.
     */
    public function get_all_texts() {
        $settings    = get_option( self::SETTINGS_KEY, [] );
        $text_fields = $this->get_text_fields_config();
        $texts       = [];

        foreach ( $text_fields as $field_name => $field_config ) {
            $key           = str_replace( 'wpuf_login_', '', $field_name );
            $texts[ $key ] = ! empty( $settings[ $field_name ] ) ? sanitize_text_field( $settings[ $field_name ] ) : $field_config['default'];
        }

        return $texts;
    }

    /**
     * Add login form settings fields
     *
     * @since 4.2.5
     *
     * @param array $settings_fields Existing settings fields.
     * @return array Modified settings fields.
     */
    public function add_login_form_settings( $settings_fields ) {
        // Find the position of wpuf_login_form_layout to insert heading before it
        if ( isset( $settings_fields['wpuf_profile'] ) && is_array( $settings_fields['wpuf_profile'] ) ) {
            $insert_position = null;

            // Find where wpuf_login_form_layout field is located
            foreach ( $settings_fields['wpuf_profile'] as $key => $field ) {
                if ( isset( $field['name'] ) && $field['name'] === 'wpuf_login_form_layout' ) {
                    $insert_position = $key;
                    break;
                }
            }

            // If we found the layout field, insert the heading before it
            if ( $insert_position !== null ) {
                $heading = [
                    'name'  => 'login_form_colors_section',
                    'label' => __( 'Login Form Colors', 'wpuf-pro' ),
                    'type'  => 'html',
                    'desc'  => '<hr>',
                ];

                // Insert heading at the found position
                array_splice( $settings_fields['wpuf_profile'], $insert_position, 0, [ $heading ] );
            }
        }

        // Use free plugin assets path for layout images (shared between free and pro)
        $layout_images_url = WPUF_ASSET_URI . '/images/login-layouts/';

        // Layout selection - this overrides the FREE version's disabled preview
        $settings_fields['wpuf_profile'][] = [
            'name'     => 'wpuf_login_form_layout',
            'label'    => __( 'Select Login Form Layout', 'wpuf-pro' ),
            'desc'     => __( 'Choose a layout style for your login forms.', 'wpuf-pro' ),
            'type'     => 'radio',
            'options'  => $this->get_layout_options( $layout_images_url ),
            'default'  => 'layout1',
            'callback' => [ $this, 'render_radio_image_field' ],
        ];

        $text_fields = $this->get_text_fields_config();

        foreach ( $text_fields as $field_name => $field_config ) {
            $settings_fields['wpuf_profile'][] = [
                'name'    => $field_name,
                'label'   => $field_config['label'],
                'type'    => 'text',
                'default' => $field_config['default'],
                'std'     => $field_config['default'],
            ];
        }

        // Color fields - these override the FREE version's disabled previews
        $color_fields = [
            'wpuf_login_form_bg_color'       => __( 'Form Background Color', 'wpuf-pro' ),
            'wpuf_login_form_border_color'   => __( 'Form Border Color', 'wpuf-pro' ),
            'wpuf_login_field_border_color'  => __( 'Field Border Color', 'wpuf-pro' ),
            'wpuf_login_field_bg_color'      => __( 'Field Background Color', 'wpuf-pro' ),
            'wpuf_login_label_text_color'    => __( 'Label Text Color', 'wpuf-pro' ),
            'wpuf_login_placeholder_color'   => __( 'Placeholder Color', 'wpuf-pro' ),
            'wpuf_login_input_text_color'    => __( 'Input Text Color', 'wpuf-pro' ),
            'wpuf_login_help_text_color'     => __( 'Help Text Color', 'wpuf-pro' ),
            'wpuf_login_button_bg_color'     => __( 'Button Background Color', 'wpuf-pro' ),
            'wpuf_login_button_border_color' => __( 'Button Border Color', 'wpuf-pro' ),
            'wpuf_login_button_text_color'   => __( 'Button Text Color', 'wpuf-pro' ),
        ];

        foreach ( $color_fields as $field_name => $field_label ) {
            $settings_fields['wpuf_profile'][] = [
                'name'    => $field_name,
                'label'   => $field_label,
                'type'    => 'color',
                'default' => '',
                'std'     => '',
            ];
        }

        return $settings_fields;
    }

    /**
     * Get layout options for settings
     *
     * @since 4.2.5
     *
     * @param string $image_url Base URL for layout images.
     * @return array Layout options.
     */
    private function get_layout_options( $image_url ) {
        $layouts = [
            'layout1' => __( 'Layout 1 - Classic', 'wpuf-pro' ),
            'layout2' => __( 'Layout 2 - Modern Dark', 'wpuf-pro' ),
            'layout3' => __( 'Layout 3 - Minimal', 'wpuf-pro' ),
            'layout4' => __( 'Layout 4 - Bordered', 'wpuf-pro' ),
            'layout5' => __( 'Layout 5 - Rounded', 'wpuf-pro' ),
            'layout6' => __( 'Layout 6 - Clean', 'wpuf-pro' ),
            'layout7' => __( 'Layout 7 - Premium', 'wpuf-pro' ),
        ];

        $options = [];
        foreach ( $layouts as $key => $label ) {
            $options[ $key ] = [
                'label' => $label,
                'image' => $image_url . $key . '.svg',
            ];
        }

        return $options;
    }

    /**
     * Enqueue admin styles
     *
     * @since 4.2.5
     *
     * @param string $hook Current admin page hook.
     * @return void
     */
    public function enqueue_admin_styles( $hook ) {
        if ( ! str_contains( $hook, 'wpuf-settings' ) && ! str_contains( $hook, 'wp-user-frontend' ) ) {
            return;
        }

        wp_enqueue_style( 'wpuf-login-form-settings' );
        wp_enqueue_style( 'wp-color-picker' );
        wp_enqueue_script( 'wp-color-picker' );
    }

    /**
     * Render radio image field
     *
     * @since 4.2.5
     *
     * @param array $args Field arguments.
     * @return void
     */
    public function render_radio_image_field( $args ) {
        // Early return if required parameters are missing
        if ( empty( $args['section'] ) || empty( $args['id'] ) || empty( $args['options'] ) ) {
            return;
        }

        $value = get_option( $args['section'] );

        // Early return if value is not an array
        if ( ! \is_array( $value ) ) {
            $value = [];
        }

        $current = $value[ $args['id'] ] ?? $args['std'] ?? '';

        echo '<fieldset><div class="wpuf-radio-image-wrapper">';

        foreach ( $args['options'] as $key => $option ) {
            $checked = checked( $current, $key, false );
            $label   = esc_html( $option['label'] ?? $key );
            $image   = esc_url( $option['image'] ?? '' );

            printf(
                '<div class="wpuf-radio-image-option">
                    <input type="radio" id="%1$s_%2$s" name="%3$s[%1$s]" value="%2$s" %4$s>
                    <label for="%1$s_%2$s" title="%5$s">',
                esc_attr( $args['id'] ),
                esc_attr( $key ),
                esc_attr( $args['section'] ),
                $checked,
                $label
            );

            if ( $image ) {
                printf( '<img src="%s" alt="%s">', $image, $label );
            }

            echo '</label></div>';
        }

        echo '</div>';

        if ( ! empty( $args['desc'] ) ) {
            printf( '<p class="description">%s</p>', wp_kses_post( $args['desc'] ) );
        }

        echo '</fieldset>';
    }

    /**
     * Enqueue frontend styles
     *
     * @since 4.2.5
     *
     * @return void
     */
    public function enqueue_frontend_styles() {
        $layout   = $this->get_current_layout();
        $settings = get_option( self::SETTINGS_KEY, [] );
        $defaults = $this->get_layout_defaults( $layout );

        wp_enqueue_style( 'wpuf-login-form' );
        wp_enqueue_style( 'wpuf-login-form-dynamic' );

        // Add inline CSS variables for dynamic colors only
        $colors = $this->prepare_colors( $settings, $defaults );
        $css    = $this->generate_css_variables( $colors );

        wp_add_inline_style( 'wpuf-login-form-dynamic', $css );
    }

    /**
     * Prepare color values from settings and defaults
     *
     * @since 4.2.5
     *
     * @param array $settings Saved settings.
     * @param array $defaults Default values.
     * @return array Prepared color array.
     */
    private function prepare_colors( $settings, $defaults ) {
        $color_map = [
            'form_width'    => 'form_width',
            'form_align'    => 'form_align',
            'form_bg'       => 'form_bg_color',
            'form_border'   => 'form_border_color',
            'field_border'  => 'field_border_color',
            'field_bg'      => 'field_bg_color',
            'label_color'   => 'label_text_color',
            'placeholder'   => 'placeholder_color',
            'input_text'    => 'input_text_color',
            'help_text'     => 'help_text_color',
            'button_bg'     => 'button_bg_color',
            'button_border' => 'button_border_color',
            'button_text'   => 'button_text_color',
        ];

        $colors = [];
        foreach ( $color_map as $key => $setting_key ) {
            $setting_name = 'wpuf_login_' . $setting_key;
            $colors[ $key ] = ! empty( $settings[ $setting_name ] ) ? $settings[ $setting_name ] : $defaults[ $setting_key ];
        }

        return $colors;
    }

    /**
     * Generate CSS variables for dynamic colors
     *
     * @since 4.2.5
     *
     * @param array $colors Color settings.
     * @return string CSS variables code.
     */
    private function generate_css_variables( $colors ) {
        return sprintf(
            ":root {
                --wpuf-login-form-bg: %s;
                --wpuf-login-form-border: %s;
                --wpuf-login-form-width: %s;
                --wpuf-login-field-bg: %s;
                --wpuf-login-field-border: %s;
                --wpuf-login-label-color: %s;
                --wpuf-login-input-text: %s;
                --wpuf-login-placeholder: %s;
                --wpuf-login-button-bg: %s;
                --wpuf-login-button-border: %s;
                --wpuf-login-button-text: %s;
                --wpuf-login-help-text: %s;
            }",
            esc_attr( $colors['form_bg'] ),
            esc_attr( $colors['form_border'] ),
            esc_attr( $colors['form_width'] ),
            esc_attr( $colors['field_bg'] ),
            esc_attr( $colors['field_border'] ),
            esc_attr( $colors['label_color'] ),
            esc_attr( $colors['input_text'] ),
            esc_attr( $colors['placeholder'] ),
            esc_attr( $colors['button_bg'] ),
            esc_attr( $colors['button_border'] ),
            esc_attr( $colors['button_text'] ),
            esc_attr( $colors['help_text'] )
        );
    }

}
