<?php

declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Modules\Setup;

/**
 * Security Profiles Definition
 *
 * Defines pre-configured security profiles for the Security Wizard.
 * Each profile contains settings that will be applied when selected.
 */
class SecurityProfiles
{
    /**
     * Profile levels
     */
    public const LEVEL_BASIC = 'basic';
    public const LEVEL_MODERATE = 'moderate';
    public const LEVEL_STRICT = 'strict';

    /**
     * Get all available security profiles
     *
     * @return array
     */
    public static function getProfiles(): array
    {
        return [
            self::LEVEL_BASIC => self::getBasicProfile(),
            self::LEVEL_MODERATE => self::getModerateProfile(),
            self::LEVEL_STRICT => self::getStrictProfile(),
        ];
    }

    /**
     * Get a specific profile by level
     *
     * @param string $level Profile level
     * @return array|null
     */
    public static function getProfile(string $level): ?array
    {
        $profiles = self::getProfiles();
        return $profiles[$level] ?? null;
    }

    /**
     * Get profile metadata for display
     *
     * @return array
     */
    public static function getProfileMeta(): array
    {
        return [
            self::LEVEL_BASIC => [
                'name' => __('Basic Protection', 'ultimate-security'),
                'description' => __('Essential security measures for small websites and blogs. Low impact on performance.', 'ultimate-security'),
                'icon' => 'shield',
                'color' => 'green',
                'recommended_for' => __('Personal blogs, small websites, beginners', 'ultimate-security'),
                'features' => [
                    __('Custom login URL', 'ultimate-security'),
                    __('Basic password policy (10+ characters)', 'ultimate-security'),
                    __('Login attempt limits', 'ultimate-security'),
                    __('Hide WordPress version', 'ultimate-security'),
                ],
            ],
            self::LEVEL_MODERATE => [
                'name' => __('Balanced Security', 'ultimate-security'),
                'description' => __('Comprehensive protection with minimal user friction. Recommended for most websites.', 'ultimate-security'),
                'icon' => 'lock',
                'color' => 'blue',
                'recommended_for' => __('Business websites, WooCommerce stores, membership sites', 'ultimate-security'),
                'features' => [
                    __('All Basic features', 'ultimate-security'),
                    __('Two-factor authentication (email)', 'ultimate-security'),
                    __('Enhanced brute force protection', 'ultimate-security'),
                    __('Security headers enabled', 'ultimate-security'),
                    __('Stronger password policy (13+ characters)', 'ultimate-security'),
                    __('URL Guard protection', 'ultimate-security'),
                ],
            ],
            self::LEVEL_STRICT => [
                'name' => __('Maximum Security', 'ultimate-security'),
                'description' => __('Enterprise-grade protection with strict policies. May require user training.', 'ultimate-security'),
                'icon' => 'safe',
                'color' => 'purple',
                'recommended_for' => __('E-commerce, financial sites, enterprise applications', 'ultimate-security'),
                'features' => [
                    __('All Moderate features', 'ultimate-security'),
                    __('2FA required for administrators', 'ultimate-security'),
                    __('Advanced rate limiting', 'ultimate-security'),
                    __('Full security headers suite', 'ultimate-security'),
                    __('Maximum password policy (15+ characters)', 'ultimate-security'),
                    __('API privacy controls', 'ultimate-security'),
                    __('Content protection enabled', 'ultimate-security'),
                ],
            ],
        ];
    }

    /**
     * Basic Profile - Essential security for small sites
     *
     * @return array
     */
    private static function getBasicProfile(): array
    {
        return [
            'security' => [
                'password_policies' => [
                    'activate_password_policies' => '1',
                    'min_length' => 10,
                    'ui_rules_mix_case' => '1',
                    'ui_rules_numeric' => '1',
                ],
                'login_limit' => [
                    'enable' => '1',
                    'login_attempts' => 5,
                    'lockout_duration' => 15,
                    'increase_login_attempts' => 10,
                    'increase_lockout_duration' => 60,
                    'retries_reset_duration' => 24,
                ],
                'recommendations' => [
                    'hide_wordpress_version' => '1',
                    'disable_file_editors' => '1',
                    'prevent_login_feedback' => '1',
                ],
                'url_guard' => [
                    'overview' => [
                        'enable' => '1',
                    ],
                ],
            ],
        ];
    }

    /**
     * Moderate Profile - Balanced security for business sites
     *
     * @return array
     */
    private static function getModerateProfile(): array
    {
        return [
            'security' => [
                'password_policies' => [
                    'activate_password_policies' => '1',
                    'min_length' => 13,
                    'ui_rules_mix_case' => '1',
                    'ui_rules_numeric' => '1',
                    'ui_rules_special_chars' => '1',
                    'password_history' => '1',
                ],
                'login_limit' => [
                    'enable' => '1',
                    'login_attempts' => 4,
                    'lockout_duration' => 20,
                    'increase_login_attempts' => 8,
                    'increase_lockout_duration' => 120,
                    'retries_reset_duration' => 12,
                ],
                '2fa_authentication' => [
                    'email_authentication' => [
                        '2fa_email_verification_enable' => '1',
                    ],
                    'application_authentication' => [
                        '2fa_application_authentication_enable' => '1',
                    ],
                ],
                'recommendations' => [
                    'hide_wordpress_version' => '1',
                    'disable_file_editors' => '1',
                    'prevent_login_feedback' => '1',
                    'disable_directory_browsing' => '1',
                    'disable_user_enumeration' => '1',
                    'unset_x_powered_by_header' => '1',
                    'block_common_usernames' => '1',
                ],
                'url_guard' => [
                    'overview' => [
                        'enable' => '1',
                        'log_retention_days' => '30',
                    ],
                ],
            ],
            'security_headers' => [
                'enable' => '1',
                'x_frame_options' => [
                    'enable' => '1',
                    'policy' => 'SAMEORIGIN',
                ],
                'x_content_type_options' => '1',
                'x_xss_protection' => '1',
                'referrer_policy' => [
                    'enable' => '1',
                    'policy' => 'strict-origin-when-cross-origin',
                ],
            ],
        ];
    }

