<?php
// inc/class-backup-codes.php

if (!defined('ABSPATH')) {
    exit;
}

class WP2FA_Backup_Codes {

    public static function init() {
        // Este archivo solo funciona si es premium
        if (!defined('WP2FA_PREMIUM') || WP2FA_PREMIUM !== true) {
            return;
        }

        add_filter('authenticate', [__CLASS__, 'check_backup_code'], 50, 3);
    }

    public static function generate_backup_codes($user_id) {
        $codes = [];
        for ($i = 0; $i < 5; $i++) {
            $codes[] = wp_generate_password(8, false);
        }
        update_user_meta($user_id, 'wp_2fa_backup_codes', $codes);
        return $codes;
    }

    public static function check_backup_code($user, $username, $password) {
        if (is_wp_error($user)) {
            return $user;
        }

        $code = isset($_POST['2fa_code']) ? sanitize_text_field($_POST['2fa_code']) : '';
        if (empty($code)) {
            return $user;
        }

        $codes = get_user_meta($user->ID, 'wp_2fa_backup_codes', true);
        if (!is_array($codes)) {
            return $user;
        }

        if (in_array($code, $codes, true)) {
            // Eliminar el código usado
            $updated_codes = array_diff($codes, [$code]);
            update_user_meta($user->ID, 'wp_2fa_backup_codes', $updated_codes);
            return $user;
        }

        return $user;
    }

    public static function render_backup_codes_section($user_id) {
        $codes = get_user_meta($user_id, 'wp_2fa_backup_codes', true);
        if (!$codes) {
            $codes = self::generate_backup_codes($user_id);
        }

        echo '<h2>' . esc_html__('Códigos de Respaldo', 'wp-2fa-authenticator') . '</h2>';
        echo '<p>' . esc_html__('Estos códigos se pueden usar si pierdes el acceso a tu autenticación 2FA.', 'wp-2fa-authenticator') . '</p>';
        echo '<ul>';
        foreach ($codes as $code) {
            echo '<li>' . esc_html($code) . '</li>';
        }
        echo '</ul>';
    }
}

WP2FA_Backup_Codes::init();
