<?php
/**
 * Admin class to create settings page and  REST API endpoint to handle parameter updates coming from the settings front-end,
 * and load the settings.
 *
 */

namespace SmartCloud\WPSuite\Gatey;

use TypeError;
use Exception;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use SmartCloud\WPSuite\Gatey\Logger;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (file_exists(filename: GATEY_PATH . 'admin/model.php')) {
    require_once GATEY_PATH . 'admin/model.php';
}

class Admin
{
    private Settings $settings;
    public function __construct()
    {
        $defaultSettings = new Settings(
            userPoolConfigurations: new UserPoolConfigurations(
                default: new ResourceConfiguration(
                    new AuthConfiguration(new Configuration('', '', '', new LoginWithOAuthConfiguration(new OAuthConfiguration('', array())))),
                    new ApiConfiguration(new RestConfiguration(''))
                ),
                secondary: new ResourceConfiguration(
                    new AuthConfiguration(new Configuration('', '', '', new LoginWithOAuthConfiguration(new OAuthConfiguration('', array())))),
                    new ApiConfiguration(new RestConfiguration(''))
                )
            ),
            secondaryUserPoolDomains: '',
            mappings: [],
            loginMechanisms: [],
            integrateWpLogin: false,
            cookieExpiration: 43200,
            signInPage: '',
            redirectSignIn: '',
            redirectSignOut: '',
            customTranslationsUrl: '',
            signUpAttributes: [],
            socialProviders: [],
            passwordlessSettings: [],
            hideSignUp: false,
            enablePoweredBy: false,
            debugLoggingEnabled: false,
        );

        // WP can return array/object depending on previous versions / serialization.
        $raw = get_option(GATEY_SLUG);

        // Merge missing properties from defaultSettings
        $merged = array_merge(
            (array) $defaultSettings,
            is_object($raw) ? (array) $raw : (is_array($raw) ? $raw : [])
        );

        $this->settings = Settings::fromMixed($merged);
        $this->registerRestRoutes();
        add_filter('auth_cookie_expiration', array($this, 'setAuthCookieExpiration'), 10, 3);
        add_action('pre_get_posts', array($this, 'filterPatternListQuery'));
    }
    public function getSettings(): Settings
    {
        return $this->settings;
    }

