<?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 ) {
        $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__( 'Login Form', 'wpuf-pro' ),
            esc_html__( 'Please complete all information below', 'wpuf-pro' )
        );

        return $message . $heading_html;
    }

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

        wp_enqueue_script( 'wpuf-login-form' );

        // Pass layout and translations to JS
        wp_localize_script(
            'wpuf-login-form',
            'wpufLoginForm',
            [
                'layout'        => $layout,
                'i18n'          => [
                    'usernameHelp' => __( 'Please enter your username or email address', 'wpuf-pro' ),
                    'passwordHelp' => __( 'Please enter your password', 'wpuf-pro' ),
                ],
            ]
        );
    }

    /**
     * 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',
            ] ),
        ];
    }

    /**
     * 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 ) {
        // Use free plugin assets path for layout images (shared between free and pro)
        $layout_images_url = WPUF_ASSET_URI . '/images/login-layouts/';

        // Layout selection
        $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' ],
        ];

        // Color settings
        $settings_fields['wpuf_profile'][] = ['name' => 'login_form_colors_section', 'label' => __( 'Login Form Colors', 'wpuf-pro' ), 'type' => 'html', 'desc' => '<hr>'];

        $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'] )
        );
    }

}
