<?php
if (!defined('ABSPATH')) exit;

class WP2FA_Login_Handler {

    public static function init() {
        error_log('WP2FA_Login_Handler INIT');
        add_action('login_form', [__CLASS__, 'render_login_fields']);
        add_filter('authenticate', [__CLASS__, 'handle_authentication'], 30, 3);
    }

    public static function render_login_fields() {
        error_log("2FA DEBUG - Ejecutando render_login_fields");
    
        $username = isset($_POST['log']) ? sanitize_user($_POST['log']) : '';
        $method = '';
        $is_premium = defined('WP2FA_PREMIUM') && WP2FA_PREMIUM === true && WP2FA_License_Manager::is_premium_active();
    
        if (!empty($username)) {
            $user = get_user_by('login', $username);
            if (!$user && is_email($username)) {
                $user = get_user_by('email', $username);
            }
    
            if ($user) {
                $method = get_user_meta($user->ID, 'wp_2fa_method', true);
                if (empty($method)) {
                    $method = get_option('wp2fa_auth_method', 'totp');
                }
                error_log("2FA DEBUG - Método por usuario '{$username}': {$method}");
            } else {
                error_log("2FA DEBUG - No se encontró el usuario con login o email '{$username}'");
            }
        }
    
        if (empty($method)) {
            $method = get_option('wp2fa_auth_method', 'totp');
            error_log("2FA DEBUG - Método 2FA global (fallback): {$method}");
        }
    
        // Mostrar campo TOTP si corresponde
        if ($method === 'totp' || ($method === 'both' && $is_premium)) {
            error_log("2FA DEBUG - Mostrando campo TOTP");
            echo '<p><label for="2fa_code">Código 2FA (TOTP)<br>';
            echo '<input type="text" name="2fa_code" id="2fa_code" class="input" value="" size="20" autofocus></label></p>';
        }
    
        // Mostrar campo Email si corresponde
        if ($is_premium && ($method === 'email' || $method === 'both')) {
            error_log("2FA DEBUG - Mostrando campo Email");
            echo '<p><label for="2fa_email_code">Código 2FA (Email)<br>';
            echo '<input type="text" name="2fa_email_code" id="2fa_email_code" class="input" value="" size="20"></label></p>';
    
            // Botón AJAX para enviar código si el método es 'email' o 'both'
            echo '<p><button type="button" class="button button-secondary" id="send_2fa_email_code">Enviar código por correo</button></p>';
    
            echo '<script>
                document.getElementById("send_2fa_email_code").addEventListener("click", function() {
                    const xhr = new XMLHttpRequest();
                    xhr.open("POST", ajaxurl, true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    const data = new URLSearchParams();
                    data.append("action", "send_2fa_email_code_ajax");
                    data.append("username", document.getElementById("user_login").value);
    
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                if (response.success) {
                                    alert("Código enviado exitosamente.");
                                } else {
                                    alert(response.data || "Error al enviar el código 2FA por correo.");
                                }
                            } catch (e) {
                                alert("Respuesta inesperada del servidor.");
                            }
                        } else {
                            alert("Error en la solicitud AJAX.");
                        }
                    };
    
                    xhr.send(data);
                });
            </script>';
        }
    }    
    

