<?php
// IV1 WP Tools – Security: 2FA (TOTP)
defined('ABSPATH') || exit;

// GoogleAuthenticator-Bibliothek laden (im lib/-Ordner)
$ga_lib = __DIR__ . '/../lib/GoogleAuthenticator.php';
if (file_exists($ga_lib)) {
    require_once $ga_lib;
}

function iv1wpt_2fa_defaults(): array {
    return [
        'enabled'      => false,
        'timeout'      => 43200, // 12 Stunden
        'exempt_users' => '',
    ];
}

// ────────────────────────────────────────────────
// Secret beim ersten Admin-Login generieren
// ────────────────────────────────────────────────
add_action('wp_login', function ($user_login, $user) {
    $opts = get_option('iv1wpt_2fa_settings', iv1wpt_2fa_defaults());
    if (empty($opts['enabled']) || !user_can($user, 'manage_options')) return;
    if (!class_exists('PHPGangsta_GoogleAuthenticator')) return;

    // Ausgenommene Benutzer prüfen
    $exempt = array_filter(array_map('trim', explode("\n", $opts['exempt_users'] ?? '')));
    if (in_array(strtolower($user->user_login), array_map('strtolower', $exempt), true)) return;

    $secret = get_user_meta($user->ID, 'admin_2fa_secret', true);
    if (!$secret) {
        $ga = new PHPGangsta_GoogleAuthenticator();
        $secret = $ga->createSecret(32);
        update_user_meta($user->ID, 'admin_2fa_secret', $secret);
        update_user_meta($user->ID, 'admin_2fa_new_secret_shown', time());
    }
}, 10, 2);

// ────────────────────────────────────────────────
// 2FA-Prüfung & Formular im Admin
// ────────────────────────────────────────────────
add_action('admin_init', function () {
    $opts = get_option('iv1wpt_2fa_settings', iv1wpt_2fa_defaults());
    if (empty($opts['enabled'])) return;
    if (!is_user_logged_in() || wp_doing_ajax() || wp_doing_cron()) return;
    if (defined('REST_REQUEST') && REST_REQUEST) return;
    if (!class_exists('PHPGangsta_GoogleAuthenticator')) return;

    $user = wp_get_current_user();
    if (!user_can($user, 'manage_options')) return;

    // Ausgenommene Benutzer
    $exempt = array_filter(array_map('trim', explode("\n", $opts['exempt_users'] ?? '')));
    if (in_array(strtolower($user->user_login), array_map('strtolower', $exempt), true)) return;

    // Bypass-Filter
    if (apply_filters('admin_2fa_bypass', false, $user)) return;

    // Timeout prüfen
    $timeout = (int) ($opts['timeout'] ?? 43200);
    $last_verified = (int) get_user_meta($user->ID, 'admin_2fa_last_verified', true);
    if ($last_verified >= time() - $timeout) return;

    // Code wurde gesendet → prüfen
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_2fa_code'], $_POST['_wpnonce'])) {
        if (wp_verify_nonce($_POST['_wpnonce'], 'admin_2fa_verify_' . $user->ID)) {
            $ga     = new PHPGangsta_GoogleAuthenticator();
            $secret = get_user_meta($user->ID, 'admin_2fa_secret', true);
            $code   = trim((string) $_POST['admin_2fa_code']);

            if ($secret && $ga->verifyCode($secret, $code, 2)) {
                update_user_meta($user->ID, 'admin_2fa_last_verified', time());
                delete_user_meta($user->ID, 'admin_2fa_new_secret_shown');
                wp_safe_redirect(admin_url());
                exit;
            }
        }
    }

    // 2FA-Formular anzeigen
    nocache_headers();
    status_header(403);
    $error      = isset($_POST['admin_2fa_code']) ? '❌ Falscher oder abgelaufener Code.' : '';
    $show_qr    = (int) get_user_meta($user->ID, 'admin_2fa_new_secret_shown', true) > 0;
    $new_secret = $show_qr ? get_user_meta($user->ID, 'admin_2fa_secret', true) : '';
    $site_name  = get_bloginfo('name');
    if ($show_qr && $new_secret) {
        $ga = new PHPGangsta_GoogleAuthenticator();
        $qr_url = $ga->getQRCodeGoogleUrl($site_name, $new_secret);
    }
    ?><!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><title>2FA erforderlich</title><meta name="robots" content="noindex">
    <style>body{font-family:system-ui,sans-serif;background:#f0f2f5;margin:0;display:flex;min-height:100vh;align-items:center;justify-content:center}.container{max-width:420px;background:#fff;padding:2.5rem;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.15);text-align:center}h2{margin:0 0 1.5rem}.error{color:#d63638;font-weight:bold;margin:1rem 0}input[type=text]{width:100%;padding:.9rem;font-size:1.2rem;border:1px solid #dcdcde;border-radius:6px;box-sizing:border-box;margin:1.2rem 0;text-align:center}button{background:#2271b1;color:#fff;border:none;padding:.9rem 2rem;font-size:1.1rem;border-radius:6px;cursor:pointer}button:hover{background:#135e96}.qr{max-width:180px;margin:1.5rem auto;display:block}.secret{font-family:monospace;background:#f8f9fa;padding:.6rem 1rem;border-radius:6px;font-size:1.1rem}.info{color:#2271b1;margin:1.2rem 0}</style>
    </head><body><div class="container">
    <h2>🔐 2-Faktor-Authentifizierung</h2>
    <?php if ($error): ?><p class="error"><?php echo esc_html($error); ?></p><?php endif; ?>
    <?php if ($show_qr && $new_secret): ?>
        <p class="info">Neuer 2FA-Code – bitte sofort in deiner App speichern:</p>
        <img class="qr" src="<?php echo esc_url($qr_url); ?>" alt="QR-Code">
        <p>Geheimcode: <span class="secret"><?php echo esc_html($new_secret); ?></span></p>
    <?php endif; ?>
    <form method="post" autocomplete="off">
        <?php wp_nonce_field('admin_2fa_verify_' . $user->ID); ?>
        <input type="text" name="admin_2fa_code" placeholder="6-stelliger Code" inputmode="numeric" pattern="[0-9]{6}" required autofocus>
        <br><br><button type="submit">Code bestätigen</button>
    </form>
    </div></body></html><?php
    exit;
}, 8);