    public function addMenu()
    {
        $generate_suffix = add_submenu_page(
            SMARTCLOUD_WPSUITE_SLUG,
            __('Gatey Settings', 'gatey'),
            __('Gatey Settings', 'gatey'),
            'manage_options',
            GATEY_SLUG,
            array($this, 'renderCognitoSettingsPage'),
        );

        add_submenu_page(
            SMARTCLOUD_WPSUITE_SLUG,
            __('Gatey Patterns', 'gatey'),
            __('Gatey Patterns', 'gatey'),
            'edit_posts',
            admin_url('edit.php?post_type=wp_block&s=gatey'),
        );

        add_action("admin_print_scripts-{$generate_suffix}", array($this, 'addScripts'));

        add_filter('parent_file', array($this, 'highlightMenu'));
        add_filter('submenu_file', array($this, 'highlightSubmenu'));

        $post_type = filter_input(INPUT_GET, 'post_type', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $search = filter_input(INPUT_GET, 's', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

        if ($this->isGateyPatternsRequest($post_type, $search)) {
            add_filter('manage_edit-wp_block_columns', array($this, 'addShortcodeColumn'), 20);
            add_action('manage_wp_block_posts_custom_column', array($this, 'renderShortcodeColumn'), 10, 2);
            add_action('admin_enqueue_scripts', array($this, 'copyShortcode'));
        }
    }

    private function isGateyPatternsRequest(?string $post_type = null, ?string $search = null): bool
    {
        $resolved_post_type = $post_type;
        if ($resolved_post_type === null) {
            $resolved_post_type = filter_input(INPUT_GET, 'post_type', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        }

        $resolved_search = $search;
        if ($resolved_search === null) {
            $resolved_search = filter_input(INPUT_GET, 's', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        }

        return 'wp_block' === $resolved_post_type && 'gatey' === $resolved_search;
    }

    public function filterPatternListQuery($query): void
    {
        if (
            !is_admin()
            || !($query instanceof \WP_Query)
            || !$query->is_main_query()
            || $query->get('gatey_pattern_lookup')
            || !$this->isGateyPatternsRequest((string) $query->get('post_type'), (string) $query->get('s'))
        ) {
            return;
        }

        $pattern_ids = $this->getGateyPatternIds();

        $query->set('post__in', !empty($pattern_ids) ? $pattern_ids : array(0));
    }

    private function getGateyPatternIds(): array
    {
        $candidate_ids = get_posts(array(
            'post_type' => 'wp_block',
            'post_status' => 'any',
            'posts_per_page' => -1,
            'fields' => 'ids',
            'orderby' => 'ID',
            'order' => 'ASC',
            'no_found_rows' => true,
            'gatey_pattern_lookup' => true,
        ));

        return array_values(array_filter(
            array_map('intval', $candidate_ids),
            array($this, 'isGateyPatternPost')
        ));
    }

    private function isGateyPatternPost(int $post_id): bool
    {
        $post = get_post($post_id);

        return $post instanceof \WP_Post
            && 'wp_block' === $post->post_type
            && has_block('gatey/authenticator', $post);
    }

    public function addShortcodeColumn($columns)
    {
        $columns['wpc_shortcode'] = __('Shortcode', 'gatey');
        return $columns;
    }

    public function renderShortcodeColumn($column, $post_id)
    {
        if ('wpc_shortcode' !== $column || !$this->isGateyPatternPost((int) $post_id)) {
            return;
        }

        $shortcode = sprintf('[gatey id="%d"]', $post_id);

        printf(
            '<span class="wpc-shortcode" id="wpc-sc-%1$d"><code>%2$s</code></span>
            <div class="row-actions">
                <span class="copy">
                    <a href="#" class="wpc-copy" data-target="wpc-sc-%1$d">Copy</a>
                </span>
            </div>',
            (int) $post_id,
            esc_html($shortcode),
            esc_html__('Copy', 'gatey')
        );
    }

    public function copyShortcode($hook)
    {

        // Csak a „Blokkok” (wp_block) listán van rá szükség
        $screen = get_current_screen();
        if ('edit.php' !== $hook || 'wp_block' !== $screen->post_type) {
            return;
        }

        wp_add_inline_script(
            'jquery-core',
            "
            (function($){
                function copyText( text, onSuccess, onFail ) {
    
                    if ( navigator.clipboard && window.isSecureContext ) {
                        navigator.clipboard.writeText( text )
                            .then( onSuccess )
                            .catch( function(){ legacyCopy( text, onSuccess, onFail ); } );
                        return;
                    }
    
                    legacyCopy( text, onSuccess, onFail );
                }
    
                function legacyCopy( text, onSuccess, onFail ) {
                    var \$tmp = $('<textarea readonly>')
                        .css({position:'absolute',left:'-9999px',top:0,opacity:0})
                        .val( text )
                        .appendTo('body')
                        .select();
    
                    try {
                        if ( document.execCommand('copy') ) {
                            onSuccess();
                            \$tmp.remove();
                            return;
                        }
                    } catch(e) {}
    
                    \$tmp.remove();
                    onFail();
                }
    
                $(document).on('click', '.wpc-copy', function(e){
                    e.preventDefault();
    
                    var \$btn   = $(this),
                        orig   = \$btn.text(),
                        text   = $('#' + \$btn.data('target')).text();
    
                    function showOk(){
                        \$btn.text( '" . esc_js(__('Copied!', 'gatey')) . "' );
                        setTimeout( function(){ \$btn.text( orig ); }, 1500 );
                    }
                    function showFail(){
                        window.prompt( '" . esc_js(__('Copy manually (Ctrl+C):', 'gatey')) . "', text );
                    }
    
                    copyText( text, showOk, showFail );
                });
            })(jQuery);
            "
        );
    }
    public function highlightMenu($parent_file)
    {
        if ($this->isGateyPatternsRequest((string) get_query_var('post_type'), (string) get_query_var('s'))) {
            return SMARTCLOUD_WPSUITE_SLUG;
        }
        return $parent_file;
    }

    public function highlightSubmenu($submenu_file)
    {
        if ($this->isGateyPatternsRequest((string) get_query_var('post_type'), (string) get_query_var('s'))) {
            return admin_url("edit.php?post_type=wp_block&s=gatey");
        }
        return $submenu_file;
    }

    public function addScripts()
    {
        $screen = get_current_screen();

        $script_asset = array();
        if (file_exists(filename: GATEY_PATH . 'admin/index.asset.php')) {
            $script_asset = require_once(GATEY_PATH . 'admin/index.asset.php');
        }
        $script_asset['dependencies'] = array_merge($script_asset['dependencies'], array('smartcloud-wpsuite-webcrypto-vendor', 'smartcloud-wpsuite-amplify-vendor', 'smartcloud-wpsuite-mantine-vendor'));
        wp_enqueue_script('smartcloud-gatey-admin-script', GATEY_URL . 'admin/index.js', $script_asset['dependencies'], GATEY_VERSION, array('in_footer' => true, 'strategy' => 'defer'));

        // Make the blocks translatable.
        if (function_exists('wp_set_script_translations')) {
            wp_set_script_translations('smartcloud-gatey-admin-script', 'gatey', GATEY_PATH . 'languages');
        }

        wp_enqueue_style('smartcloud-gatey-admin-style', GATEY_URL . 'admin/index.css', array('wp-components'), GATEY_VERSION);
        wp_enqueue_style('smartcloud-wpsuite-mantine-vendor-style', SMARTCLOUD_WPSUITE_URL . 'assets/css/mantine-vendor.css', array(), \SmartCloud\WPSuite\Hub\VERSION_MANTINE);
    }

    public function renderCognitoSettingsPage()
    {
        echo '<div id="smartcloud-gatey-admin"></div>';
    }

    public function initRestApi()
    {
        register_rest_route(
            GATEY_SLUG . '/v1',
            '/login',
            array(
                'methods' => 'POST',
                'callback' => array($this, 'login'),
                'permission_callback' => '__return_true',
            )
        );
        register_rest_route(
            GATEY_SLUG . '/v1',
            '/logout',
            array(
                'methods' => 'GET',
                'callback' => array($this, 'logout'),
                'permission_callback' => '__return_true',
            )
        );
        register_rest_route(
            GATEY_SLUG . '/v1',
            '/get-roles',
            array(
                'methods' => 'GET',
                'callback' => array($this, 'getRoles'),
                'permission_callback' => function () {
                    if (!current_user_can('manage_options')) {
                        return new WP_Error('rest_forbidden', esc_html__('Forbidden', 'gatey'), array('status' => 403));
                    }
                    return true;
                },
            )
        );
        register_rest_route(
            GATEY_SLUG . '/v1',
            '/update-settings',
            array(
                'methods' => 'POST',
                'callback' => array($this, 'updateSettings'),
                'permission_callback' => function () {
                    if (!current_user_can('manage_options')) {
                        return new WP_Error('rest_forbidden', esc_html__('Forbidden', 'gatey'), array('status' => 403));
                    }
                    return true;
                },
            )
        );
    }

    private function getRequestLogContext(WP_REST_Request $request): array
    {
        return array_filter(array(
            'method' => $request->get_method(),
            'route' => $request->get_route(),
            'request_uri' => isset($_SERVER['REQUEST_URI']) ? sanitize_text_field((string) wp_unslash($_SERVER['REQUEST_URI'])) : '',
            'http_referer' => isset($_SERVER['HTTP_REFERER']) ? esc_url_raw((string) wp_unslash($_SERVER['HTTP_REFERER'])) : '',
            'remote_addr' => isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field((string) wp_unslash($_SERVER['REMOTE_ADDR'])) : '',
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field((string) wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
        ), static fn($value) => '' !== $value);
    }

    private function getUserLogContext($user): array
    {
        if (!($user instanceof \WP_User)) {
            return array();
        }

        return array(
            'wp_user_id' => $user->ID,
            'wp_user_login' => (string) $user->user_login,
            'wp_user_email' => sanitize_email((string) $user->user_email),
            'wp_roles' => array_values((array) $user->roles),
        );
    }

    public function login(WP_REST_Request $request)
    {
        $data = $request->get_body_params();
        $request_context = array_merge(
            $this->getRequestLogContext($request),
            array(
                'requested_email' => sanitize_email((string) ($data['email'] ?? '')),
                'integrate_wp_login' => (bool) $this->settings->integrateWpLogin,
                'configured_sign_in_page' => (string) $this->settings->signInPage,
                'configured_redirect_sign_in' => (string) $this->settings->redirectSignIn,
                'configured_redirect_sign_out' => (string) $this->settings->redirectSignOut,
            )
        );

        Logger::info('Gatey login request received', $request_context);

        if (wp_get_current_user()->has_prop('user_email') && wp_get_current_user()->get('user_email') === $data['email']) {
            //return new WP_REST_Response(array('success' => true, 'message' => __('Already logged in.', 'gatey')), 200);
        }

        $region = $this->settings->userPoolConfigurations->default->API->GraphQL->region;
        $poolId = $this->settings->userPoolConfigurations->default->Auth->Cognito->userPoolId;
        $clientId = $this->settings->userPoolConfigurations->default->Auth->Cognito->userPoolClientId;
        $token = (string) $request->get_header('Authorization');
        if (
            strpos($token, 'Bearer ')
            !== 0
        ) {
            Logger::warning('Gatey login rejected due to invalid Authorization header', array_merge(
                $request_context,
                array(
                    'has_authorization_header' => '' !== $token,
                    'authorization_prefix' => substr($token, 0, 16),
                )
            ));
            return new WP_REST_Response(array('success' => false, 'message' => __('Invalid token.', 'gatey')), 401);
        }
        $token = substr($token, 7);

        $verifier = new CognitoTokenVerifier(
            $region,
            $poolId,
            $clientId
        );
        try {
            $t = $verifier->verifyIdToken($token);
        } catch (Exception $e) {
            Logger::warning('Gatey login token verification failed', array_merge(
                $request_context,
                array(
                    'region' => $region,
                    'pool_id' => $poolId,
                    'client_id_present' => !empty($clientId),
                    'verification_error' => $e->getMessage(),
                )
            ));
            return new WP_REST_Response(array('success' => false, 'message' => __('Invalid token.', 'gatey')), 401);
        }

        $updated = false;
        $diff = array();
        $cognito_groups = array_values((array) ($t['cognito:groups'] ?? array()));

        Logger::info('Gatey login token verified', array_merge(
            $request_context,
            array(
                'cognito_username' => (string) ($t['cognito:username'] ?? ''),
                'token_email' => sanitize_email((string) ($t['email'] ?? '')),
                'cognito_groups' => $cognito_groups,
            )
        ));

        $getByEmail = array_key_exists('email', $t);
        $user = $getByEmail ? get_user_by('email', $t['email']) : get_user_by('login', $t['cognito:username']);
        if ($getByEmail && !$user) {
            $user = get_user_by('login', $t['cognito:username']);
        }
        if (!$user) {
            Logger::info('Gatey login creating WordPress user', array_merge(
                $request_context,
                array(
                    'cognito_username' => (string) ($t['cognito:username'] ?? ''),
                    'token_email' => sanitize_email((string) ($t['email'] ?? '')),
                )
            ));

            $userdata = array(
                'user_login' => $t['cognito:username'],
                'user_pass' => /*$data['password'] ? $data['password'] : */ wp_generate_password(),
                'user_email' => array_key_exists('email', $t) ? $t['email'] : null,
                'first_name' => array_key_exists('given_name', $t) ? $t['given_name'] : null,
                'last_name' => array_key_exists('family_name', $t) ? $t['family_name'] : null,
                'nickname' => array_key_exists('preferred_username', $t) ? $t['preferred_username'] : null,
            );
            $user_id = wp_insert_user($userdata);
            if (is_wp_error($user_id)) {
                Logger::warning('Gatey login user creation failed, retrying email lookup', array_merge(
                    $request_context,
                    array(
                        'cognito_username' => (string) ($t['cognito:username'] ?? ''),
                        'token_email' => sanitize_email((string) ($t['email'] ?? '')),
                        'wp_error' => $user_id->get_error_message(),
                    )
                ));
                $user = get_user_by('email', $t['email']);
            } else {
                $user = get_user_by('id', $user_id);
            }
        } else if (
            (array_key_exists('email', $t) && $user->user_email != $t['email']) ||
            (array_key_exists('given_name', $t) && $user->first_name != $t['given_name']) ||
            (array_key_exists('family_name', $t) && $user->last_name != $t['family_name']) ||
            (array_key_exists('preferred_username', $t) && $user->nickname != $t['preferred_username'])
        ) {
            Logger::info('Gatey login syncing existing WordPress user profile', array_merge(
                $request_context,
                $this->getUserLogContext($user),
                array(
                    'token_email' => sanitize_email((string) ($t['email'] ?? '')),
                    'cognito_username' => (string) ($t['cognito:username'] ?? ''),
                )
            ));

            $user->user_email = array_key_exists('email', $t) ? $t['email'] : null;
            $user->first_name = array_key_exists('given_name', $t) ? $t['given_name'] : null;
            $user->last_name = array_key_exists('family_name', $t) ? $t['family_name'] : null;
            $user->nickname = array_key_exists('preferred_username', $t) ? $t['preferred_username'] : null;
            $updated = true;
        }

        if (!($user instanceof \WP_User)) {
            Logger::error('Gatey login could not resolve a WordPress user after token verification', array_merge(
                $request_context,
                array(
                    'cognito_username' => (string) ($t['cognito:username'] ?? ''),
                    'token_email' => sanitize_email((string) ($t['email'] ?? '')),
                )
            ));

            return new WP_REST_Response(array('success' => false, 'message' => __('Unable to complete sign in.', 'gatey')), 500);
        }

        if (!empty($this->settings->mappings)) {
            // get new roles from cognito groups, and remove all the other roles, than add the new ones and update the user
            $roles_by_cognito_groups = array_map(function ($mapping) {
                return $mapping->wordpressRole;
            }, $this->settings->mappings);
            $diff = array_diff($user->roles, $roles_by_cognito_groups);
            if (!empty($diff)) {
                foreach ($diff as $role) {
                    $user->remove_role($role);
                }
                $updated = true;
            }
        }
        if (!empty($cognito_groups)) {
            // if $this->settings->mappings empty, than if the cognito groups contains admin, add the user to the administrator role, otherwise to the subscriber role
            if (empty($this->settings->mappings)) {
                if (!empty($diff)) {
                    if (in_array('admin', $cognito_groups, true)) {
                        $user->add_role('administrator');
                    } else {
                        $user->add_role('subscriber');
                    }
                    $updated = true;
                }
            } else {
                foreach ($this->settings->mappings as $mapping) {
                    if (in_array($mapping->cognitoGroup, $cognito_groups, true) && !in_array($mapping->wordpressRole, $user->roles, true)) {
                        $user->add_role($mapping->wordpressRole);
                        $updated = true;
                    } else if (!in_array($mapping->cognitoGroup, $cognito_groups, true) && in_array($mapping->wordpressRole, $user->roles, true)) {
                        $user->remove_role($mapping->wordpressRole);
                        $updated = true;
                    }
                }
            }
        }
        if (empty($user->roles)) {
            $user->set_role('subscriber');
            $updated = true;
        }
        if ($updated) {
            $user_id = wp_update_user($user);
            if (is_wp_error($user_id)) {
                Logger::warning('Gatey login wp_update_user failed', array_merge(
                    $request_context,
                    $this->getUserLogContext($user),
                    array(
                        'wp_error' => $user_id->get_error_message(),
                        'cognito_groups' => $cognito_groups,
                    )
                ));
            } else {
                $user = get_user_by('id', $user_id);

                Logger::info('Gatey login updated WordPress user', array_merge(
                    $request_context,
                    $this->getUserLogContext($user),
                    array(
                        'cognito_groups' => $cognito_groups,
                    )
                ));
            }
        }

        if (in_array('administrator', $user->roles)) {
            $next_url = admin_url();
        } else {
            $next_url = home_url();
        }

        wp_set_current_user($user->ID, $user->user_login);
        wp_set_auth_cookie($user->ID, true);

        Logger::info('Gatey login completed', array_merge(
            $request_context,
            $this->getUserLogContext($user),
            array(
                'updated_user' => $updated,
                'cognito_username' => (string) ($t['cognito:username'] ?? ''),
                'cognito_groups' => $cognito_groups,
                'next_url' => $next_url,
            )
        ));

        //do_action('wp_login', $user->user_login, $user);
        return new WP_REST_Response(array('success' => true, 'message' => __('Logged in.', 'gatey'), 'redirect' => $next_url), 200);
    }

    public function logout(WP_REST_Request $request)
    {
        $user = wp_get_current_user();
        $request_context = array_merge(
            $this->getRequestLogContext($request),
            $this->getUserLogContext($user),
            array(
                'integrate_wp_login' => (bool) $this->settings->integrateWpLogin,
                'configured_sign_in_page' => (string) $this->settings->signInPage,
                'configured_redirect_sign_out' => (string) $this->settings->redirectSignOut,
            )
        );

        Logger::info('Gatey logout request received', $request_context);

        if ($user && is_array($user->roles) && sizeof($user->roles) > 0 && in_array($user->roles[0], array('administrator'))) {
            $next_url = admin_url();
        } else {
            $next_url = home_url();
        }

        wp_logout();

        Logger::info('Gatey logout completed', array_merge(
            $request_context,
            array(
                'next_url' => $next_url,
            )
        ));

        return new WP_REST_Response(array('success' => true, 'message' => __('Logged out.', 'gatey'), 'redirect' => $next_url), 200);
    }
    public function getRoles(WP_REST_Request $request)
    {
        global $wp_roles;
        return new WP_REST_Response(array_keys(array_map(array($this, 'getRoleName'), $wp_roles->roles)), 200);
    }
    public function getRoleName($role)
    {
        return $role['name'];
    }
    public function updateSettings(WP_REST_Request $request)
    {
        $settings_param = json_decode($request->get_body());

        $debugLoggingEnabled = (bool) ($settings_param->debugLoggingEnabled ?? false);

        $this->settings = new Settings(
            new UserPoolConfigurations(
                new ResourceConfiguration(
                    new AuthConfiguration(
                        new Configuration(
                            $settings_param?->userPoolConfigurations?->default?->Auth?->Cognito?->userPoolId,
                            $settings_param?->userPoolConfigurations?->default?->Auth?->Cognito?->identityPoolId,
                            $settings_param?->userPoolConfigurations?->default?->Auth?->Cognito?->userPoolClientId,
                            new LoginWithOAuthConfiguration(
                                new OAuthConfiguration(
                                    $settings_param?->userPoolConfigurations?->default?->Auth?->Cognito?->loginWith?->oauth?->domain,
                                    $settings_param?->userPoolConfigurations?->default?->Auth?->Cognito?->loginWith?->oauth?->scopes
                                )
                            )
                        )
                    ),
                    new ApiConfiguration(
                        new RestConfiguration(
                            $settings_param?->userPoolConfigurations?->default?->API?->GraphQL?->region,
                        ),
                    ),
                ),
                new ResourceConfiguration(
                    new AuthConfiguration(
                        new Configuration(
                            $settings_param?->userPoolConfigurations?->secondary?->Auth?->Cognito?->userPoolId,
                            $settings_param?->userPoolConfigurations?->secondary?->Auth?->Cognito?->identityPoolId,
                            $settings_param?->userPoolConfigurations?->secondary?->Auth?->Cognito?->userPoolClientId,
                            new LoginWithOAuthConfiguration(
                                new OAuthConfiguration(
                                    $settings_param?->userPoolConfigurations?->secondary?->Auth?->Cognito?->loginWith?->oauth?->domain,
                                    $settings_param?->userPoolConfigurations?->secondary?->Auth?->Cognito?->loginWith?->oauth?->scopes
                                )
                            )
                        )
                    ),
                    new ApiConfiguration(
                        new RestConfiguration(
                            $settings_param?->userPoolConfigurations?->secondary?->API?->GraphQL?->region,
                        ),
                    ),
                ),
            ),
            $settings_param->secondaryUserPoolDomains ?? "",
            $settings_param?->mappings,
            $settings_param->loginMechanisms ?? [],
            $settings_param->integrateWpLogin ?? false,
            isset($settings_param?->cookieExpiration) && $settings_param->cookieExpiration > 0 ? $settings_param->cookieExpiration : 43200,
            $settings_param->signInPage ?? "",
            $settings_param->redirectSignIn ?? "",
            $settings_param->redirectSignOut ?? "",
            $settings_param->customTranslationsUrl ?? "",
            $settings_param->signUpAttributes ?? [],
            $settings_param->socialProviders ?? [],
            (array) ($settings_param->passwordlessSettings ?? []),
            $settings_param->hideSignUp ?? false,
            $settings_param->enablePoweredBy ?? false,
            $debugLoggingEnabled,
        );

        // Frissített beállítások mentése
        update_option(GATEY_SLUG, $this->settings);

        Logger::info('Gatey settings updated', [
            'debugLoggingEnabled' => $debugLoggingEnabled,
            'hideSignUp' => $this->settings->hideSignUp,
            'enablePoweredBy' => $this->settings->enablePoweredBy,
            'integrateWpLogin' => $this->settings->integrateWpLogin,
            'cookieExpiration' => $this->settings->cookieExpiration,
            'mapping_count' => count($this->settings->mappings),
            'loginMechanisms_count' => count($this->settings->loginMechanisms),
            'has_secondary_pool' => !empty($settings_param?->userPoolConfigurations?->secondary?->Auth?->Cognito?->userPoolId)
        ]);

        return new WP_REST_Response(array('success' => true, 'message' => __('Settings updated successfully.', 'gatey')), 200);
    }

    public function setAuthCookieExpiration($length, $user_id, $remember)
    {
        return $this->settings->cookieExpiration;
    }

    private function registerRestRoutes()
    {
        if (!class_exists('WP_REST_Controller')) {
            return;
        }

        add_action('rest_api_init', array($this, 'initRestApi'));
    }

}