//No borrar este funciona correctamente con BOTH
/*     public static function render_login_fields() {
        error_log("2FA DEBUG - Ejecutando render_login_fields");
    
        $username = isset($_POST['log']) ? sanitize_user($_POST['log']) : '';
        $method = '';
        $is_premium = defined('WP2FA_PREMIUM') && WP2FA_PREMIUM === true && WP2FA_License_Manager::is_premium_active();
    
        if (!empty($username)) {
            $user = get_user_by('login', $username);
            if (!$user && is_email($username)) {
                $user = get_user_by('email', $username);
            }
    
            if ($user) {
                $method = get_user_meta($user->ID, 'wp_2fa_method', true);
                if (empty($method)) {
                    $method = get_option('wp2fa_auth_method', 'totp');
                }
                error_log("2FA DEBUG - Método por usuario '{$username}': {$method}");
            } else {
                error_log("2FA DEBUG - No se encontró el usuario con login o email '{$username}'");
            }
        }
    
        if (empty($method)) {
            $method = get_option('wp2fa_auth_method', 'totp');
            error_log("2FA DEBUG - Método 2FA global (fallback): {$method}");
        }
    
        if ($method === 'totp' || ($method === 'both' && $is_premium)) {
            error_log("2FA DEBUG - Mostrando campo TOTP");
            echo '<p><label for="2fa_code">Código 2FA (TOTP)<br>';
            echo '<input type="text" name="2fa_code" id="2fa_code" class="input" value="" size="20"></label></p>';
        }
    
        if ($is_premium && ($method === 'email' || $method === 'both')) {
            error_log("2FA DEBUG - Mostrando campo Email");
            echo '<p><label for="2fa_email_code">Código 2FA (Email)<br>';
            echo '<input type="text" name="2fa_email_code" id="2fa_email_code" class="input" value="" size="20"></label></p>';
            echo '<p><button type="button" class="button button-secondary" id="send_2fa_email_code">Enviar código por correo</button></p>';
            echo '<script>
                document.getElementById("send_2fa_email_code").addEventListener("click", function() {
                    const xhr = new XMLHttpRequest();
                    xhr.open("POST", ajaxurl, true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    const data = new URLSearchParams();
                    data.append("action", "send_2fa_email_code_ajax");
                    data.append("username", document.getElementById("user_login").value);
    
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            alert(xhr.responseText);
                        } else {
                            alert("Error al enviar el código 2FA por correo.");
                        }
                    };
    
                    xhr.send(data);
                });
            </script>';
        }
    } */    


    //este render login fields si sirve
/*     public static function render_login_fields() {
        error_log("2FA DEBUG - Ejecutando render_login_fields");
    
        $username = isset($_POST['log']) ? sanitize_user($_POST['log']) : '';
        $method = '';
        $is_premium = defined('WP2FA_PREMIUM') && WP2FA_PREMIUM === true && WP2FA_License_Manager::is_premium_active();

        if (!empty($username)) {
            $user = get_user_by('login', $username);
            if (!$user && is_email($username)) {
                $user = get_user_by('email', $username);
            }
        
            if ($user) {
                $method = get_user_meta($user->ID, 'wp_2fa_method', true);
                if (empty($method)) {
                    $method = get_option('wp2fa_auth_method', 'totp');
                }
                error_log("2FA DEBUG - Método por usuario '{$username}': {$method}");
            } else {
                error_log("2FA DEBUG - No se encontró el usuario con login o email '{$username}'");
            }
        }
        
        if (empty($method)) {
            $method = get_option('wp2fa_auth_method', 'totp');
            error_log("2FA DEBUG - Método 2FA global (fallback): {$method}");
        }
    
        if ($method === 'totp' || ($method === 'both' && $is_premium)) {
            error_log("2FA DEBUG - Mostrando campo TOTP");
            echo '<p><label for="2fa_code">Código 2FA (TOTP)<br>';
            echo '<input type="text" name="2fa_code" id="2fa_code" class="input" value="" size="20"></label></p>';
        }
    
        if ($is_premium && ($method === 'email' || $method === 'both')) {
            error_log("2FA DEBUG - Mostrando campo Email");
            echo '<p><label for="2fa_email_code">Código 2FA (Email)<br>';
            echo '<input type="text" name="2fa_email_code" id="2fa_email_code" class="input" value="" size="20"></label></p>';
        }
    } */
        
    