// ────────────────────────────────────────────────
// QR-Code im Benutzerprofil
// ────────────────────────────────────────────────
add_action('show_user_profile', 'iv1wpt_2fa_profile_section');
add_action('edit_user_profile', 'iv1wpt_2fa_profile_section');
function iv1wpt_2fa_profile_section($user): void {
    if (!user_can($user, 'manage_options')) return;
    $secret = get_user_meta($user->ID, 'admin_2fa_secret', true);
    if (!$secret || !class_exists('PHPGangsta_GoogleAuthenticator')) return;

    $ga = new PHPGangsta_GoogleAuthenticator();
    $qr_url = $ga->getQRCodeGoogleUrl(get_bloginfo('name'), $secret);
    $last = (int) get_user_meta($user->ID, 'admin_2fa_last_verified', true);
    ?>
    <h2>🔐 Zwei-Faktor-Authentifizierung (2FA)</h2>
    <table class="form-table">
        <tr><th>QR-Code</th><td><img src="<?php echo esc_url($qr_url); ?>" alt="QR" style="max-width:200px"></td></tr>
        <tr><th>Geheimcode</th><td><code style="font-size:1.2em;letter-spacing:1px"><?php echo esc_html($secret); ?></code></td></tr>
        <tr><th>Status</th><td><?php echo $last > 0 ? 'Zuletzt: ' . wp_date('d.m.Y H:i', $last) : 'Noch nie verifiziert'; ?></td></tr>
    </table>
    <?php
}

// ────────────────────────────────────────────────
// AJAX: 2FA-Einstellungen speichern
// ────────────────────────────────────────────────
add_action('wp_ajax_iv1wpt_2fa_save', 'iv1wpt_2fa_save_ajax');
function iv1wpt_2fa_save_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(__('No permission.', 'iv1-wp-tools'));

    $opts = [
        'enabled'      => (isset($_POST['enabled']) && $_POST['enabled'] === '1'),
        'timeout'      => absint($_POST['timeout'] ?? 43200),
        'exempt_users' => sanitize_textarea_field($_POST['exempt_users'] ?? ''),
    ];
    update_option('iv1wpt_2fa_settings', $opts);
    //wp_send_json_success('2FA-Einstellungen gespeichert.');
	
    $current_user = wp_get_current_user();
    $current_login = $current_user->user_login ?? '';
    $current_user_id = get_current_user_id();

    $exempt_users = array_filter(array_map(
        'trim',
        preg_split('/\r\n|\r|\n/', $opts['exempt_users'])
    ));

    $is_exempt = in_array($current_login, $exempt_users, true);

    $has_2fa_secret = !empty(get_user_meta($current_user_id, 'admin_2fa_secret', true));

    if ($opts['enabled'] && !$is_exempt && !$has_2fa_secret) {
        wp_logout();

        wp_send_json_success([
            'message'  => '2FA-Einstellungen gespeichert. Bitte melde dich erneut an und richte 2FA ein.',
            'redirect' => wp_login_url(admin_url('admin.php?page=iv1-wp-tools&tab=security')),
        ]);
    }

    wp_send_json_success([
        'message' => '2FA-Einstellungen gespeichert.',
    ]);	
	
	
}

// ────────────────────────────────────────────────
// AJAX: 2FA-Secret für einen Benutzer zurücksetzen
// ────────────────────────────────────────────────
add_action('wp_ajax_iv1wpt_2fa_reset', 'iv1wpt_2fa_reset_ajax');
function iv1wpt_2fa_reset_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) wp_send_json_error(__('No permission.', 'iv1-wp-tools'));

    $user_id = absint($_POST['user_id'] ?? 0);
    if ($user_id === 0) wp_send_json_error('Ungültige User-ID.');

    delete_user_meta($user_id, 'admin_2fa_secret');
    delete_user_meta($user_id, 'admin_2fa_last_verified');
    delete_user_meta($user_id, 'admin_2fa_new_secret_shown');

    $user = get_user_by('ID', $user_id);
    iv1wpt_plugin_log('IV1WPT 2FA: Secret zurückgesetzt für ' . ($user ? $user->user_login : 'User #' . $user_id));
    wp_send_json_success('2FA-Secret zurückgesetzt für ' . ($user ? $user->display_name : 'User #' . $user_id));
}
