<?php

namespace WeDevs\Wpuf\Pro\Integrations\N8N;

use WeDevs\Wpuf\Integrations\WPUF_N8N_Integration;
use WeDevs\Wpuf\Traits\FieldableTrait;

if ( ! class_exists( 'WeDevs\Wpuf\Pro\Integrations\N8N\N8N_Registration_Integration' ) ) {
    /**
     * WPUF N8N Registration Form Integration Class (Pro)
     *
     * @since 4.2.6
     */
    class N8N_Registration_Integration {

        use FieldableTrait;

        /**
         * Core N8N integration instance
         *
         * @var WPUF_N8N_Integration
         */
        private $core_integration;

        public function __construct() {
            // Get the core N8N integration instance
            if ( function_exists( 'wpuf' ) ) {
                $integrations = wpuf()->integrations;
                if ( isset( $integrations->n8n ) ) {
                    $this->core_integration = $integrations->n8n;
                }
            }

            // Hook into registration forms
            add_action( 'wpuf_after_register', [ $this, 'send_user_to_n8n' ], 20, 6 );
            add_filter( 'wpuf_registration_form_builder_setting_menu_titles', [ $this, 'add_n8n_registration_menu_title' ] );
            add_filter( 'wpuf_form_builder_post_settings', [ $this, 'add_n8n_registration_form_settings' ] );
        }

        /**
         * Send user to N8N
         *
         * @since 4.2.6
         *
         * @param int $user_id
         * @param int $form_id
         * @param array $form_settings
         * @param array $user_vars
         * @param array $taxonomy_vars
         * @param array $meta_vars
         *
         * @return void
         */
        public function send_user_to_n8n( $user_id, $form_id, $form_settings, $user_vars, $taxonomy_vars, $meta_vars ) {
            // Check if N8N integration is enabled for this form
            if ( empty( $form_settings['enable_n8n'] ) || ! wpuf_is_checkbox_or_toggle_on( $form_settings['enable_n8n'] ) ) {
                return;
            }

            // Get the webhook URL
            $n8n_webhook_url = isset( $form_settings['n8n_webhook_url'] ) ? $form_settings['n8n_webhook_url'] : '';
            if ( empty( $n8n_webhook_url ) ) {
                return;
            }

            // Sanitize the URL
            $n8n_webhook_url = esc_url_raw( $n8n_webhook_url );

            // Get the user data
            $user = get_userdata( $user_id );
            if ( ! $user ) {
                return;
            }

            // Prepare the data to send to N8N
            $user_data = [
                'user_id' => $user_id,
                'form_id' => $form_id,
            ];

            if ( ! empty( $user->user_login ) ) {
                $user_data['user_login'] = $user->user_login;
            }
            if ( ! empty( $user->user_email ) ) {
                $user_data['user_email'] = $user->user_email;
            }
            if ( ! empty( $user->first_name ) ) {
                $user_data['first_name'] = $user->first_name;
            }
            if ( ! empty( $user->last_name ) ) {
                $user_data['last_name'] = $user->last_name;
            }
            if ( ! empty( $user->display_name ) ) {
                $user_data['display_name'] = $user->display_name;
            }
            if ( ! empty( $user->nickname ) ) {
                $user_data['nickname'] = $user->nickname;
            }
            if ( ! empty( $user->user_url ) ) {
                $user_data['user_url'] = $user->user_url;
            }
            if ( ! empty( $user->description ) ) {
                $user_data['description'] = $user->description;
            }
            if ( ! empty( $user->user_registered ) ) {
                $user_data['user_registered'] = $user->user_registered;
            }
            if ( ! empty( $user->roles ) && is_array( $user->roles ) ) {
                $user_data['role'] = $user->roles[0];
            }

            // Process meta fields
            if ( ! empty( $meta_vars ) ) {
                [ $meta_key_value, $multi_repeated, $files ] = self::prepare_meta_fields( $meta_vars );

                // Add meta fields to user data
                foreach ( $meta_key_value as $meta_key => $meta_value ) {
                    $user_data[ $meta_key ] = $meta_value;
                }
            }

            // Get authentication headers from core integration
            $headers = $this->get_authentication_headers();

            // Send data to N8N webhook
            try {
                $response = wp_remote_post(
                    $n8n_webhook_url, [
                        'method'  => 'POST',
                        'timeout' => 30,
                        'headers' => $headers,
                        'body'    => wp_json_encode( $user_data ),
                    ]
                );
            } catch ( \Exception $e ) {
                error_log( 'WPUF N8N: Exception sending webhook for user ' . $user_id . ': ' . $e->getMessage() );
            }
        }

        /**
         * Get authentication headers
         *
         * @since 4.2.6
         *
         * @return array
         */
        private function get_authentication_headers() {
            // Try to use core integration's method if available
            if ( $this->core_integration && method_exists( $this->core_integration, 'prepare_authentication_headers' ) ) {
                // Use reflection to call protected method
                $reflection = new \ReflectionClass( $this->core_integration );
                $method = $reflection->getMethod( 'prepare_authentication_headers' );
                $method->setAccessible( true );
                return $method->invoke( $this->core_integration );
            }

            // Fallback: duplicate authentication logic
            $headers = [
                'Content-Type' => 'application/json',
            ];

            // Get global N8N settings for authentication
            $n8n_settings = get_option( 'n8n', [] );

            // Add authentication based on global settings
            $auth_type = isset( $n8n_settings['authentication_type'] ) ? $n8n_settings['authentication_type'] : 'none';

            switch ( $auth_type ) {
                case 'basic_auth':
                    $username = isset( $n8n_settings['basic_auth_username'] ) ? $n8n_settings['basic_auth_username'] : '';
                    $password = isset( $n8n_settings['basic_auth_password'] ) ? $n8n_settings['basic_auth_password'] : '';
                    if ( ! empty( $username ) && ! empty( $password ) ) {
                        $headers['Authorization'] = 'Basic ' . base64_encode( $username . ':' . $password );
                    }
                    break;

                case 'header_auth':
                    $header_name = isset( $n8n_settings['header_auth_name'] ) ? $n8n_settings['header_auth_name'] : '';
                    $header_value = isset( $n8n_settings['header_auth_value'] ) ? $n8n_settings['header_auth_value'] : '';
                    if ( ! empty( $header_name ) && ! empty( $header_value ) ) {
                        $headers[ $header_name ] = $header_value;
                    }
                    break;

                case 'jwt_auth':
                    $jwt_key_type = isset( $n8n_settings['jwt_key_type'] ) ? $n8n_settings['jwt_key_type'] : 'passphrase';
                    $jwt_key = '';

                    if ( $jwt_key_type === 'passphrase' ) {
                        $jwt_key = isset( $n8n_settings['jwt_key_passphrase'] ) ? $n8n_settings['jwt_key_passphrase'] : '';
                    } elseif ( $jwt_key_type === 'pem_key' ) {
                        $jwt_key = isset( $n8n_settings['jwt_key_pem_key'] ) ? $n8n_settings['jwt_key_pem_key'] : '';
                    }

                    if ( ! empty( $jwt_key ) ) {
                        $jwt_token = $this->create_jwt_token( $jwt_key );
                        if ( $jwt_token ) {
                            $headers['Authorization'] = 'Bearer ' . $jwt_token;
                        }
                    }
                    break;
            }

            return $headers;
        }

        /**
         * Create JWT token for authentication
         *
         * @since 4.2.6
         *
         * @param string $secret_key
         * @return string|false
         */
        private function create_jwt_token( $secret_key ) {
            // Simple JWT implementation - you might want to use a proper JWT library
            $header = json_encode( [
                'typ' => 'JWT',
                'alg' => 'HS256'
            ] );

            $payload = json_encode( [
                'iat' => time(),
                'exp' => time() + 3600, // 1 hour expiration
                'iss' => get_site_url(),
            ] );

            $base64_header = str_replace( ['+', '/', '='], ['-', '_', ''], base64_encode( $header ) );
            $base64_payload = str_replace( ['+', '/', '='], ['-', '_', ''], base64_encode( $payload ) );

            $signature = hash_hmac( 'sha256', $base64_header . '.' . $base64_payload, $secret_key, true );
            $base64_signature = str_replace( ['+', '/', '='], ['-', '_', ''], base64_encode( $signature ) );

            return $base64_header . '.' . $base64_payload . '.' . $base64_signature;
        }

        /**
         * Add N8N to registration form menu titles (after Advanced Settings)
         *
         * @since 4.2.6
         *
         * @param array $settings
         * @return array
         */
        public function add_n8n_registration_menu_title( $settings ) {
            $settings['n8n'] = [
                'label' => __( 'N8N', 'wpuf-pro' ),
                'icon'  => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="custom-stroke">
                        <path d="M5.38983 12.0847C5.38983 13.0208 4.63099 13.7797 3.69492 13.7797C2.75884 13.7797 2 13.0208 2 12.0847C2 11.1487 2.75884 10.3898 3.69492 10.3898C4.63099 10.3898 5.38983 11.1487 5.38983 12.0847ZM5.38983 12.0847H7.50847M10.8983 12.0847C10.8983 13.0208 10.1395 13.7797 9.20339 13.7797C8.26731 13.7797 7.50847 13.0208 7.50847 12.0847M10.8983 12.0847C10.8983 11.1487 10.1395 10.3898 9.20339 10.3898C8.26731 10.3898 7.50847 11.1487 7.50847 12.0847M10.8983 12.0847H12.2542M16.4068 15.3051C16.4068 16.2412 17.1656 17 18.1017 17C19.0378 17 19.7966 16.2412 19.7966 15.3051C19.7966 14.369 19.0378 13.6102 18.1017 13.6102C17.1656 13.6102 16.4068 14.369 16.4068 15.3051ZM16.4068 15.3051H15.4746C14.5853 15.3051 13.8644 14.5842 13.8644 13.6949C13.8644 12.8056 13.1435 12.0847 12.2542 12.0847M12.2542 12.0847C13.1435 12.0847 13.8644 11.3638 13.8644 10.4746C13.8644 9.5853 14.5853 8.86441 15.4746 8.86441H18.6102M22 8.69492C22 9.63099 21.2412 10.3898 20.3051 10.3898C19.369 10.3898 18.6102 9.63099 18.6102 8.69492C18.6102 7.75884 19.369 7 20.3051 7C21.2412 7 22 7.75884 22 8.69492Z" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>',
            ];

            return $settings;
        }

        /**
         * Add N8N registration form settings as a top-level section
         *
         * @since 4.2.6
         *
         * @param array $settings
         *
         * @return array
         */
        public function add_n8n_registration_form_settings( $settings ) {
            // Add N8N as a top-level section (like general, notification, display, advanced)
            $settings['n8n'] = [
                'section' => [
                    'n8n_integration' => [
                        'label'  => __( 'N8N Integration', 'wpuf-pro' ),
                        'desc'   => __( 'Configure N8N webhook integration to send user registration data to your N8N workflows', 'wpuf-pro' ),
                        'fields' => [
                            'enable_n8n' => [
                                'label'     => __( 'Enable N8N Integration', 'wpuf-pro' ),
                                'type'      => 'toggle',
                                'help_text' => __( 'Enable N8N integration for registration forms', 'wpuf-pro' ),
                                'default'   => 'off',
                            ],
                            'n8n_webhook_url' => [
                                'label'       => __( 'Webhook URL', 'wpuf-pro' ),
                                'type'        => 'text',
                                'placeholder' => __( 'https://your-n8n-instance.com/webhook/your-webhook-id', 'wpuf-pro' ),
                                'help_text'   => __( 'Enter the N8N webhook URL to send user data when registrations are submitted', 'wpuf-pro' ),
                            ],
                        ],
                    ],
                ],
            ];

            return $settings;
        }
    }
}