/*     public static function render_login_fields() {
        error_log("2FA DEBUG - Ejecutando render_login_fields");

        $username = isset($_POST['log']) ? sanitize_user($_POST['log']) : '';
        $method = '';

        if ($username) {
            $user = get_user_by('login', $username);
            if ($user) {
                $method = get_user_meta($user->ID, 'wp_2fa_method', true);
                if (empty($method)) {
                    $method = get_option('wp2fa_auth_method', 'totp');
                    update_user_meta($user->ID, 'wp_2fa_method', $method);
                }
                // 🔒 Reforzar método si no es premium
                $is_premium = defined('WP2FA_PREMIUM') && WP2FA_PREMIUM === true && WP2FA_License_Manager::is_premium_active();
                if (!$is_premium && $method !== 'totp') {
                    $method = 'totp'; // Forzamos el método a TOTP
                }

                error_log("2FA DEBUG - Método 2FA por usuario: " . $method);
            }
        }

        if (empty($method)) {
            $method = get_option('wp2fa_auth_method', 'totp');
            error_log("2FA DEBUG - Método 2FA global: " . $method);
        }

        if ($method === 'totp' || $method === 'both') {
            echo '<p><label for="2fa_code">Código 2FA (TOTP)<br>';
            echo '<input type="text" name="2fa_code" id="2fa_code" class="input" value="" size="20"></label></p>';
        }

        if ((defined('WP2FA_PREMIUM') && WP2FA_PREMIUM === true) && ($method === 'email' || $method === 'both')) {
            echo '<p><label for="2fa_email_code">Código 2FA (Email)<br>';
            echo '<input type="text" name="2fa_email_code" id="2fa_email_code" class="input" value="" size="20"></label></p>';
        }
    } */

    public static function handle_authentication($user, $username, $password) {
        if (is_wp_error($user)) return $user;
    
        $method = get_user_meta($user->ID, 'wp_2fa_method', true);
        $is_premium = defined('WP2FA_PREMIUM') && WP2FA_PREMIUM === true && WP2FA_License_Manager::is_premium_active();
    
        // DEBUG
        error_log("2FA DEBUG - Método guardado para el usuario {$user->user_login}: {$method}");
        error_log("2FA DEBUG - handle_authentication() usando método: " . $method);
    
        if (empty($method)) {
            $method = get_option('wp2fa_auth_method', 'totp');
            update_user_meta($user->ID, 'wp_2fa_method', $method);
            error_log("2FA DEBUG - Método no definido, usando el global: {$method}");
        }
    
        if (!$is_premium && $method !== 'totp') {
            error_log("2FA DEBUG - No hay licencia premium, forzando a TOTP.");
            $method = 'totp';
            update_user_meta($user->ID, 'wp_2fa_method', 'totp');
        }
    
        // Variables de entrada
        $totp_entered = isset($_POST['2fa_code']) && !empty($_POST['2fa_code']);
        $email_entered = isset($_POST['2fa_email_code']) && !empty($_POST['2fa_email_code']);
    
        if (!$is_premium && ($method === 'email' || $method === 'both')) {
            error_log("2FA WARNING - Usuario {$username} tenía método '{$method}' pero no tiene licencia válida. Se forzará a 'totp'.");
            $method = 'totp';
            update_user_meta($user->ID, 'wp_2fa_method', $method);
        }
    
        // === EMAIL ===
        if ($method === 'email') {
            if (!$email_entered) {
                return new WP_Error('2fa_email_required', 'Falta el código 2FA por correo.');
            }
            $result = WP2FA_Email_Auth::validate_email_code($user);
            if (is_wp_error($result)) return $result;
    
            error_log("2FA DEBUG - Usuario autenticado correctamente vía email.");
    
            delete_transient('wp_2fa_email_sent_' . $user->ID);
            delete_user_meta($user->ID, 'wp_2fa_email_code');
    
            return $user; // NO REDIRECCIÓN MANUAL AQUÍ
        }
    
        // === BOTH ===
        if ($method === 'both' && $is_premium) {
            if (!$totp_entered) {
                return new WP_Error('2fa_totp_required', 'Falta el código 2FA (TOTP).');
            }
            if (!$email_entered) {
                return new WP_Error('2fa_email_required', 'Falta el código 2FA por correo.');
            }
    
            $totp_result = WP2FA_TOTP::validate_2fa_code($user, $username, $password);
            if (is_wp_error($totp_result)) {
                error_log("2FA DEBUG - Validación TOTP fallida: " . $totp_result->get_error_message());
                return $totp_result;
            }
    
            $email_result = WP2FA_Email_Auth::validate_email_code($user);
            if (is_wp_error($email_result)) {
                error_log("2FA DEBUG - Validación Email fallida: " . $email_result->get_error_message());
                return $email_result;
            }
    
            error_log("2FA DEBUG - Usuario autenticado correctamente vía BOTH.");
    
            delete_transient('wp_2fa_email_sent_' . $user->ID);
            delete_user_meta($user->ID, 'wp_2fa_email_code');
    
            return $user; // NO REDIRECCIÓN MANUAL AQUÍ
        }
    
        // === TOTP ===
        if ($method === 'totp') {
            if (!$totp_entered) {
                return new WP_Error('2fa_totp_required', 'Falta el código 2FA (TOTP).');
            }
    
            $totp_result = WP2FA_TOTP::validate_2fa_code($user, $username, $password);
            if (is_wp_error($totp_result)) {
                error_log("2FA DEBUG - Validación TOTP fallida: " . $totp_result->get_error_message());
                return $totp_result;
            }
    
            error_log("2FA DEBUG - Usuario autenticado correctamente vía TOTP.");
        }
    
        delete_transient('wp_2fa_email_sent_' . $user->ID);
        return $user;
    }
       
    
}

WP2FA_Login_Handler::init();
