<?php
/**
 * Email-Based Two-Factor Authentication
 * 
 * Handles email-based two-factor authentication by sending verification codes
 * to users' email addresses during the login process.
 *
 * @package GuardDog
 * @since 1.8.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class Guard_Dog_Email_Two_Factor_Auth {

    /**
     * User meta key for email 2FA enabled status
     * @var string
     */
    const USER_META_ENABLED_KEY = '_guard_dog_email_2fa_enabled';

    /**
     * User meta key for email 2FA verification codes
     * @var string
     */
    const USER_META_CODES_KEY = '_guard_dog_email_2fa_codes';

    /**
     * Email provider instance
     * @var Guard_Dog_Email_Provider
     */
    private $email_provider;

    /**
     * Activity log instance
     * @var Guard_Dog_Activity_Log
     */
    private $activity_log;

    /**
     * Constructor
     *
     * @param Guard_Dog_Activity_Log $activity_log Activity log instance
     * @param Guard_Dog_Email_Provider|null $email_provider Email provider instance (optional)
     */
    public function __construct($activity_log, $email_provider = null) {
        $this->activity_log = $activity_log;
        $this->email_provider = $email_provider ?: new Guard_Dog_Email_Provider();
        $this->add_hooks();
    }

    /**
     * Add WordPress hooks
     */
    public function add_hooks() {
        // User profile actions.
        // Profile page hooks are now handled in the main 2FA template.
        // Email 2FA is integrated into the consolidated user profile 2FA section.
        add_action( 'personal_options_update', array( $this, 'save_user_profile_settings' ) );
        add_action( 'edit_user_profile_update', array( $this, 'save_user_profile_settings' ) );

        // AJAX handlers for logged-in users.
        add_action( 'wp_ajax_guard_dog_send_email_2fa_code', array( $this, 'ajax_send_verification_code' ) );
        add_action( 'wp_ajax_guard_dog_verify_email_2fa_code', array( $this, 'ajax_verify_email_code' ) );
        add_action( 'wp_ajax_guard_dog_enable_email_2fa', array( $this, 'ajax_enable_email_2fa' ) );
        add_action( 'wp_ajax_guard_dog_disable_email_2fa', array( $this, 'ajax_disable_email_2fa' ) );
        add_action( 'wp_ajax_guard_dog_refresh_email_2fa_nonces', array( $this, 'ajax_refresh_email_2fa_nonces' ) );
        
        // AJAX handlers for non-logged-in users (needed during 2FA login process).
        add_action( 'wp_ajax_nopriv_guard_dog_send_email_2fa_code', array( $this, 'ajax_send_verification_code' ) );

        // Script enqueueing.
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_profile_scripts' ) );

        // Shortcode registration - now handled by the main 2FA shortcode
        // add_shortcode('guard_dog_email_2fa', [$this, 'shortcode_handler']);
    }

    /**
     * Check if email 2FA is enabled for a user
     *
     * @param int|WP_User|string $user User ID, user object, username, or email
     * @return bool
     */
    public function is_email_2fa_enabled_for_user($user) {
        $user_id = $this->get_user_id($user);
        if ($user_id <= 0) {
            return false;
        }

        return (bool) get_user_meta($user_id, self::USER_META_ENABLED_KEY, true);
    }

    /**
     * Check if the email provider is configured and ready to use
     *
     * @return bool
     */
    public function is_email_provider_configured() {
        return $this->email_provider->is_configured();
    }

    /**
     * Get user ID from various input types
     *
     * @param int|WP_User|string $user User ID, user object, username, or email
     * @return int
     */
    private function get_user_id($user) {
        if (is_numeric($user)) {
            return absint($user);
        } elseif ($user instanceof WP_User) {
            return $user->ID;
        } elseif (is_string($user)) {
            if (is_email($user)) {
                $user_obj = get_user_by('email', sanitize_email($user));
            } else {
                $user_obj = get_user_by('login', sanitize_user($user));
            }
            
            if ($user_obj && !is_wp_error($user_obj)) {
                return $user_obj->ID;
            }
        }

        return 0;
    }

    /**
     * Generate a verification code
     *
     * @return string
     */
    private function generate_verification_code() {
        return sprintf('%06d', wp_rand(0, 999999));
    }

    /**
     * Send verification code to user's email
     *
     * @param int $user_id User ID
     * @return array Result array with 'success' boolean and 'message' string
     */
    public function send_verification_code($user_id) {
        $user = get_user_by('ID', $user_id);
        if ( ! $user ) {
            return array(
                'success' => false,
                'message' => __( 'Invalid user.', 'guard-dog' )
            );
        }

        // Check if email provider is configured.
        if ( ! $this->email_provider->is_configured() ) {
            return array(
                'success' => false,
                'message' => __( 'Email provider is not configured. Please contact your administrator.', 'guard-dog' )
            );
        }

        // Generate verification code.
        $code = $this->generate_verification_code();
        
        // Store code with expiration (10 minutes).
        $codes = array(
            'code' => $code,
            'expires' => time() + (10 * MINUTE_IN_SECONDS),
            'attempts' => 0
        );
        
        update_user_meta($user_id, self::USER_META_CODES_KEY, $codes);

        // Prepare email content using templates
        $site_name = get_bloginfo('name');

        $subject = null;
        if ( class_exists( 'Guard_Dog_Email_Template_Customizer' ) ) {
            $customizer = new Guard_Dog_Email_Template_Customizer();
            $subject    = $customizer->get_email_subject( array( 'user' => $user, 'site_name' => $site_name, 'name' => $user->display_name ) );
        }
        if ( $subject === null || $subject === '' ) {
            // Translators: %s is the site name.
            $subject = sprintf( __( '[%s] Two-Factor Authentication Code', 'guard-dog' ), $site_name );
        }

        // Template variables
        $template_args = array(
            'code' => $code,
            'user' => $user,
            'site_name' => $site_name,
            'expiry_minutes' => 10
        );

        // Allow themes/plugins to modify template variables
        $template_args = apply_filters('guard_dog_email_2fa_template_args', $template_args, $user_id);

        // Load HTML template (supports theme overrides)
        $message = Guard_Dog_View_Loader::load_email_template('two-factor-code', $template_args);

        // Load plain text template (supports theme overrides)
        $text_message = Guard_Dog_View_Loader::load_email_template('two-factor-code-plain', $template_args);

        // Fallback to simple text if templates fail to load
        if (empty($message)) {
            $message = sprintf(
                '<p>%s</p><p><strong>%s</strong></p><p>%s</p><p>%s</p>',
                // Translators: %s is the user's display name.
                sprintf(esc_html__('Hello %s,', 'guard-dog'), esc_html($user->display_name)),
                __('Your verification code is:', 'guard-dog'),
                '<strong>' . esc_html($code) . '</strong>',
                esc_html__('This code will expire in 10 minutes. If you did not request this code, please ignore this email.', 'guard-dog')
            );
        }

        if (empty($text_message)) {
            $text_message = sprintf(
                "%s\n\n%s\n\n%s\n\n%s",
                // Translators: %s is the user's display name.
                sprintf(esc_html__('Hello %s,', 'guard-dog'), esc_html($user->display_name)),
                __('Your verification code is:', 'guard-dog'),
                $code,
                esc_html__('This code will expire in 10 minutes. If you did not request this code, please ignore this email.', 'guard-dog')
            );
        }

        // Send email
        $result = $this->email_provider->send_email($user->user_email, $subject, $message, $text_message);

        if ($result['success']) {
            // Log the event.
            if ( $this->activity_log ) {
                $this->activity_log->add_log_entry( 'email_2fa_code_sent', array(
                    'user_id' => $user_id,
                    'username' => $user->user_login,
                    'email' => $user->user_email
                ) );
            }

            return array(
                'success' => true,
                'message' => __( 'Verification code sent to your email address.', 'guard-dog' )
            );
        } else {
            return $result;
        }
    }

    /**
     * Verify email verification code
     *
     * @param int $user_id User ID
     * @param string $code Verification code
     * @return array Result array with 'success' boolean and 'message' string
     */
    public function verify_code($user_id, $code) {
        $user = get_user_by('ID', $user_id);
        if (!$user) {
            return [
                'success' => false,
                'message' => __('Invalid user.', 'guard-dog')
            ];
        }

        $stored_codes = get_user_meta($user_id, self::USER_META_CODES_KEY, true);
        if (empty($stored_codes) || !is_array($stored_codes)) {
            return [
                'success' => false,
                'message' => __('No verification code found. Please request a new code.', 'guard-dog')
            ];
        }

        // Check if code has expired
        if (time() > $stored_codes['expires']) {
            delete_user_meta($user_id, self::USER_META_CODES_KEY);
            return [
                'success' => false,
                'message' => __('Verification code has expired. Please request a new code.', 'guard-dog')
            ];
        }

        // Check attempts (max 3 attempts)
        if ($stored_codes['attempts'] >= 3) {
            delete_user_meta($user_id, self::USER_META_CODES_KEY);
            return [
                'success' => false,
                'message' => __('Too many failed attempts. Please request a new code.', 'guard-dog')
            ];
        }

        // Verify code
        if ($stored_codes['code'] === $code) {
            // Success - remove the code
            delete_user_meta($user_id, self::USER_META_CODES_KEY);

            // Log successful verification
            if ($this->activity_log) {
                $this->activity_log->add_log_entry('email_2fa_verified', [
                    'user_id' => $user_id,
                    'username' => $user->user_login,
                    'email' => $user->user_email
                ]);
            }

            return [
                'success' => true,
                'message' => __('Verification successful.', 'guard-dog')
            ];
        } else {
            // Increment attempts
            $stored_codes['attempts']++;
            update_user_meta($user_id, self::USER_META_CODES_KEY, $stored_codes);

            // Log failed attempt
            if ($this->activity_log) {
                $this->activity_log->add_log_entry('email_2fa_failed', [
                    'user_id' => $user_id,
                    'username' => $user->user_login,
                    'email' => $user->user_email,
                    'attempts' => $stored_codes['attempts']
                ]);
            }

            return [
                'success' => false,
                'message' => __('Invalid verification code. Please try again.', 'guard-dog')
            ];
        }
    }

    /**
     * AJAX handler to send verification code
     */
    public function ajax_send_verification_code() {
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('AJAX send email 2FA code - LOGIN CONTEXT', 'email_2fa', [
                'user_logged_in' => is_user_logged_in(),
                'current_user_id' => get_current_user_id(),
                'post_user_id' => isset($_POST['user_id']) ? sanitize_text_field(wp_unslash($_POST['user_id'])) : 'not_set',
                'relevant_post_keys' => $this->get_relevant_email_2fa_post_keys()
            ]);
        }

        // For login context, user might not be fully logged in yet
        // Check if this is being called during 2FA login process
        $user_id = isset($_POST['user_id']) ? absint(sanitize_text_field(wp_unslash($_POST['user_id']))) : 0;
        
        // Check if this is a login context by looking for the 2FA login nonce
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        $is_login_context = !empty($nonce) && wp_verify_nonce($nonce, 'guard_dog_verify_2fa_login_' . $user_id);
        
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Email 2FA context detection', 'email_2fa', array(
                'user_logged_in' => is_user_logged_in(),
                'user_id' => $user_id,
                'nonce_provided' => !empty($nonce),
                'is_login_context' => $is_login_context,
                'expected_login_action' => 'guard_dog_verify_2fa_login_' . $user_id
            ));
        }

        if (!$is_login_context && !is_user_logged_in()) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('User not logged in and not login context', 'email_2fa');
            }
            wp_send_json_error(array('message' => __('You must be logged in to use this feature.', 'guard-dog')), 403);
        }

        // Security checks - for login context, we can't compare with current_user_id
        if (!$is_login_context && $user_id !== get_current_user_id()) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Permission denied: user_id mismatch', 'email_2fa');
            }
            wp_send_json_error(array('message' => __('Permission denied.', 'guard-dog')), 403);
        }

        // For login context, nonce is already verified above
        if (!$is_login_context) {
            // Profile context - use the send code nonce
            $expected_action = 'guard_dog_send_email_2fa_code_' . $user_id;
            $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
            
            if (!wp_verify_nonce($nonce, $expected_action)) {
                if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                    Guard_Dog()->debug->error('Profile context nonce verification failed', 'email_2fa');
                }
                wp_send_json_error(array('message' => __('Security verification failed.', 'guard-dog')), 403);
            }
        }

        // Check if email 2FA is enabled
        if (!$this->is_email_2fa_enabled_for_user($user_id)) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Email 2FA not enabled for user', 'email_2fa', array('user_id' => $user_id));
            }
            wp_send_json_error(array('message' => __('Email two-factor authentication is not enabled.', 'guard-dog')), 400);
        }

        // Send verification code
        $result = $this->send_verification_code($user_id);

        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Send verification code result', 'email_2fa', [
                'success' => $result['success'],
                'user_id' => $user_id
            ]);
        }

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result, 400);
        }
    }

    /**
     * AJAX handler to verify email code
     */
    public function ajax_verify_email_code() {
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('ajax_verify_email_code called', 'email_2fa', [
                'user_logged_in' => is_user_logged_in(),
                'relevant_post_keys' => $this->get_relevant_email_2fa_post_keys(),
                'current_user_id' => get_current_user_id()
            ]);
        }

        // Check if user is logged in
        if (!is_user_logged_in()) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('User not logged in', 'email_2fa');
            }
            wp_send_json_error(array('message' => __('You must be logged in to use this feature.', 'guard-dog')), 403);
        }

        $user_id = isset($_POST['user_id']) ? absint(sanitize_text_field(wp_unslash($_POST['user_id']))) : 0;
        $code = isset($_POST['code']) ? sanitize_text_field(wp_unslash($_POST['code'])) : '';

        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Processing verification', 'email_2fa', [
                'user_id' => $user_id,
                'code_length' => strlen($code)
            ]);
        }

        // Security checks
        if ($user_id !== get_current_user_id()) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Permission denied: user_id mismatch', 'email_2fa', [
                    'requested_user_id' => $user_id,
                    'current_user_id' => get_current_user_id()
                ]);
            }
            wp_send_json_error(array('message' => __('Permission denied.', 'guard-dog')), 403);
        }

        // Verify nonce
        $expected_action = 'guard_dog_verify_email_2fa_code_' . $user_id;
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Nonce verification', 'email_2fa', [
                'expected_action' => $expected_action,
                'nonce_received' => !empty($nonce)
            ]);
        }
        
        if (!wp_verify_nonce($nonce, $expected_action)) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Nonce verification failed', 'email_2fa');
            }
            wp_send_json_error(array('message' => __('Security verification failed.', 'guard-dog')), 403);
        }

        // Validate code format
        if (empty($code) || !ctype_digit($code) || strlen($code) !== 6) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Invalid code format', 'email_2fa', [
                    'code_empty' => empty($code),
                    'code_numeric' => !empty($code) ? ctype_digit($code) : false,
                    'code_length' => strlen($code)
                ]);
            }
            wp_send_json_error(array('message' => __('Please enter a valid 6-digit code.', 'guard-dog')), 400);
        }

        // Verify code
        $result = $this->verify_code($user_id, $code);
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Code verification result', 'email_2fa', [
                'success' => $result['success'],
                'message' => $result['message']
            ]);
        }

        if ($result['success']) {
            // Enable email 2FA for the user
            update_user_meta($user_id, self::USER_META_ENABLED_KEY, true);

            // Log the event
            if ($this->activity_log) {
                $user = get_user_by('ID', $user_id);
                $this->activity_log->add_log_entry('email_2fa_enabled', [
                    'user_id' => $user_id,
                    'username' => $user->user_login,
                    'email' => $user->user_email
                ]);
            }

            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->info('Successfully enabled Email 2FA', 'email_2fa', array('user_id' => $user_id));
            }
            wp_send_json_success([
                'message' => __('Email two-factor authentication enabled successfully!', 'guard-dog')
            ]);
        } else {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Verification failed', 'email_2fa', array('reason' => $result['message']));
            }
            wp_send_json_error($result, 400);
        }
    }

    /**
     * AJAX handler to enable email 2FA
     */
    public function ajax_enable_email_2fa() {
        // Debug logging for request start
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Email 2FA Enable request started', 'email_2fa', [
                'timestamp' => current_time('mysql'),
                'memory_usage' => memory_get_usage(true),
                'memory_limit' => ini_get('memory_limit'),
                'max_execution_time' => ini_get('max_execution_time'),
                'user_logged_in' => is_user_logged_in(),
                'current_user_id' => get_current_user_id()
            ]);
        }
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('User not logged in', 'email_2fa');
            }
            wp_send_json_error(array('message' => __('You must be logged in to use this feature.', 'guard-dog')), 403);
        }

        $user_id = isset($_POST['user_id']) ? absint(sanitize_text_field(wp_unslash($_POST['user_id']))) : 0;
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Enable request', 'email_2fa', array('user_id' => $user_id));
        }

        // Security checks
        if ($user_id !== get_current_user_id()) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Permission denied: user_id mismatch', 'email_2fa', [
                    'requested_user_id' => $user_id,
                    'current_user_id' => get_current_user_id()
                ]);
            }
            wp_send_json_error(array('message' => __('Permission denied.', 'guard-dog')), 403);
        }

        // Verify nonce
        $expected_action = 'guard_dog_enable_email_2fa_' . $user_id;
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        
        // Debug logging for nonce verification
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Email 2FA Enable nonce verification', 'email_2fa', [
                'user_id' => $user_id,
                'expected_action' => $expected_action,
                'nonce_length' => strlen($nonce),
                'has_wpnonce' => isset($_POST['_wpnonce']),
                'has_nonce' => isset($_POST['nonce']),
                'relevant_post_keys' => $this->get_relevant_email_2fa_post_keys()
            ]);
        }
        
        if (!wp_verify_nonce($nonce, $expected_action)) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Email 2FA Enable nonce verification failed', 'email_2fa', [
                    'user_id' => $user_id,
                    'expected_action' => $expected_action,
                    'nonce_length' => strlen($nonce),
                    'verify_result' => false
                ]);
            }
            wp_send_json_error(array('message' => __('Security verification failed.', 'guard-dog')), 403);
        }

        // Check if email provider is configured
        if (!$this->email_provider->is_configured()) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Email provider not configured', 'email_2fa');
            }
            wp_send_json_error(array('message' => __('Email provider is not configured. Please contact your administrator.', 'guard-dog')), 400);
        }

        // Send verification code to user's email
        $result = $this->send_verification_code($user_id);
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Send verification code result', 'email_2fa', [
                'success' => $result['success'],
                'message' => $result['message']
            ]);
        }
        
        if (!$result['success']) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Failed to send verification code', 'email_2fa', array('reason' => $result['message']));
            }
            wp_send_json_error(array('message' => $result['message']), 400);
        }

        // Debug logging for successful enable
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Email 2FA Enable request completed successfully', 'email_2fa', [
                'timestamp' => current_time('mysql'),
                'memory_usage' => memory_get_usage(true),
                'verification_code_sent' => true,
                'user_email' => $user->user_email
            ]);
        }
        
        wp_send_json_success([
            'message' => __('Verification code sent to your email. Please check your email and enter the code to complete setup.', 'guard-dog'),
            'requires_verification' => true
        ]);
    }

    /**
     * AJAX handler to disable email 2FA
     */
    public function ajax_disable_email_2fa() {
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => __('You must be logged in to use this feature.', 'guard-dog')), 403);
        }

        // Get current user ID first (no POST data access needed)
        $current_user_id = get_current_user_id();
        $expected_action = 'guard_dog_disable_email_2fa_' . $current_user_id;
        
        // Verify nonce first before processing any POST data
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        
        if (!wp_verify_nonce($nonce, $expected_action)) {
            wp_send_json_error(array('message' => __('Security verification failed.', 'guard-dog')), 403);
        }

        // Now safe to access POST data after nonce validation
        $user_id = isset($_POST['user_id']) ? absint(sanitize_text_field(wp_unslash($_POST['user_id']))) : 0;

        // Security checks
        if ($user_id !== $current_user_id) {
            wp_send_json_error(array('message' => __('Permission denied.', 'guard-dog')), 403);
        }

        // Disable email 2FA
        delete_user_meta($user_id, self::USER_META_ENABLED_KEY);
        delete_user_meta($user_id, self::USER_META_CODES_KEY);

        // Log the event
        if ($this->activity_log) {
            $user = get_user_by('ID', $user_id);
            $this->activity_log->add_log_entry('email_2fa_disabled', [
                'user_id' => $user_id,
                'username' => $user->user_login,
                'email' => $user->user_email
            ]);
        }

        wp_send_json_success([
            'message' => __('Email two-factor authentication disabled successfully.', 'guard-dog')
        ]);
    }

    /**
     * AJAX handler to refresh email 2FA nonces.
     *
     * @since 1.8.1
     */
    public function ajax_refresh_email_2fa_nonces() {
        // Check if user is logged in first
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => __('You must be logged in to use this feature.', 'guard-dog')), 403);
        }

        $user_id = get_current_user_id();
        
        // Use WordPress standard AJAX nonce verification
        $expected_action = 'guard_dog_disable_email_2fa_' . $user_id; // Reuse existing nonce
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        
        if (!wp_verify_nonce($nonce, $expected_action)) {
            wp_send_json_error(array('message' => __('Security verification failed.', 'guard-dog')), 403);
        }

        // Generate fresh nonces with keys that match the JavaScript expectations
        $nonces = [
            'emailEnable' => wp_create_nonce('guard_dog_enable_email_2fa_' . $user_id),
            'emailVerify' => wp_create_nonce('guard_dog_verify_email_2fa_code_' . $user_id),
            'emailSendCode' => wp_create_nonce('guard_dog_send_email_2fa_code_' . $user_id),
            'emailDisable' => wp_create_nonce('guard_dog_disable_email_2fa_' . $user_id),
        ];

        wp_send_json_success([
            'message' => __('Nonces refreshed successfully.', 'guard-dog'),
            'nonces' => $nonces
        ]);
    }



    /**
     * Save user profile settings
     *
     * @param int $user_id User ID
     */
    public function save_user_profile_settings($user_id) {
        // Check permissions
        if (!current_user_can('edit_user', $user_id)) {
            return;
        }

        // Handle email 2FA disable form submission
        if (isset($_POST['guard_dog_disable_email_2fa']) && isset($_POST['guard_dog_disable_email_2fa_nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['guard_dog_disable_email_2fa_nonce'])), 'guard_dog_disable_email_2fa_' . $user_id)) {
                return;
            }

            // Delete the meta keys to disable
            delete_user_meta($user_id, self::USER_META_ENABLED_KEY);
            delete_user_meta($user_id, self::USER_META_CODES_KEY);

            // Add success notice
            add_action('admin_notices', function() {
                add_settings_error(
                    'guard_dog_email_2fa',
                    'email_2fa_disabled',
                    __('Email Two-Factor Authentication has been disabled.', 'guard-dog'),
                    'success'
                );
            });
        }
    }

    /**
     * Handle shortcode
     *
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public function shortcode_handler($atts) {
        // Only allow logged-in users
        if (!is_user_logged_in()) {
            return '<div class="guard-dog-email-2fa-notice guard-dog-email-2fa-error">' . 
                   esc_html__('You must be logged in to manage email two-factor authentication.', 'guard-dog') . 
                   '</div>';
        }

        // Enqueue CSS and JavaScript assets
        $this->enqueue_shortcode_assets();

        return Guard_Dog_View_Loader::load_partial('shortcode-email-2fa', [
            'atts' => $atts,
            'this' => $this
        ]);
    }

    /**
     * Enqueue profile scripts
     *
     * @param string $hook_suffix Current admin page hook
     */
    public function enqueue_profile_scripts($hook_suffix) {
        // Only load on user profile page
        if ('profile.php' !== $hook_suffix && 'user-edit.php' !== $hook_suffix) {
            return;
        }

        // Check if the current user can setup email 2FA for the displayed user
        $user_id_param = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
        $user_id = $user_id_param ? $user_id_param : get_current_user_id();
        if (get_current_user_id() !== $user_id) {
            return; // Don't load script if viewing someone else's profile
        }

        // Enqueue the script
        wp_enqueue_script(
            'guard-dog-profile-email-2fa',
            GUARD_DOG_URL . 'assets/js/guard-dog-profile-email-2fa.js',
            ['jquery'],
            GUARD_DOG_VERSION,
            true
        );

        // Pass data to the script
        $user_id = get_current_user_id();
        wp_localize_script('guard-dog-profile-email-2fa', 'guard_dog_email_2fa', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonces' => [
                'verifyCode' => wp_create_nonce('guard_dog_verify_email_2fa_code_' . $user_id),
                'disable' => wp_create_nonce('guard_dog_disable_email_2fa_' . $user_id),
            ],
            'strings' => [
                'sending' => esc_html__('Sending...', 'guard-dog'),
                'enable_button' => esc_html__('Enable Email 2FA', 'guard-dog'),
                'ajax_error' => esc_html__('AJAX Error', 'guard-dog'),
                'confirm_disable' => esc_html__('Are you sure you want to disable email two-factor authentication?', 'guard-dog')
            ]
        ]);
    }

    /**
     * Safely get action parameter for script enqueuing
     * This is used for display-only purposes to determine if scripts should be enqueued
     *
     * @return string|null The action parameter or null if not found
     */
    /**
     * Get relevant POST keys for email 2FA debug logging (only email 2FA-specific fields)
     *
     * @return array Array of relevant POST keys
     */
    private function get_relevant_email_2fa_post_keys(): array {
        $relevant_keys = [];
        $expected_keys = ['_wpnonce', 'nonce', 'user_id', 'guard_dog_email_2fa_code', 'action'];
        
        foreach ($expected_keys as $key) {
            if (isset($_POST[$key])) {
                $relevant_keys[] = $key;
            }
        }
        
        return $relevant_keys;
    }

    private function get_safe_action_parameter(): ?string {
        // Check GET parameter first
        if (isset($_GET['action'])) {
            return sanitize_text_field(wp_unslash($_GET['action']));
        }
        
        // Check POST parameter if GET is not available
        if (isset($_POST['action'])) {
            return sanitize_text_field(wp_unslash($_POST['action']));
        }
        
        return null;
    }

    /**
     * Enqueue login scripts
     */
    public function enqueue_login_scripts($user_id = 0) {
        // Only enqueue if we're on the 2FA login page
        $local_action = $this->get_safe_action_parameter();
        
        // Also check global $action variable set by main 2FA class
        global $action;
        $current_action = $action ?? $local_action;
        
        if ($current_action !== 'guard_dog_2fa') {
            return;
        }

        wp_enqueue_script('jquery');
        wp_enqueue_style('guard-dog-login-2fa', GUARD_DOG_URL . 'assets/css/guard-dog-login-2fa.css', [], GUARD_DOG_VERSION);
        wp_enqueue_script('guard-dog-login-2fa', GUARD_DOG_URL . 'assets/js/guard-dog-login-2fa.js', ['jquery'], GUARD_DOG_VERSION, true);
        
        // Localize script with AJAX URL and other necessary data
        wp_localize_script('guard-dog-login-2fa', 'guard_dog_login_2fa', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'userId' => $user_id,
            'strings' => [
                'sending' => __('Sending...', 'guard-dog'),
                'codeSent' => __('Code sent! Check your email.', 'guard-dog'),
                'error' => __('Error sending code. Please try again.', 'guard-dog'),
                'networkError' => __('Network error. Please try again.', 'guard-dog'),
            ]
        ]);
    }

    /**
     * Enqueue shortcode assets
     */
    private function enqueue_shortcode_assets() {
        // Only enqueue once per page
        static $assets_enqueued = false;
        if ($assets_enqueued) {
            return;
        }
        $assets_enqueued = true;

        // Enqueue CSS
        wp_enqueue_style(
            'guard-dog-shortcode-email-2fa',
            GUARD_DOG_URL . 'assets/css/guard-dog-shortcode-email-2fa.css',
            [],
            GUARD_DOG_VERSION
        );

        // Enqueue JavaScript
        wp_enqueue_script(
            'guard-dog-shortcode-email-2fa',
            GUARD_DOG_URL . 'assets/js/guard-dog-shortcode-email-2fa.js',
            ['jquery'],
            GUARD_DOG_VERSION,
            true
        );

        // Localize script with AJAX URL and other data
        $user_id = get_current_user_id();
        wp_localize_script('guard-dog-shortcode-email-2fa', 'guard_dog_email_2fa_shortcode', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'userId' => $user_id,
            'nonces' => [
                'sendCode' => wp_create_nonce('guard_dog_send_email_2fa_code_' . $user_id),
                'verifyCode' => wp_create_nonce('guard_dog_verify_email_2fa_code_' . $user_id),
                'enable' => wp_create_nonce('guard_dog_enable_email_2fa_' . $user_id),
                'disable' => wp_create_nonce('guard_dog_disable_email_2fa_' . $user_id),
            ],
            'strings' => [
                'loading' => __('Loading...', 'guard-dog'),
                'error' => __('An error occurred.', 'guard-dog'),
                'networkError' => __('Network error. Please try again.', 'guard-dog'),
                'confirmDisable' => __('Are you sure you want to disable email two-factor authentication?', 'guard-dog'),
            ]
        ]);

        // Debug logging for nonce creation
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Email 2FA Shortcode nonces created', 'email_2fa', [
                'user_id' => $user_id,
                'nonce_actions' => [
                    'sendCode' => 'guard_dog_send_email_2fa_code_' . $user_id,
                    'verifyCode' => 'guard_dog_verify_email_2fa_code_' . $user_id,
                    'enable' => 'guard_dog_enable_email_2fa_' . $user_id,
                    'disable' => 'guard_dog_disable_email_2fa_' . $user_id,
                ],
                'nonce_lengths' => [
                    'sendCode' => strlen(wp_create_nonce('guard_dog_send_email_2fa_code_' . $user_id)),
                    'verifyCode' => strlen(wp_create_nonce('guard_dog_verify_email_2fa_code_' . $user_id)),
                    'enable' => strlen(wp_create_nonce('guard_dog_enable_email_2fa_' . $user_id)),
                    'disable' => strlen(wp_create_nonce('guard_dog_disable_email_2fa_' . $user_id)),
                ]
            ]);
        }
    }

    /**
     * Get email 2FA status for a user
     *
     * @param int|WP_User|string $user User ID, user object, username, or email
     * @return array Status information
     */
    public function get_user_email_2fa_status($user) {
        $user_id = $this->get_user_id($user);
        $user_obj = null;

        if (is_numeric($user)) {
            $user_id = absint($user);
            $user_obj = get_user_by('id', $user_id);
        } elseif ($user instanceof WP_User) {
            $user_id = $user->ID;
            $user_obj = $user;
        } elseif (is_string($user)) {
            if (is_email($user)) {
                $user_obj = get_user_by('email', sanitize_email($user));
            } else {
                $user_obj = get_user_by('login', sanitize_user($user));
            }
            
            if ($user_obj && !is_wp_error($user_obj)) {
                $user_id = $user_obj->ID;
            }
        }

        if ($user_id <= 0 || !$user_obj) {
            return [
                'enabled' => false,
                'user_exists' => false,
                'user_id' => 0
            ];
        }

        $is_enabled = (bool) get_user_meta($user_id, self::USER_META_ENABLED_KEY, true);

        return [
            'enabled' => $is_enabled,
            'user_exists' => true,
            'user_id' => $user_id,
            'username' => $user_obj->user_login,
            'email' => $user_obj->user_email
        ];
    }
}