    /**
     * Strict Profile - Maximum security for enterprise sites
     *
     * @return array
     */
    private static function getStrictProfile(): array
    {
        return [
            'security' => [
                'password_policies' => [
                    'activate_password_policies' => '1',
                    'min_length' => 15,
                    'ui_rules_mix_case' => '1',
                    'ui_rules_numeric' => '1',
                    'ui_rules_special_chars' => '1',
                    'password_history' => '1',
                    'password_expiry_value' => 90,
                    'password_expiry_unit' => 'day',
                    'password_expiry_warning_days' => 14,
                    'change_initial_password' => '1',
                ],
                'login_limit' => [
                    'enable' => '1',
                    'login_attempts' => 3,
                    'lockout_duration' => 30,
                    'increase_login_attempts' => 5,
                    'increase_lockout_duration' => 180,
                    'retries_reset_duration' => 6,
                ],
                '2fa_authentication' => [
                    'email_authentication' => [
                        '2fa_email_verification_enable' => '1',
                        '2fa_email_verification_enable_for' => ['administrator'],
                    ],
                    'application_authentication' => [
                        '2fa_application_authentication_enable' => '1',
                        '2fa_application_authentication_enable_for' => ['administrator'],
                    ],
                ],
                'recommendations' => [
                    'hide_wordpress_version' => '1',
                    'disable_file_editors' => '1',
                    'prevent_login_feedback' => '1',
                    'disable_directory_browsing' => '1',
                    'disable_user_enumeration' => '1',
                    'unset_x_powered_by_header' => '1',
                    'block_common_usernames' => '1',
                    'change_display_name' => '1',
                    'disable_XMLRPC' => '1',
                    'remove_rsd_link' => '1',
                    'remove_wlw_manifest_link' => '1',
                    'remove_shortlink' => '1',
                    'hide_css_file_version' => '1',
                    'hide_js_file_version' => '1',
                ],
                'url_guard' => [
                    'overview' => [
                        'enable' => '1',
                        'log_retention_days' => '60',
                    ],
                ],
                'content_protection' => [
                    'enable' => '1',
                    'disable_right_click' => '1',
                    'disable_dev_tools' => '1',
                    'disable_view_source' => '1',
                ],
                'api_privacy' => [
                    'enable' => '1',
                    'strip_wp_version' => '1',
                    'strip_user_logins' => '1',
                ],
            ],
            'security_headers' => [
                'enable' => '1',
                'x_frame_options' => [
                    'enable' => '1',
                    'policy' => 'DENY',
                ],
                'x_content_type_options' => '1',
                'x_xss_protection' => '1',
                'referrer_policy' => [
                    'enable' => '1',
                    'policy' => 'strict-origin-when-cross-origin',
                ],
                'hsts' => [
                    'enable' => '1',
                    'max_age' => 31536000,
                    'include_subdomains' => '1',
                ],
                'permissions_policy' => [
                    'enable' => '1',
                    'camera' => 'none',
                    'microphone' => 'none',
                    'geolocation' => 'none',
                ],
            ],
            'rate_limiter' => [
                'rate_limiting_enabled' => '1',
                'rate_limit_authenticated' => 100,
                'rate_limit_anonymous' => 40,
            ],
        ];
    }

    /**
     * Get the settings keys that will be modified by a profile
     *
     * @param string $level Profile level
     * @return array List of setting paths that will be changed
     */
    public static function getProfileSettingKeys(string $level): array
    {
        $profile = self::getProfile($level);
        if (!$profile) {
            return [];
        }

        $keys = [];
        self::extractSettingKeys($profile, '', $keys);
        return $keys;
    }

    /**
     * Recursively extract setting keys from profile
     *
     * @param array $data Profile data
     * @param string $prefix Current key prefix
     * @param array $keys Collected keys
     */
    private static function extractSettingKeys(array $data, string $prefix, array &$keys): void
    {
        foreach ($data as $key => $value) {
            $currentKey = $prefix ? "{$prefix}.{$key}" : $key;
            if (is_array($value) && !self::isLeafValue($value)) {
                self::extractSettingKeys($value, $currentKey, $keys);
            } else {
                $keys[] = $currentKey;
            }
        }
    }

    /**
     * Check if value is a leaf (not a nested settings array)
     *
     * @param mixed $value Value to check
     * @return bool
     */
    private static function isLeafValue($value): bool
    {
        if (!is_array($value)) {
            return true;
        }
        // If all keys are numeric, it's a list value (like roles array)
        $keys = array_keys($value);
        foreach ($keys as $key) {
            if (!is_numeric($key)) {
                return false;
            }
        }
        return true;
    }
}
