<?php
/**
 * WP Multi – Modul: Benutzer für Kommentare sperren
 *
 * Automatisch aus wp-multi.php ausgelagert. Wird über den Loader in
 * wp-multi.php eingebunden (nur wenn das WP Multi Toolkit aktiv ist).
 */

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

/*
 * User Kommentar Blocken
 */

function wp_multi_create_blocked_users_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'blocked_users';
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        username varchar(100) DEFAULT '' NOT NULL,
        email varchar(100) DEFAULT '' NOT NULL,
        ip_address varchar(45) DEFAULT '' NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
}

function wp_multi_activate() {
    wp_multi_create_blocked_users_table();
}

register_activation_hook( WP_MULTI_FILE, 'wp_multi_activate' );

function wp_multi_block_user($username = '', $email = '', $ip_address = '') {
    global $wpdb;
    if (empty($username) && empty($email) && empty($ip_address)) {
        return false;
    }
    $result = $wpdb->insert(
        $wpdb->prefix . 'blocked_users',
        [
            'username' => $username,
            'email' => $email,
            'ip_address' => $ip_address
        ]
    );
    return $result !== false;
}

function wp_multi_delete_blocked_user($id) {
    global $wpdb;
    return $wpdb->delete($wpdb->prefix . 'blocked_users', ['id' => $id], ['%d']);
}

// Der Menüpunkt "Gesperrte Benutzer" wird zentral in wp_multi_register_admin_menus() registriert.

function wp_multi_blocked_users_page() {
    global $wpdb;

    $notices = array();

    if (isset($_POST['block_username']) || isset($_POST['block_email']) || isset($_POST['block_ip'])) {
        check_admin_referer('wp_multi_block_user');
        $username = sanitize_text_field($_POST['block_username']);
        $email = sanitize_email($_POST['block_email']);
        $ip_address = sanitize_text_field($_POST['block_ip']);
        if (wp_multi_block_user($username, $email, $ip_address)) {
            $notices[] = array('success', __('Benutzer wurde gesperrt!', 'wp-multi'));
        } else {
            $notices[] = array('error', __('Fehler beim Sperren des Benutzers!', 'wp-multi'));
        }
    }

    if (isset($_GET['delete']) && isset($_GET['_wpnonce'])) {
        if (wp_verify_nonce($_GET['_wpnonce'], 'wp_multi_delete_user_' . $_GET['delete'])) {
            $user_id = intval($_GET['delete']);
            if ($user_id > 0 && wp_multi_delete_blocked_user($user_id)) {
                $notices[] = array('success', __('Benutzer wurde gelöscht!', 'wp-multi'));
            } else {
                $notices[] = array('error', __('Fehler beim Löschen des Benutzers!', 'wp-multi'));
            }
        }
    }

    $search_query = '';
    if (isset($_GET['search'])) {
        $search_query = sanitize_text_field($_GET['search']);
    }

    $blocked_users = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}blocked_users WHERE username LIKE %s OR email LIKE %s OR ip_address LIKE %s",
        '%' . $search_query . '%', '%' . $search_query . '%', '%' . $search_query . '%'
    ));

    wpmt_admin_page_open(
        __('Gesperrte Benutzer', 'wp-multi'),
        __('Benutzer per Name, E-Mail oder IP von Kommentaren ausschließen', 'wp-multi')
    );

    foreach ($notices as $notice) {
        wpmt_admin_notice($notice[0], $notice[1]);
    }

    echo '<div class="wpm-grid wpm-grid--2">';

    wpmt_admin_card_open(__('Benutzer sperren', 'wp-multi'));
    ?>
        <form method="post">
            <?php wp_nonce_field('wp_multi_block_user'); ?>
            <div class="wpm-field">
                <label class="wpm-field__label"><?php _e('Benutzername', 'wp-multi'); ?></label>
                <input type="text" name="block_username" placeholder="Benutzername">
            </div>
            <div class="wpm-field">
                <label class="wpm-field__label"><?php _e('E-Mail-Adresse', 'wp-multi'); ?></label>
                <input type="email" name="block_email" placeholder="E-Mail-Adresse">
            </div>
            <div class="wpm-field">
                <label class="wpm-field__label"><?php _e('IP-Adresse', 'wp-multi'); ?></label>
                <input type="text" name="block_ip" placeholder="IP-Adresse">
            </div>
            <p><input type="submit" class="wpm-btn wpm-btn--primary" value="<?php esc_attr_e('Benutzer sperren', 'wp-multi'); ?>"></p>
        </form>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_card_open(__('Suchen', 'wp-multi'));
    ?>
        <form method="get">
            <input type="hidden" name="page" value="wp-multi-blocked-users">
            <div class="wpm-field">
                <label class="wpm-field__label"><?php _e('Suchbegriff', 'wp-multi'); ?></label>
                <input type="text" name="search" value="<?php echo esc_attr($search_query); ?>" placeholder="<?php esc_attr_e('Benutzername, E-Mail oder IP', 'wp-multi'); ?>">
            </div>
            <p><input type="submit" class="wpm-btn" value="<?php esc_attr_e('Suchen', 'wp-multi'); ?>"></p>
        </form>
    <?php
    wpmt_admin_card_close();

    echo '</div>';

    wpmt_admin_card_open(__('Gesperrte Benutzer', 'wp-multi'));
    ?>
        <div class="wpm-table-wrap">
        <table class="wpm-table">
            <thead>
                <tr>
                    <th><?php _e('Benutzername', 'wp-multi'); ?></th>
                    <th><?php _e('E-Mail-Adresse', 'wp-multi'); ?></th>
                    <th><?php _e('IP-Adresse', 'wp-multi'); ?></th>
                    <th><?php _e('Aktionen', 'wp-multi'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if ($blocked_users) : ?>
                    <?php foreach ($blocked_users as $user) : ?>
                        <tr>
                            <td><?php echo esc_html($user->username); ?></td>
                            <td><?php echo esc_html($user->email); ?></td>
                            <td><?php echo esc_html($user->ip_address); ?></td>
                            <td>
                                <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=wp-multi-blocked-users&delete=' . $user->id), 'wp_multi_delete_user_' . $user->id)); ?>" class="wpm-btn wpm-btn--danger"><?php _e('Löschen', 'wp-multi'); ?></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                        <td colspan="4"><?php _e('Keine gesperrten Benutzer gefunden.', 'wp-multi'); ?></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
        </div>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}

function wp_multi_check_blocked_user($commentdata) {
    global $wpdb;
    $username = isset($commentdata['comment_author']) ? $commentdata['comment_author'] : '';
    $email = isset($commentdata['comment_author_email']) ? $commentdata['comment_author_email'] : '';
    $ip_address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    $blocked_user = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}blocked_users WHERE username = %s OR email = %s OR ip_address = %s",
        $username, $email, $ip_address
    ));
    if ($blocked_user) {
        wp_die('Ihr Kommentar konnte nicht abgesendet werden, da Sie gesperrt sind. Bitte wenden Sie sich an den Support.');
    }
    return $commentdata;
}
add_filter('preprocess_comment', 'wp_multi_check_blocked_user');


