<?php

namespace CleantalkSP\SpbctWP\Settings;

use CleantalkSP\SpbctWP\DTO\ReactDataDTO;

class SettingsGeneralReact
{
    public static function getReactData()
    {
        global $spbc;

        $user  = wp_get_current_user();
        $email = (isset($user->ID) && $user->ID > 0) ? $user->user_email : spbc_get_admin_email();

        $storage_settings = (isset($spbc->storage['settings']) && is_array($spbc->storage['settings'])) ?
            $spbc->storage['settings'] :
            (array) $spbc->settings;

        $auth_login_url = wp_login_url();
        if (
            ! empty($storage_settings['login_page_rename__enabled']) &&
            ! empty($storage_settings['login_page_rename__name'])
        ) {
            $auth_login_url = get_site_url() . '/' . $storage_settings['login_page_rename__name'];
        }

        $data['strings'] = [
            'settingsSlug' => SPBC_SETTINGS,
            'nonce' => wp_create_nonce(SPBC_SETTINGS . '-options'),
            'two_fa_verification_email_recipient' => $email,
            'auth_login_page_url' => $auth_login_url,
            'tech_support_url_field_prefix' => get_home_url() . '/' . (get_option('permalink_structure', false) ? '' : '?'),
            'login_rename_notify_admin_email' => spbc_get_admin_email(),
        ];
        $data['flags'] = [
            'keyIsOk' => (bool) $spbc->key_is_ok,
            'canActivatePlugins' => (bool) current_user_can('activate_plugins'),
            'shuffleSaltsUnlocked' => ! empty($spbc->settings['there_was_signature_treatment']),
        ];
        $data['objects'] = [
            'settings' => self::groupSettings(array_merge((array)$spbc->network_settings, (array)$spbc->settings)),
            'wp_user_roles_options' => self::getWpUserRolesOptionsForReact(),
        ];

        $dto = new ReactDataDTO($data);

        return $dto->getArray();
    }

    private static function groupSettings($settings)
    {
        global $spbc;

        $grouped_settings = [];
        foreach ($settings as $key => $value) {
            if (
                $key === 'spbc_key'
            ) {
                if (
                    ! (
                        is_main_site() ||
                        $spbc->ms__work_mode == 3 ||
                        ($spbc->ms__work_mode == 1 && is_super_admin())
                    )
                ) {
                    $value = 'Provided by admin';
                }
                $grouped_settings['apikey'][$key] = $value;
            }
            if (
                $key === 'bfp__heading' ||
                $key === 'bfp__delay__1_fails' ||
                $key === 'bfp__delay__5_fails' ||
                $key === 'bfp__allowed_wrong_auths' ||
                $key === 'bfp__count_interval' ||
                $key === 'bfp__block_period__5_fails' ||
                $key === 'check_pass__enable' ||
                $key === 'check_pass__roles' ||
                $key === '2fa__enable' ||
                $key === '2fa__roles' ||
                $key === 'edit_tech_support_url__enabled' ||
                $key === 'edit_tech_support_url__link' ||
                $key === 'edit_tech_support_url__remove' ||
                $key === 'login_page_rename__enabled' ||
                $key === 'login_page_rename__name' ||
                $key === 'login_page_rename__redirect' ||
                $key === 'login_page_rename__send_email_notification'
            ) {
                $grouped_settings['auth_and_logging_in'][$key] = $value;
            }

            if ( is_multisite() && is_main_site() &&
                ( $key === 'ms__work_mode' ||
                $key === 'ms__hoster_api_key' ||
                $key === 'ms__service_utilization' ) // <----- @ToDo Remove?
            ) {
                $grouped_settings['apikey'][$key] = $value;
            }

            if (
                $key === 'fw__custom_message' ||
                $key === 'secfw__enabled' ||
                $key === 'waf__enabled' ||
                $key === 'waf__xss_check' ||
                $key === 'waf__sql_check' ||
                $key === 'waf__exploit_check' ||
                $key === 'waf_blocker__enabled'
            ) {
                $grouped_settings['firewall'][$key] = $value;
            }
        }

        // Reorder auth_and_logging_in settings to ensure correct display order
        if (! empty($grouped_settings['auth_and_logging_in'])) {
            // UI-only field (not a saved option); rendered by React ActionShuffleSalts
            $grouped_settings['auth_and_logging_in']['action_shuffle_salts'] = true;

            $auth_settings_order = [
                'bfp__heading',
                'bfp__delay__1_fails',
                'bfp__delay__5_fails',
                'bfp__allowed_wrong_auths',
                'bfp__count_interval',
                'bfp__block_period__5_fails',
                'check_pass__enable',
                'check_pass__roles',
                '2fa__enable',
                '2fa__roles',
                'edit_tech_support_url__enabled',
                'edit_tech_support_url__link',
                'edit_tech_support_url__remove',
                'login_page_rename__enabled',
                'login_page_rename__name',
                'login_page_rename__redirect',
                'login_page_rename__send_email_notification',
                'action_shuffle_salts',
            ];
            $ordered = [];
            foreach ($auth_settings_order as $key) {
                if (isset($grouped_settings['auth_and_logging_in'][$key])) {
                    $ordered[$key] = $grouped_settings['auth_and_logging_in'][$key];
                }
            }
            $grouped_settings['auth_and_logging_in'] = $ordered;
        }

        return $grouped_settings;
    }

    /**
     * Role slugs and labels for React multiselects (matches PHP settings fields).
     *
     * @return array<int, array{value: string, label: string}>
     */
    private static function getWpUserRolesOptionsForReact()
    {
        $wp_roles = wp_roles();
        $out      = array();

        foreach ($wp_roles->roles as $slug => $details) {
            $name    = isset($details['name']) ? $details['name'] : (string) $slug;
            $out[] = array(
                'value' => (string) $slug,
                'label' => $name,
            );
        }

        return $out;
    }
}
