<?php

/**
 * Kelas untuk fungsi publik
 */
class SecureAuth_Authenticator_2FA_Public {

    /**
     * Tambahkan form 2FA di halaman login
     */
    public function add_2fa_login_form() {
        ?>
        <p>
            <label for="secureauth_authenticator_code">
                <?php esc_html_e('SecureAuth Authenticator Code', 'secureauth-authenticator-2fa'); ?><br />
                <input type="text" name="secureauth_authenticator_code" id="secureauth_authenticator_code" class="input" size="20" autocomplete="off" />
            </label>
        </p>
        <?php
        wp_nonce_field('secureauth_2fa_login_action', 'secureauth_2fa_login_nonce');
    }
    

    /**
     * Verifikasi 2FA saat login
     *
     * @param WP_User|WP_Error $user User object atau error
     * @param string $username Username
     * @param string $password Password
     * @return WP_User|WP_Error
     */
    public function verify_2fa_login($user, $username, $password) {
        if (is_wp_error($user)) {
            return $user;
        }
    
        if ($user instanceof WP_User) {
            $enabled = get_user_meta($user->ID, 'secureauth_authenticator_enabled', true);
    
            if ($enabled === 'yes') {
                // ✅ Verifikasi nonce
                if (
                    !isset($_POST['secureauth_2fa_login_nonce']) ||
                    !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['secureauth_2fa_login_nonce'])), 'secureauth_2fa_login_action')
                ) {
                    return new WP_Error(
                        'secureauth_authenticator_nonce_invalid',
                        __('<strong>ERROR</strong>: Verifikasi keamanan gagal. Silakan coba lagi.', 'secureauth-authenticator-2fa')
                    );
                }
    
                $secret = get_user_meta($user->ID, 'secureauth_authenticator_secret', true);
    
                $code = isset($_POST['secureauth_authenticator_code']) 
                    ? sanitize_text_field(wp_unslash($_POST['secureauth_authenticator_code'])) 
                    : '';
    
                if (empty($code)) {
                    return new WP_Error(
                        'secureauth_authenticator_code_empty',
                        __('<strong>ERROR</strong>: Kode SecureAuth Authenticator diperlukan.', 'secureauth-authenticator-2fa')
                    );
                }
    
                $sa = new SecureAuth_Authenticator();
                if (!$sa->verify_code($secret, $code)) {
                    return new WP_Error(
                        'secureauth_authenticator_code_invalid',
                        __('<strong>ERROR</strong>: Kode SecureAuth Authenticator tidak valid.', 'secureauth-authenticator-2fa')
                    );
                }
            }
        }
    
        return $user;
    }
    
    
}