<?php
/**
 * React-based 2FA Profile Settings Template
 *
 * This template renders a React root element and passes data via window object
 */

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;

$ultimate_security_options = Utils::ultimate_security_get_option();

$available_providers = [];

// Get application authentication type (TOTP or HOTP)
$application_authentication_type = isset($ultimate_security_options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_type'])
    ? $ultimate_security_options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_type']
    : 'TOTP';

// Email authentication settings
$enable_2fa_email_verification = isset($ultimate_security_options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable'])
    ? $ultimate_security_options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable']
    : 0;
$email_verification_enable_for = isset($ultimate_security_options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable_for'])
    ? $ultimate_security_options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable_for']
    : '';

// Get email allowed user roles
$email_verification_enable_for_arr = $email_allowed_user_roles = [];
if ($email_verification_enable_for) {
    $email_verification_enable_for_arr = $ultimate_security_options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable_for'];
    if (is_array($email_verification_enable_for_arr) && sizeof($email_verification_enable_for_arr)) {
        foreach ($email_verification_enable_for_arr as $k => $v) {
            if (is_array($v) && isset($v['code'])) {
                $email_allowed_user_roles[] = $v['code'];
            } elseif (is_string($v)) {
                $email_allowed_user_roles[] = $v;
            }
        }
    }
}
$email_allowed_user_roles = array_intersect($email_allowed_user_roles, $user->roles);
if ($enable_2fa_email_verification && sizeof($email_allowed_user_roles))
    $available_providers[] = ['value' => 'Email', 'label' => 'Email'];

// Application authentication settings
$enable_2fa_application_authentication = isset($ultimate_security_options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_enable'])
    ? $ultimate_security_options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_enable']
    : 0;
$application_authentication_enable_for = isset($ultimate_security_options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_enable_for'])
    ? $ultimate_security_options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_enable_for']
    : '';

// Get application allowed user roles
$application_authentication_enable_for_arr = $application_allowed_user_roles = [];
if ($application_authentication_enable_for) {
    $application_authentication_enable_for_arr = $ultimate_security_options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_enable_for'];
    if (is_array($application_authentication_enable_for_arr) && sizeof($application_authentication_enable_for_arr)) {
        foreach ($application_authentication_enable_for_arr as $k => $v) {
            if (is_array($v) && isset($v['code'])) {
                $application_allowed_user_roles[] = $v['code'];
            } elseif (is_string($v)) {
                $application_allowed_user_roles[] = $v;
            }
        }
    }
}
$application_allowed_user_roles = array_intersect($application_allowed_user_roles, $user->roles);
if ($enable_2fa_application_authentication && sizeof($application_allowed_user_roles))
    $available_providers[] = ['value' => 'Authenticator Application', 'label' => 'Authenticator Application'];
// Get selected provider
$selected_2fa_provider = get_user_meta($user->ID, 'ultimate-security-2fa-provider', true)
    ? get_user_meta($user->ID, 'ultimate-security-2fa-provider', true)
    : '';

// Get email authentication status
$ultimate_security_enable_email_authentication = get_user_meta($user->ID, 'ultimate_security_enable_email_authentication', true)
    ? get_user_meta($user->ID, 'ultimate_security_enable_email_authentication', true)
    : 0;

// Check if Pro version
$is_pro = \WPUltimateSecurity\UltimateSecurity\Support\Validation\ProValidation::ultimate_security_is_pro();

// Passkeys settings - show in profile if Pro is active
$passkeys_feature_enabled = isset($ultimate_security_options['security']['passkeys']['general_settings']['enable_passkeys']) &&
    $ultimate_security_options['security']['passkeys']['general_settings']['enable_passkeys'];
$passkeys_show_in_profile = isset($ultimate_security_options['security']['passkeys']['display_settings']['display_passkeys_in_users_profile']) &&
    $ultimate_security_options['security']['passkeys']['display_settings']['display_passkeys_in_users_profile'];
// Show passkeys section for all Pro users - let them set up even if not fully configured
// The Passkeys endpoints are always registered in Pro, so this should work
$passkeys_enabled = $is_pro;

// Passkey policy data for React component
$passkey_enforce_for_roles = isset($ultimate_security_options['security']['passkeys']['policy_settings']['enforce_for_roles'])
    ? $ultimate_security_options['security']['passkeys']['policy_settings']['enforce_for_roles']
    : [];
$passkey_is_required = !empty(array_intersect($user->roles, $passkey_enforce_for_roles));
$passkey_grace_period_days = isset($ultimate_security_options['security']['passkeys']['policy_settings']['grace_period_days'])
    ? (int) $ultimate_security_options['security']['passkeys']['policy_settings']['grace_period_days']
    : 7;

// Calculate grace period remaining
$passkey_grace_remaining = 0;
if ($passkey_is_required) {
    $user_registered = strtotime($user->user_registered);
    $grace_expires = $user_registered + ($passkey_grace_period_days * DAY_IN_SECONDS);
    $passkey_grace_remaining = max(0, ceil(($grace_expires - time()) / DAY_IN_SECONDS));
}

// Get passkey count for this user
$passkey_count = 0;
if ($is_pro && class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\Passkeys\PasskeyPolicies')) {
    $passkey_count = \WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\Passkeys\PasskeyPolicies::get_passkey_count($user->ID);
}

// SMS authentication settings (Pro) - show if Pro is active
$sms_feature_enabled = isset($ultimate_security_options['security']['2fa_authentication']['sms_authentication']['enable']) &&
    $ultimate_security_options['security']['2fa_authentication']['sms_authentication']['enable'];
// For SMS, show in dropdown if Pro is active (even if not fully configured)
$sms_enabled = $is_pro;

$sms_enable_for = isset($ultimate_security_options['security']['2fa_authentication']['sms_authentication']['allowed_roles'])
    ? $ultimate_security_options['security']['2fa_authentication']['sms_authentication']['allowed_roles']
    : [];

// Get SMS allowed user roles - if not configured, allow all roles for Pro users
$sms_allowed_user_roles = [];


if (is_array($sms_enable_for) && !empty($sms_enable_for)) {
    // Extract role codes from the array structure if needed
    $sms_roles = [];
    foreach ($sms_enable_for as $role) {
        if (is_array($role) && isset($role['code'])) {
            $sms_roles[] = $role['code'];
        } elseif (is_string($role)) {
            $sms_roles[] = $role;
        }
    }
    $sms_allowed_user_roles = array_intersect($sms_roles, $user->roles);
} elseif ($is_pro) {
    // If no roles configured but Pro is active, allow all user roles
    $sms_allowed_user_roles = $user->roles;
}

// Always ensure administrators can use SMS when Pro is active
if ($is_pro && in_array('administrator', $user->roles) && !in_array('administrator', $sms_allowed_user_roles)) {
    $sms_allowed_user_roles[] = 'administrator';
}

// error_log(print_r($sms_allowed_user_roles, true));
if ($sms_feature_enabled && sizeof($sms_allowed_user_roles) > 0 && $is_pro) {
    $available_providers[] = ['value' => 'SMS', 'label' => 'SMS Authentication (Pro)'];
}

// Get SMS verification status for user
$sms_verified = get_user_meta($user->ID, 'ultimate_security_sms_verified', true);
$sms_phone = get_user_meta($user->ID, 'ultimate_security_sms_phone', true);
// Mask phone number for security
$sms_phone_masked = '';
if ($sms_phone && strlen($sms_phone) > 7) {
    $sms_phone_masked = substr($sms_phone, 0, 2) . str_repeat('*', strlen($sms_phone) - 6) . substr($sms_phone, -4);
}

// Backup codes count (Pro)
$backup_codes_count = 0;
if ($is_pro && class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService')) {
    $backup_codes_count = \WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService::get_remaining_count($user->ID);
}

// Prepare initial data for React
$initial_data = [
    'selectedProvider' => $selected_2fa_provider,
    'emailEnabled' => $enable_2fa_email_verification,
    'emailAllowedRoles' => $email_allowed_user_roles,
    'emailAuthEnabled' => $ultimate_security_enable_email_authentication,
    'appEnabled' => $enable_2fa_application_authentication,
    'appAllowedRoles' => $application_allowed_user_roles,
    'appType' => $application_authentication_type,
    'isPro' => $is_pro,
    'passkeysEnabled' => $passkeys_enabled,
    'displayPasskeysInUsersProfile' => $passkeys_show_in_profile,
    'logoUrl' => ULTIMATE_SECURITY_URL . 'assets/admin/images/logo-44x44.svg',
    'version' => ULTIMATE_SECURITY_VERSION,
    // Pro features
    'smsEnabled' => $sms_enabled,
    'smsAllowedRoles' => $sms_allowed_user_roles,
    'smsVerified' => $sms_verified,
    'smsPhone' => $sms_phone_masked,
    'backupCodesCount' => $backup_codes_count,
    'available_providers' => $available_providers,
    // Passkey policy data
    'passkeyPolicy' => [
        'isRequired' => $passkey_is_required,
        'enforceForRoles' => $passkey_enforce_for_roles,
        'gracePeriodDays' => $passkey_grace_period_days,
        'gracePeriodRemaining' => $passkey_grace_remaining,
        'passkeyCount' => $passkey_count,
        'userRoles' => $user->roles,
    ],
];

// Add TOTP data if applicable
if ($application_authentication_type === 'TOTP') {
    $initial_data['totpData'] = [
        'currentCode' => $totp_current_code,
        'secret' => $totp_secret,
        'qrCodeUri' => $totp_qr_code_uri,
        'refreshAfter' => $refresh_after,
    ];
}

// Add HOTP data if applicable
if ($application_authentication_type === 'HOTP') {
    $initial_data['hotpData'] = [
        'currentCode' => $hotp_current_code,
        'secret' => $hotp_secret,
        'qrCodeUri' => $hotp_qr_code_uri,
        'counter' => $hotp_counter,
        'refreshAfter' => $refresh_after,
    ];
}
?>

<!-- React Root Element -->
<div id="ultimate-security-2fa-profile-root"></div>

<script type="text/javascript">
    window.ultimateSecurityProfile = {
        userId: <?php echo json_encode($user->ID); ?>,
        ajaxUrl: <?php echo json_encode(admin_url('admin-ajax.php')); ?>,
        nonce: <?php echo json_encode(wp_create_nonce('ultimate_security_nonce')); ?>,
        restUrl: <?php echo json_encode(get_rest_url()); ?>,
        restNonce: <?php echo json_encode(wp_create_nonce('wp_rest')); ?>,
        pluginUrl: <?php echo json_encode(ULTIMATE_SECURITY_URL); ?>,
        siteName: <?php echo json_encode(get_bloginfo('name')); ?>,
        initialData: <?php echo json_encode($initial_data); ?>,
        // Debug info - can be removed in production
        debug: {
            isPro: <?php echo json_encode($is_pro); ?>,
            passkeysEnabled: <?php echo json_encode($passkeys_enabled); ?>,
            smsEnabled: <?php echo json_encode($sms_enabled); ?>,
            smsAllowedRoles: <?php echo json_encode($sms_allowed_user_roles); ?>,
            userRoles: <?php echo json_encode($user->roles); ?>
        }
    };
    // console.log('Ultimate Security 2FA Profile Debug:', window.ultimateSecurityProfile.debug);
</script>