<?php
// inc/class-totp.php

use OTPHP\TOTP;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;

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

class WP2FA_TOTP {

    public static function init() {
        add_action('admin_menu', [__CLASS__, 'add_settings_menu']);
    }

    public static function add_settings_menu() {
        add_menu_page(
            esc_html__('Autenticación 2FA', 'wp-2fa-authenticator'),
            esc_html__('2FA Settings', 'wp-2fa-authenticator'),
            'read',
            'wp-2fa-settings',
            [__CLASS__, 'settings_page'],
            'dashicons-shield',
            25
        );
    }

    public static function settings_page() {
        $user_id = get_current_user_id();
        $user_secret = get_user_meta($user_id, 'wp_2fa_secret', true);
        $current_user = wp_get_current_user();
        $username = esc_html($current_user->user_login);
        $site_name = esc_html(get_bloginfo('name'));

        echo '<div class="wrap"><h1>' . esc_html__('Configuración de Autenticación 2FA', 'wp-2fa-authenticator') . '</h1>';

        if (!$user_secret && isset($_POST['generate_secret'])) {
            $secret = TOTP::generate()->getSecret();
            update_user_meta($user_id, 'wp_2fa_secret', sanitize_text_field($secret));
            $user_secret = $secret;
        }

        if (!$user_secret) {
            echo '<form method="post"><input type="submit" name="generate_secret" value="' . esc_attr__('Generar Clave Secreta', 'wp-2fa-authenticator') . '" class="button button-primary"></form>';
        } else {
            $totp = TOTP::create($user_secret);
            $totp->setLabel($username);
            $totp->setIssuer($site_name);
            $otp_url = $totp->getProvisioningUri();

            $upload_dir = wp_upload_dir();
            $qr_filename = 'qr-' . $user_id . '.png';
            $qr_path = trailingslashit($upload_dir['basedir']) . $qr_filename;
            $qr_url  = trailingslashit($upload_dir['baseurl']) . $qr_filename;

            $qr = QrCode::create($otp_url);
            $writer = new PngWriter();
            $result = $writer->write($qr);

            if (wp_is_writable(dirname($qr_path))) {
                file_put_contents($qr_path, $result->getString());
            }

            echo '<p>' . esc_html__('Escanea este código QR con Google Authenticator:', 'wp-2fa-authenticator') . '</p>';
            echo '<img src="' . esc_url($qr_url) . '" alt="' . esc_attr__('QR Code', 'wp-2fa-authenticator') . '" style="width:200px;height:200px;"><br>';
            echo '<p>' . esc_html__('O ingresa esta clave manualmente:', 'wp-2fa-authenticator') . ' <strong>' . esc_html($user_secret) . '</strong></p>';
        }

        echo '</div>';
    }

    public static function validate_2fa_code($user, $username, $password) {
        $method = get_user_meta($user->ID, 'wp_2fa_method', true);
        if ($method !== 'totp' && $method !== 'both') {
            return $user;
        }

        $secret = get_user_meta($user->ID, 'wp_2fa_secret', true);
        if (!$secret) {
            return new WP_Error('2fa_missing_secret', __('No hay secreto TOTP configurado.', 'wp-2fa-authenticator'));
        }

        $code = isset($_POST['2fa_code']) ? sanitize_text_field($_POST['2fa_code']) : '';
        if (empty($code)) {
            return new WP_Error('2fa_missing_code', __('Por favor introduce el código TOTP.', 'wp-2fa-authenticator'));
        }

        $totp = TOTP::create($secret);

        if (!$totp->verify($code)) {
            return new WP_Error('2fa_invalid_code', __('El código TOTP es incorrecto.', 'wp-2fa-authenticator'));
        }

        return $user;
    }
}
WP2FA_TOTP::init();
